@zharp/cli 0.2.0 → 0.3.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 +94 -94
- package/dist/cli.js +884 -128
- package/dist/cli.js.map +1 -1
- package/dist/index.d.mts +13 -2
- package/dist/index.d.ts +13 -2
- package/dist/index.js +191 -44
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +181 -34
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/api.ts","../src/log.ts","../src/native.ts","../src/elf.ts","../src/files.ts","../src/macho.ts","../src/sourcemaps.ts","../src/debug-id.ts","../src/version.ts","../src/init/index.ts","../src/init/connect.ts","../src/init/detect.ts","../src/init/recipes.ts"],"sourcesContent":["#!/usr/bin/env node\r\n/**\r\n * `zharp` — upload what Zharp needs to turn minified and obfuscated stacks back into source.\r\n */\r\nimport { parseArgs } from 'node:util';\r\nimport { existsSync } from 'node:fs';\r\nimport { resolveConnection, UploadError, type Connection } from './api';\r\nimport { consoleLogger } from './log';\r\nimport { uploadDartSymbols, uploadDsyms, uploadProguard } from './native';\r\nimport { injectDirectory, uploadSourcemaps } from './sourcemaps';\r\nimport { VERSION } from './version';\r\nimport { runInit } from './init';\r\n\r\nconst HELP = `zharp ${VERSION} — readable stack traces for Zharp\r\n\r\nUsage:\r\n zharp init Connect this project to Zharp and set it up\r\n [--yes] [--dry-run] (signs in through the browser)\r\n zharp sourcemaps inject <dir> Add debug IDs to JS files and their maps\r\n zharp sourcemaps upload <dir> --app <id> Upload JS files and their maps\r\n [--release <r>] [--delete-after]\r\n zharp proguard upload <mapping.txt> --app <id> --uuid <uuid>\r\n zharp dart-symbols upload <dir> --app <id> Flutter --split-debug-info output\r\n [--obfuscation-map <file>] (and its obfuscation map)\r\n zharp dsym upload <path> --app <id> A .dSYM, or a folder of them\r\n\r\nOptions:\r\n --app <id> Application ID (or ZHARP_APP)\r\n --release <r> Release name to file the upload under (or ZHARP_RELEASE)\r\n --include <glob> Only these files (repeatable; sourcemaps)\r\n --exclude <glob> Not these files (repeatable; sourcemaps)\r\n --delete-after Delete .map files after uploading them\r\n --dry-run Show what would happen; change and send nothing\r\n --url <url> Zharp API (default ZHARP_URL or https://api.zharp.io)\r\n -h, --help, -v, --version\r\n\r\nEnvironment:\r\n ZHARP_AUTH_TOKEN A workspace API key with the \"artifacts:write\" scope (required to upload)\r\n ZHARP_URL The Zharp API, default https://api.zharp.io\r\n`;\r\n\r\nclass UsageError extends Error {}\r\n\r\nfunction fail(message: string): never {\r\n throw new UsageError(message);\r\n}\r\n\r\nasync function main(argv: string[]): Promise<void> {\r\n const { values, positionals } = parseArgs({\r\n args: argv,\r\n allowPositionals: true,\r\n options: {\r\n app: { type: 'string' },\r\n release: { type: 'string' },\r\n uuid: { type: 'string' },\r\n 'obfuscation-map': { type: 'string' },\r\n include: { type: 'string', multiple: true },\r\n exclude: { type: 'string', multiple: true },\r\n 'delete-after': { type: 'boolean' },\r\n 'dry-run': { type: 'boolean' },\r\n yes: { type: 'boolean', short: 'y' },\r\n tarballs: { type: 'string' },\r\n url: { type: 'string' },\r\n help: { type: 'boolean', short: 'h' },\r\n version: { type: 'boolean', short: 'v' },\r\n },\r\n });\r\n if (values.version) {\r\n console.log(VERSION);\r\n return;\r\n }\r\n const [group, command, target] = positionals;\r\n if (values.help || !group) {\r\n console.log(HELP);\r\n return;\r\n }\r\n if (group === 'init') {\r\n process.exitCode = await runInit({ url: values.url, yes: values.yes === true, dryRun: values['dry-run'] === true, tarballs: values.tarballs, dir: command });\r\n return;\r\n }\r\n const logger = consoleLogger();\r\n const dryRun = values['dry-run'] === true;\r\n const release = values.release ?? process.env.ZHARP_RELEASE;\r\n const needTarget = (what: string) => {\r\n if (!target) fail(`${group} ${command} needs ${what}. See \\`zharp --help\\`.`);\r\n if (!existsSync(target)) fail(`${target} does not exist.`);\r\n return target;\r\n };\r\n const connect = (): Connection | null => (dryRun ? null : resolveConnection({ app: values.app, url: values.url }));\r\n\r\n switch (`${group} ${command}`) {\r\n case 'sourcemaps inject': {\r\n const dir = needTarget('a directory');\r\n const files = injectDirectory(dir, { include: values.include, exclude: values.exclude, dryRun, logger });\r\n logger.info(`${dryRun ? 'Would inject' : 'Injected'} debug IDs into ${files.filter((f) => f.changed).length} file(s); ${files.filter((f) => !f.changed).length} already had one.`);\r\n return;\r\n }\r\n case 'sourcemaps upload': {\r\n const dir = needTarget('a directory');\r\n const connection = connect();\r\n const result = await uploadSourcemaps(dir, connection, {\r\n release,\r\n include: values.include,\r\n exclude: values.exclude,\r\n deleteAfter: values['delete-after'] === true,\r\n dryRun,\r\n logger,\r\n });\r\n if (result.files === 0) process.exitCode = 1;\r\n return;\r\n }\r\n case 'proguard upload': {\r\n const file = needTarget('the mapping.txt file');\r\n if (!values.uuid) fail('proguard upload needs --uuid <uuid>: the build UUID the Zharp Gradle plugin put into the app.');\r\n await uploadProguard(file, values.uuid, connect(), { release, dryRun, logger });\r\n return;\r\n }\r\n case 'dart-symbols upload': {\r\n await uploadDartSymbols(needTarget('the --split-debug-info directory'), connect(), { release, dryRun, logger, obfuscationMap: values['obfuscation-map'] });\r\n return;\r\n }\r\n case 'dsym upload': {\r\n await uploadDsyms(needTarget('a .dSYM bundle or a folder of them'), connect(), { release, dryRun, logger });\r\n return;\r\n }\r\n default:\r\n fail(`Unknown command \"${positionals.join(' ')}\". See \\`zharp --help\\`.`);\r\n }\r\n}\r\n\r\n// Errors set the exit code rather than calling process.exit(): uploads still in flight finish\r\n// (or fail) cleanly first.\r\nmain(process.argv.slice(2)).catch((error) => {\r\n console.error(`[zharp] error: ${error instanceof UsageError || error instanceof UploadError || error instanceof Error ? error.message : String(error)}`);\r\n process.exitCode = 1;\r\n});\r\n","/**\r\n * The artifact upload API: `POST /api/v1/applications/:id/artifacts`, multipart, with a\r\n * workspace API key that has the `artifacts:write` scope.\r\n */\r\nimport { gzipSync } from 'node:zlib';\r\n\r\nexport const DEFAULT_URL = 'https://api.zharp.io';\r\n\r\nexport type ArtifactKind = 'sourcemap' | 'minified-source' | 'proguard' | 'dart-symbols' | 'dart-obfuscation-map' | 'dsym';\r\n\r\nexport interface Connection {\r\n /** The Zharp API's base URL, e.g. https://api.zharp.io. */\r\n url: string;\r\n /** A workspace API key with the `artifacts:write` scope. */\r\n authToken: string;\r\n /** The application's ID, as in the dashboard URL. */\r\n app: string | number;\r\n}\r\n\r\nexport interface Artifact {\r\n kind: ArtifactKind;\r\n debugId: string;\r\n /** The file's path or URL (JS), or file name. */\r\n name: string;\r\n release?: string;\r\n arch?: string;\r\n data: Uint8Array;\r\n /** Send gzipped (large native symbol files). */\r\n gzip?: boolean;\r\n}\r\n\r\nexport class UploadError extends Error {\r\n constructor(\r\n message: string,\r\n readonly status?: number,\r\n /** Retrying will not help: a rejected key, a missing app, a bad request. */\r\n readonly permanent = false,\r\n ) {\r\n super(message);\r\n this.name = 'UploadError';\r\n }\r\n}\r\n\r\n/**\r\n * The connection from options and the environment (`ZHARP_AUTH_TOKEN`, `ZHARP_URL`,\r\n * `ZHARP_APP`). Throws with what is missing.\r\n */\r\nexport function resolveConnection(options: { url?: string; authToken?: string; app?: string | number }): Connection {\r\n const authToken = options.authToken || process.env.ZHARP_AUTH_TOKEN;\r\n const app = options.app ?? process.env.ZHARP_APP;\r\n const missing: string[] = [];\r\n if (!authToken) missing.push('an auth token (ZHARP_AUTH_TOKEN, or the authToken option): a workspace API key with the \"artifacts:write\" scope');\r\n if (app === undefined || app === '') missing.push('the application ID (--app, the app option, or ZHARP_APP)');\r\n if (missing.length) throw new UploadError(`Cannot upload without ${missing.join(' and ')}.`, undefined, true);\r\n return { url: (options.url || process.env.ZHARP_URL || DEFAULT_URL).replace(/\\/+$/, ''), authToken: authToken!, app: app! };\r\n}\r\n\r\nexport function artifactsUrl(connection: Connection): string {\r\n return `${connection.url}/api/v1/applications/${encodeURIComponent(String(connection.app))}/artifacts`;\r\n}\r\n\r\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\r\n\r\n/** Upload one artifact, retrying network failures, 408, 429 and 5xx with backoff. */\r\nexport async function uploadArtifact(\r\n connection: Connection,\r\n artifact: Artifact,\r\n options: { retries?: number; fetch?: typeof fetch; backoffMs?: number } = {},\r\n): Promise<unknown> {\r\n const doFetch = options.fetch ?? fetch;\r\n const retries = options.retries ?? 3;\r\n const backoff = options.backoffMs ?? 1000;\r\n const fileName = (artifact.name.split('/').pop() || 'artifact') + (artifact.gzip ? '.gz' : '');\r\n const payload = artifact.gzip ? gzipSync(artifact.data) : artifact.data;\r\n\r\n for (let attempt = 0; ; attempt++) {\r\n // A fresh body per attempt: a FormData is consumed by the request that sends it.\r\n const form = new FormData();\r\n form.set('kind', artifact.kind);\r\n form.set('debugId', artifact.debugId);\r\n form.set('name', artifact.name);\r\n if (artifact.release) form.set('release', artifact.release);\r\n if (artifact.arch) form.set('arch', artifact.arch);\r\n const type = artifact.gzip ? 'application/gzip' : artifact.kind === 'sourcemap' ? 'application/json' : 'application/octet-stream';\r\n form.set('file', new Blob([payload as Uint8Array<ArrayBuffer>], { type }), fileName);\r\n\r\n let retryAfter = 0;\r\n let error: UploadError;\r\n try {\r\n const response = await doFetch(artifactsUrl(connection), {\r\n method: 'POST',\r\n headers: { Authorization: `Bearer ${connection.authToken}`, 'User-Agent': 'zharp-cli' },\r\n body: form,\r\n });\r\n const text = await response.text().catch(() => '');\r\n if (response.ok) {\r\n try {\r\n return text ? JSON.parse(text) : null;\r\n } catch {\r\n return text;\r\n }\r\n }\r\n error = describeFailure(response.status, text, connection);\r\n retryAfter = Number(response.headers.get('retry-after')) * 1000 || 0;\r\n } catch (cause) {\r\n error = new UploadError(`Could not reach ${connection.url}: ${(cause as Error)?.message ?? cause}`);\r\n }\r\n if (error.permanent || attempt >= retries) throw error;\r\n await sleep(Math.max(retryAfter, backoff * 2 ** attempt));\r\n }\r\n}\r\n\r\nfunction serverMessage(text: string): string {\r\n try {\r\n const body = JSON.parse(text);\r\n const message = body?.message ?? body?.error;\r\n if (typeof message === 'string') return message;\r\n if (Array.isArray(message)) return message.join('; ');\r\n } catch {}\r\n return text.slice(0, 300);\r\n}\r\n\r\nfunction describeFailure(status: number, text: string, connection: Connection): UploadError {\r\n const detail = serverMessage(text);\r\n const retryable = status === 408 || status === 429 || status >= 500;\r\n const explain: Record<number, string> = {\r\n 401: 'The auth token was rejected — check ZHARP_AUTH_TOKEN (a workspace API key, not the app key).',\r\n 403: 'The API key cannot upload here — it needs the \"artifacts:write\" scope, in the workspace that owns the app.',\r\n 404: `Application ${connection.app} was not found — check --app (the ID in the app's dashboard URL) and ZHARP_URL.`,\r\n 413: 'The file is larger than the server accepts.',\r\n };\r\n const message = `${explain[status] ?? `Upload failed with HTTP ${status}.`}${detail ? ` Server said: ${detail}` : ''}`;\r\n return new UploadError(message, status, !retryable);\r\n}\r\n\r\n/** Run `fn` over `items`, `limit` at a time. Stops at the first error. */\r\nexport async function eachLimit<T>(items: T[], limit: number, fn: (item: T, index: number) => Promise<void>): Promise<void> {\r\n let next = 0;\r\n let failed: unknown;\r\n const worker = async () => {\r\n while (failed === undefined && next < items.length) {\r\n const index = next++;\r\n try {\r\n await fn(items[index], index);\r\n } catch (error) {\r\n failed ??= error;\r\n }\r\n }\r\n };\r\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\r\n if (failed !== undefined) throw failed;\r\n}\r\n","/** Where progress goes. The CLI prints it; the bundler plugins prefix it with their name. */\r\nexport interface Logger {\r\n info(message: string): void;\r\n warn(message: string): void;\r\n}\r\n\r\nexport const consoleLogger = (prefix = '[zharp]'): Logger => ({\r\n info: (message) => console.log(`${prefix} ${message}`),\r\n warn: (message) => console.warn(`${prefix} ${message}`),\r\n});\r\n\r\nexport const silentLogger: Logger = { info() {}, warn() {} };\r\n","/**\r\n * Mobile symbol files: R8/ProGuard mappings (Android), Dart symbol files (Flutter\r\n * `--split-debug-info`) and dSYMs (iOS). Each is uploaded gzipped, keyed by the ID its platform's\r\n * errors carry.\r\n */\r\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\r\nimport { basename, dirname, join, resolve } from 'node:path';\r\nimport { eachLimit, uploadArtifact, type Artifact, type Connection } from './api';\r\nimport { readElf, isElf } from './elf';\r\nimport { formatBytes, walk } from './files';\r\nimport { consoleLogger, type Logger } from './log';\r\nimport { isMachO, readMachO } from './macho';\r\n\r\nexport interface NativeUploadOptions {\r\n release?: string;\r\n dryRun?: boolean;\r\n logger?: Logger;\r\n fetch?: typeof fetch;\r\n retries?: number;\r\n}\r\n\r\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\r\n\r\nasync function send(connection: Connection | null, artifacts: Artifact[], options: NativeUploadOptions): Promise<Artifact[]> {\r\n const logger = options.logger ?? consoleLogger();\r\n let done = 0;\r\n await eachLimit(artifacts, 2, async (artifact) => {\r\n if (!options.dryRun) {\r\n if (!connection) throw new Error('No connection to upload to.');\r\n await uploadArtifact(connection, artifact, { fetch: options.fetch, retries: options.retries });\r\n }\r\n done += 1;\r\n const extra = artifact.arch ? ` ${artifact.arch}` : '';\r\n logger.info(` [${done}/${artifacts.length}] ${options.dryRun ? 'would upload' : 'uploaded'} ${artifact.kind} ${artifact.name}${extra} (${formatBytes(artifact.data.length)}) ${artifact.debugId}`);\r\n });\r\n return artifacts;\r\n}\r\n\r\n// ── Android ──────────────────────────────────────────────────────────────────\r\n\r\n/** Upload an R8/ProGuard `mapping.txt` under the build's UUID (the one the Gradle plugin put in the app). */\r\nexport async function uploadProguard(mappingFile: string, uuid: string, connection: Connection | null, options: NativeUploadOptions = {}) {\r\n if (!UUID.test(uuid)) throw new Error(`--uuid must be a UUID, got \"${uuid}\".`);\r\n const data = readFileSync(mappingFile);\r\n return send(connection, [{ kind: 'proguard', debugId: uuid.toLowerCase(), name: basename(mappingFile), release: options.release, data, gzip: true }], options);\r\n}\r\n\r\n// ── Flutter ──────────────────────────────────────────────────────────────────\r\n\r\nexport interface DartSymbolFile {\r\n path: string;\r\n buildId: string;\r\n os?: string;\r\n arch?: string;\r\n}\r\n\r\nconst DART_ARCH: Record<string, string> = { x86_64: 'x64', x86: 'ia32' };\r\n\r\n/**\r\n * The Dart symbol files in a `--split-debug-info` directory (`app.android-arm64.symbols`, …), or\r\n * the one file given. The debug ID is the ELF GNU build ID — the `build_id` an obfuscated\r\n * stack prints.\r\n */\r\nexport function findDartSymbols(path: string, logger: Logger = consoleLogger()): DartSymbolFile[] {\r\n const files = statSync(path).isDirectory() ? walk(resolve(path)) : [resolve(path)];\r\n const out: DartSymbolFile[] = [];\r\n for (const file of files) {\r\n const named = /\\.symbols$/.test(file);\r\n const data = readFileSync(file);\r\n if (!isElf(data)) {\r\n if (named) logger.warn(`Skipped ${basename(file)}: not an ELF file.`);\r\n continue;\r\n }\r\n const elf = readElf(data);\r\n if (!elf.buildId) {\r\n logger.warn(`Skipped ${basename(file)}: it has no GNU build ID.`);\r\n continue;\r\n }\r\n const match = /\\.([a-z]+)-([a-z0-9_]+)\\.symbols$/.exec(basename(file));\r\n out.push({ path: file, buildId: elf.buildId, os: match?.[1], arch: match?.[2] ?? (elf.arch && (DART_ARCH[elf.arch] ?? elf.arch)) });\r\n }\r\n return out;\r\n}\r\n\r\n/**\r\n * The obfuscation map Flutter writes with\r\n * `--extra-gen-snapshot-options=--save-obfuscation-map=<file>`: `obfuscation.json` or\r\n * `*.obfuscation.json`, in the symbols directory or the directory next to it.\r\n */\r\nexport function findObfuscationMap(symbolsPath: string): string | undefined {\r\n const dir = statSync(symbolsPath).isDirectory() ? resolve(symbolsPath) : dirname(resolve(symbolsPath));\r\n for (const where of [dir, dirname(dir)]) {\r\n let names: string[];\r\n try {\r\n names = readdirSync(where).sort();\r\n } catch {\r\n continue;\r\n }\r\n const found = names.find((n) => n === 'obfuscation.json') ?? names.find((n) => n.endsWith('.obfuscation.json'));\r\n if (found && statSync(join(where, found)).isFile()) return join(where, found);\r\n }\r\n return undefined;\r\n}\r\n\r\n/** The map's contents, checked: a JSON array of obfuscated/original name pairs (flat or nested). */\r\nfunction readObfuscationMap(file: string): Buffer {\r\n const data = readFileSync(file);\r\n let parsed: unknown;\r\n try {\r\n parsed = JSON.parse(data.toString('utf8'));\r\n } catch (error) {\r\n throw new Error(`${file} is not valid JSON (${(error as Error).message}).`);\r\n }\r\n if (!Array.isArray(parsed)) throw new Error(`${file} is not a Dart obfuscation map: expected a JSON array of [obfuscated, original] names.`);\r\n return data;\r\n}\r\n\r\nexport interface DartSymbolsUploadOptions extends NativeUploadOptions {\r\n /** The obfuscation map to upload with the symbols. Default: found next to them (see findObfuscationMap). */\r\n obfuscationMap?: string;\r\n}\r\n\r\nexport async function uploadDartSymbols(path: string, connection: Connection | null, options: DartSymbolsUploadOptions = {}) {\r\n const logger = options.logger ?? consoleLogger();\r\n const files = findDartSymbols(path, logger);\r\n if (files.length === 0) throw new Error(`No Dart symbol files in ${path} — build with \\`flutter build … --obfuscate --split-debug-info=<dir>\\` and pass that directory.`);\r\n logger.info(`${options.dryRun ? 'Would upload' : 'Uploading'} ${files.length} Dart symbol file(s)`);\r\n const artifacts: Artifact[] = files.map((f) => ({\r\n kind: 'dart-symbols',\r\n debugId: f.buildId,\r\n name: basename(f.path),\r\n arch: f.arch,\r\n release: options.release,\r\n data: readFileSync(f.path),\r\n gzip: true,\r\n }));\r\n if (options.obfuscationMap && !existsSync(options.obfuscationMap)) throw new Error(`${options.obfuscationMap} does not exist.`);\r\n const mapFile = options.obfuscationMap ?? findObfuscationMap(path);\r\n if (mapFile) {\r\n const data = readObfuscationMap(mapFile);\r\n // One map serves every architecture of the build: once per build ID.\r\n const buildIds = [...new Set(files.map((f) => f.buildId))];\r\n logger.info(`With obfuscation map ${basename(mapFile)} for ${buildIds.length} build ID(s)`);\r\n for (const debugId of buildIds) {\r\n artifacts.push({ kind: 'dart-obfuscation-map', debugId, name: basename(mapFile), release: options.release, data, gzip: true });\r\n }\r\n } else {\r\n logger.info('No obfuscation map found (build with --extra-gen-snapshot-options=--save-obfuscation-map=build/obfuscation.json, or pass --obfuscation-map): obfuscated names in error messages stay as they are.');\r\n }\r\n return send(connection, artifacts, options);\r\n}\r\n\r\n// ── iOS ──────────────────────────────────────────────────────────────────────\r\n\r\nexport interface DsymImage {\r\n /** The DWARF file inside the .dSYM bundle. */\r\n path: string;\r\n uuid: string;\r\n arch: string;\r\n offset: number;\r\n size: number;\r\n}\r\n\r\n/**\r\n * The binary images in a .dSYM bundle, a folder of them (Xcode's `$DWARF_DSYM_FOLDER_PATH`), or\r\n * a DWARF file itself. Universal files give one image per architecture.\r\n */\r\nexport function findDsymImages(path: string): DsymImage[] {\r\n const root = resolve(path);\r\n const candidates = statSync(root).isDirectory()\r\n ? walk(root).filter((f) => /[\\\\/]Contents[\\\\/]Resources[\\\\/]DWARF[\\\\/][^\\\\/]+$/.test(f))\r\n : [root];\r\n const out: DsymImage[] = [];\r\n for (const file of candidates) {\r\n const data = readFileSync(file);\r\n if (!isMachO(data)) continue;\r\n for (const image of readMachO(data)) out.push({ path: file, ...image });\r\n }\r\n return out;\r\n}\r\n\r\nexport async function uploadDsyms(path: string, connection: Connection | null, options: NativeUploadOptions = {}) {\r\n const logger = options.logger ?? consoleLogger();\r\n const images = findDsymImages(path);\r\n if (images.length === 0) throw new Error(`No dSYM DWARF files in ${path} — pass a .dSYM bundle or the folder that holds them ($DWARF_DSYM_FOLDER_PATH).`);\r\n logger.info(`${options.dryRun ? 'Would upload' : 'Uploading'} ${images.length} dSYM image(s)`);\r\n const cache = new Map<string, Buffer>();\r\n const artifacts: Artifact[] = images.map((image) => {\r\n let data = cache.get(image.path);\r\n if (!data) cache.set(image.path, (data = readFileSync(image.path)));\r\n return {\r\n kind: 'dsym',\r\n debugId: image.uuid,\r\n name: basename(image.path),\r\n arch: image.arch,\r\n release: options.release,\r\n // One architecture's slice of a universal file is a complete Mach-O file on its own.\r\n data: data.subarray(image.offset, image.offset + image.size),\r\n gzip: true,\r\n };\r\n });\r\n return send(connection, artifacts, options);\r\n}\r\n","/**\r\n * The GNU build ID of an ELF file — what a Dart AOT snapshot prints as `build_id: '…'` in an\r\n * obfuscated stack, and what its `--split-debug-info` symbol file carries too.\r\n */\r\n\r\nconst NT_GNU_BUILD_ID = 3;\r\nconst SHT_NOTE = 7;\r\nconst PT_NOTE = 4;\r\n\r\nexport interface ElfInfo {\r\n /** Lowercase hex, as Dart prints it. */\r\n buildId?: string;\r\n bits: 32 | 64;\r\n littleEndian: boolean;\r\n /** e_machine, as an architecture name where known. */\r\n arch?: string;\r\n}\r\n\r\nconst MACHINES: Record<number, string> = { 3: 'x86', 40: 'arm', 62: 'x86_64', 183: 'arm64', 243: 'riscv64' };\r\n\r\nexport function isElf(data: Uint8Array): boolean {\r\n return data.length >= 16 && data[0] === 0x7f && data[1] === 0x45 && data[2] === 0x4c && data[3] === 0x46;\r\n}\r\n\r\n/** Parse just enough of an ELF file to find its GNU build ID. Throws on a file that is not ELF. */\r\nexport function readElf(data: Uint8Array): ElfInfo {\r\n if (!isElf(data)) throw new Error('not an ELF file');\r\n const bits = data[4] === 2 ? 64 : 32;\r\n const littleEndian = data[5] !== 2;\r\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\r\n const u16 = (o: number) => view.getUint16(o, littleEndian);\r\n const u32 = (o: number) => view.getUint32(o, littleEndian);\r\n const addr = (o: number) => (bits === 64 ? Number(view.getBigUint64(o, littleEndian)) : u32(o));\r\n const info: ElfInfo = { bits, littleEndian, arch: MACHINES[u16(18)] };\r\n\r\n const notes = (offset: number, size: number): string | undefined => {\r\n let p = offset;\r\n const end = Math.min(offset + size, data.length);\r\n while (p + 12 <= end) {\r\n const nameSize = u32(p);\r\n const descSize = u32(p + 4);\r\n const type = u32(p + 8);\r\n const nameStart = p + 12;\r\n const descStart = nameStart + align4(nameSize);\r\n if (descStart + descSize > end) break;\r\n const name = String.fromCharCode(...data.subarray(nameStart, nameStart + Math.max(0, nameSize - 1)));\r\n if (name === 'GNU' && type === NT_GNU_BUILD_ID) return hex(data.subarray(descStart, descStart + descSize));\r\n p = descStart + align4(descSize);\r\n }\r\n return undefined;\r\n };\r\n\r\n // Section headers first (symbol files keep them), then program headers (stripped binaries).\r\n const shoff = addr(bits === 64 ? 0x28 : 0x20);\r\n const shentsize = u16(bits === 64 ? 0x3a : 0x2e);\r\n const shnum = u16(bits === 64 ? 0x3c : 0x30);\r\n for (let i = 0; i < shnum && shoff > 0; i++) {\r\n const h = shoff + i * shentsize;\r\n if (h + shentsize > data.length) break;\r\n if (u32(h + 4) !== SHT_NOTE) continue;\r\n const offset = addr(bits === 64 ? h + 0x18 : h + 0x10);\r\n const size = addr(bits === 64 ? h + 0x20 : h + 0x14);\r\n const id = notes(offset, size);\r\n if (id) return { ...info, buildId: id };\r\n }\r\n const phoff = addr(bits === 64 ? 0x20 : 0x1c);\r\n const phentsize = u16(bits === 64 ? 0x36 : 0x2a);\r\n const phnum = u16(bits === 64 ? 0x38 : 0x2c);\r\n for (let i = 0; i < phnum && phoff > 0; i++) {\r\n const h = phoff + i * phentsize;\r\n if (h + phentsize > data.length) break;\r\n if (u32(h) !== PT_NOTE) continue;\r\n const offset = addr(bits === 64 ? h + 0x08 : h + 0x04);\r\n const size = addr(bits === 64 ? h + 0x20 : h + 0x10);\r\n const id = notes(offset, size);\r\n if (id) return { ...info, buildId: id };\r\n }\r\n return info;\r\n}\r\n\r\nconst align4 = (n: number) => (n + 3) & ~3;\r\n\r\nfunction hex(bytes: Uint8Array): string {\r\n let out = '';\r\n for (const b of bytes) out += b.toString(16).padStart(2, '0');\r\n return out;\r\n}\r\n","/** Walking a directory, and include/exclude patterns. */\r\nimport { readdirSync, statSync } from 'node:fs';\r\nimport { join, relative, sep } from 'node:path';\r\n\r\n/** A glob (`**`, `*`, `?`), a regular expression, or a list of them. */\r\nexport type Pattern = string | RegExp | Array<string | RegExp>;\r\n\r\n/** Every file under `dir`, recursively, as absolute paths. `node_modules` is skipped. */\r\nexport function walk(dir: string): string[] {\r\n const out: string[] = [];\r\n const visit = (current: string) => {\r\n for (const entry of readdirSync(current, { withFileTypes: true })) {\r\n const full = join(current, entry.name);\r\n if (entry.isDirectory()) {\r\n if (entry.name !== 'node_modules') visit(full);\r\n } else if (entry.isFile()) out.push(full);\r\n else if (entry.isSymbolicLink()) {\r\n try {\r\n if (statSync(full).isFile()) out.push(full);\r\n } catch {}\r\n }\r\n }\r\n };\r\n visit(dir);\r\n return out.sort();\r\n}\r\n\r\n/** `path` relative to `dir`, with forward slashes. */\r\nexport function relativePath(dir: string, path: string): string {\r\n return relative(dir, path).split(sep).join('/');\r\n}\r\n\r\n/** A glob as a regular expression over a relative path with forward slashes. */\r\nexport function globToRegExp(glob: string): RegExp {\r\n let out = '';\r\n for (let i = 0; i < glob.length; i++) {\r\n const c = glob[i];\r\n if (c === '*') {\r\n if (glob[i + 1] === '*') {\r\n // `**/` matches any number of directories, including none.\r\n const slash = glob[i + 2] === '/';\r\n out += slash ? '(?:.*/)?' : '.*';\r\n i += slash ? 2 : 1;\r\n } else out += '[^/]*';\r\n } else if (c === '?') out += '[^/]';\r\n else out += /[.+^${}()|[\\]\\\\]/.test(c) ? `\\\\${c}` : c;\r\n }\r\n // A pattern without a slash matches a file name at any depth, as .gitignore does.\r\n return new RegExp(glob.includes('/') ? `^${out}$` : `(?:^|/)${out}$`);\r\n}\r\n\r\nfunction toList(pattern: Pattern | undefined): RegExp[] {\r\n if (pattern === undefined) return [];\r\n return (Array.isArray(pattern) ? pattern : [pattern]).map((p) => (typeof p === 'string' ? globToRegExp(p) : p));\r\n}\r\n\r\n/** A filter over relative paths: in `include` (when given) and not in `exclude`. */\r\nexport function pathFilter(include?: Pattern, exclude?: Pattern): (relativePath: string) => boolean {\r\n const inc = toList(include);\r\n const exc = toList(exclude);\r\n return (path) => (inc.length === 0 || inc.some((r) => r.test(path))) && !exc.some((r) => r.test(path));\r\n}\r\n\r\nexport function formatBytes(bytes: number): string {\r\n if (bytes < 1024) return `${bytes} B`;\r\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;\r\n return `${(bytes / 1024 / 1024).toFixed(1)} MB`;\r\n}\r\n","/**\r\n * The LC_UUID of each architecture in a Mach-O file (thin or universal) — the UUID an iOS crash\r\n * report lists for each binary image, and the key its dSYM is found by.\r\n */\r\n\r\nconst LC_UUID = 0x1b;\r\n\r\nexport interface MachOImage {\r\n /** Uppercase with dashes, as the iOS SDK (`UUID.uuidString`) and Apple's tools print it. */\r\n uuid: string;\r\n arch: string;\r\n /** Where the image is in the file: the whole file, or its slice of a universal one. */\r\n offset: number;\r\n size: number;\r\n}\r\n\r\nconst MH_MAGIC = 0xfeedface;\r\nconst MH_MAGIC_64 = 0xfeedfacf;\r\nconst FAT_MAGIC = 0xcafebabe;\r\nconst FAT_MAGIC_64 = 0xcafebabf;\r\n\r\nexport function isMachO(data: Uint8Array): boolean {\r\n if (data.length < 8) return false;\r\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\r\n const be = view.getUint32(0, false);\r\n const le = view.getUint32(0, true);\r\n return be === FAT_MAGIC || be === FAT_MAGIC_64 || [MH_MAGIC, MH_MAGIC_64].includes(le) || [MH_MAGIC, MH_MAGIC_64].includes(be);\r\n}\r\n\r\nexport function archName(cpuType: number, cpuSubtype: number): string {\r\n const sub = cpuSubtype & 0x00ffffff;\r\n switch (cpuType) {\r\n case 0x0100000c:\r\n return sub === 2 ? 'arm64e' : 'arm64';\r\n case 0x0200000c:\r\n return 'arm64_32';\r\n case 0x0000000c:\r\n return sub === 9 ? 'armv7' : sub === 11 ? 'armv7s' : sub === 12 ? 'armv7k' : 'arm';\r\n case 0x01000007:\r\n return sub === 8 ? 'x86_64h' : 'x86_64';\r\n case 0x00000007:\r\n return 'i386';\r\n default:\r\n return `cpu${cpuType}`;\r\n }\r\n}\r\n\r\n/** The images in a Mach-O file: one for a thin file, one per slice for a universal one. */\r\nexport function readMachO(data: Uint8Array): MachOImage[] {\r\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\r\n const magic = view.getUint32(0, false);\r\n if (magic === FAT_MAGIC || magic === FAT_MAGIC_64) {\r\n const wide = magic === FAT_MAGIC_64;\r\n const count = view.getUint32(4, false);\r\n const images: MachOImage[] = [];\r\n for (let i = 0; i < count; i++) {\r\n const h = 8 + i * (wide ? 32 : 20);\r\n const offset = wide ? Number(view.getBigUint64(h + 8, false)) : view.getUint32(h + 8, false);\r\n const size = wide ? Number(view.getBigUint64(h + 16, false)) : view.getUint32(h + 12, false);\r\n images.push(...readThin(data.subarray(offset, offset + size)).map((image) => ({ ...image, offset })));\r\n }\r\n return images;\r\n }\r\n return readThin(data);\r\n}\r\n\r\nfunction readThin(data: Uint8Array): MachOImage[] {\r\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\r\n let little: boolean;\r\n if ([MH_MAGIC, MH_MAGIC_64].includes(view.getUint32(0, true))) little = true;\r\n else if ([MH_MAGIC, MH_MAGIC_64].includes(view.getUint32(0, false))) little = false;\r\n else throw new Error('not a Mach-O file');\r\n const wide = view.getUint32(0, little) === MH_MAGIC_64;\r\n const cpuType = view.getUint32(4, little);\r\n const cpuSubtype = view.getUint32(8, little);\r\n const ncmds = view.getUint32(16, little);\r\n let p = wide ? 32 : 28;\r\n for (let i = 0; i < ncmds && p + 8 <= data.length; i++) {\r\n const cmd = view.getUint32(p, little);\r\n const size = view.getUint32(p + 4, little);\r\n if (cmd === LC_UUID && p + 24 <= data.length) {\r\n return [{ uuid: formatUuid(data.subarray(p + 8, p + 24)), arch: archName(cpuType, cpuSubtype), offset: 0, size: data.length }];\r\n }\r\n if (size < 8) break;\r\n p += size;\r\n }\r\n return [];\r\n}\r\n\r\nfunction formatUuid(bytes: Uint8Array): string {\r\n let hex = '';\r\n for (const b of bytes) hex += b.toString(16).padStart(2, '0');\r\n hex = hex.toUpperCase();\r\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\r\n}\r\n","/**\r\n * Source maps for JavaScript: inject debug IDs into a build's output, upload each file and its\r\n * map, and delete the maps so they are not served.\r\n */\r\nimport { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';\r\nimport { dirname, isAbsolute, resolve } from 'node:path';\r\nimport { eachLimit, uploadArtifact, type Connection } from './api';\r\nimport { existingDebugId, injectCode, injectMap, sourceMappingUrl, withoutSourceMappingUrl } from './debug-id';\r\nimport { formatBytes, pathFilter, relativePath, walk, type Pattern } from './files';\r\nimport { consoleLogger, type Logger } from './log';\r\n\r\nconst JS_FILE = /\\.(?:js|mjs|cjs)$/;\r\n\r\nexport interface SourceFile {\r\n /** Absolute path of the JavaScript file. */\r\n file: string;\r\n /** Absolute path of its source map. */\r\n map: string;\r\n /** Path of the file relative to the directory, with forward slashes. */\r\n name: string;\r\n mapName: string;\r\n}\r\n\r\nexport interface FindOptions {\r\n include?: Pattern;\r\n exclude?: Pattern;\r\n /** Only these files (absolute paths) — the bundler plugins pass what the build wrote. */\r\n files?: string[];\r\n}\r\n\r\n/** The source map a JS file has: `<file>.map` next to it, or the file its `sourceMappingURL` names. */\r\nexport function mapFor(file: string, code?: string): string | undefined {\r\n const sibling = `${file}.map`;\r\n if (existsSync(sibling)) return sibling;\r\n const url = sourceMappingUrl(code ?? readFileSync(file, 'utf8'));\r\n if (!url || /^[a-z][a-z0-9+.-]*:/i.test(url)) return undefined; // data:, http:… are not files here\r\n let path: string;\r\n try {\r\n path = decodeURIComponent(url.split(/[?#]/)[0]);\r\n } catch {\r\n return undefined;\r\n }\r\n const full = isAbsolute(path) ? path : resolve(dirname(file), path);\r\n return existsSync(full) ? full : undefined;\r\n}\r\n\r\n/** Every JS file under `dir` that has a source map. */\r\nexport function findSourceFiles(dir: string, options: FindOptions = {}): SourceFile[] {\r\n const root = resolve(dir);\r\n const keep = pathFilter(options.include, options.exclude);\r\n const candidates = options.files ? options.files.map((f) => resolve(f)) : walk(root);\r\n const out: SourceFile[] = [];\r\n for (const file of candidates) {\r\n if (!JS_FILE.test(file) || !existsSync(file)) continue;\r\n const name = relativePath(root, file);\r\n if (!keep(name)) continue;\r\n const map = mapFor(file);\r\n if (map) out.push({ file, map, name, mapName: relativePath(root, map) });\r\n }\r\n return out;\r\n}\r\n\r\nexport interface InjectOptions extends FindOptions {\r\n /** Remove the `sourceMappingURL` comment too — for maps that are deleted after upload. */\r\n stripSourceMappingUrl?: boolean;\r\n dryRun?: boolean;\r\n logger?: Logger;\r\n}\r\n\r\nexport interface InjectedFile extends SourceFile {\r\n debugId: string;\r\n /** False when the file already had this debug ID. */\r\n changed: boolean;\r\n}\r\n\r\n/**\r\n * Add a debug ID to every JS file under `dir` that has a source map, and to the map. Running it\r\n * again changes nothing: a file that has a debug ID keeps it.\r\n */\r\nexport function injectDirectory(dir: string, options: InjectOptions = {}): InjectedFile[] {\r\n const logger = options.logger ?? consoleLogger();\r\n const files = findSourceFiles(dir, options);\r\n const out: InjectedFile[] = [];\r\n const noSourcesContent: string[] = [];\r\n for (const source of files) {\r\n const code = readFileSync(source.file, 'utf8');\r\n const injected = injectCode(code, { stripSourceMappingUrl: options.stripSourceMappingUrl });\r\n let map;\r\n try {\r\n map = injectMap(readFileSync(source.map, \"utf8\"), injected.debugId, source.map);\r\n } catch (error) {\r\n logger.warn(`Skipped ${source.name}: ${source.mapName} is not a readable source map (${(error as Error).message}).`);\r\n continue;\r\n }\r\n if (!options.dryRun) {\r\n if (injected.changed) writeFileSync(source.file, injected.code);\r\n if (map.changed) writeFileSync(source.map, map.text);\r\n }\r\n if (!map.hasSourcesContent) noSourcesContent.push(source.mapName);\r\n const changed = injected.changed || map.changed;\r\n out.push({ ...source, debugId: injected.debugId, changed });\r\n logger.info(`${changed ? (options.dryRun ? 'would inject' : 'injected') : 'already has'} ${injected.debugId} ${source.name}`);\r\n }\r\n if (noSourcesContent.length) {\r\n logger.warn(\r\n `${noSourcesContent.length} source map(s) have no sourcesContent, so Zharp can show original names and lines but not the code around them: ${noSourcesContent.slice(0, 3).join(', ')}${noSourcesContent.length > 3 ? ', …' : ''}`,\r\n );\r\n }\r\n if (out.length === 0) logger.warn(`No JavaScript files with source maps found in ${dir}.`);\r\n return out;\r\n}\r\n\r\nexport interface UploadOptions extends FindOptions {\r\n release?: string;\r\n /** Delete the .map files once they are uploaded. */\r\n deleteAfter?: boolean;\r\n /** Also strip the `sourceMappingURL` comments that pointed at deleted maps. */\r\n stripSourceMappingUrl?: boolean;\r\n dryRun?: boolean;\r\n concurrency?: number;\r\n logger?: Logger;\r\n fetch?: typeof fetch;\r\n retries?: number;\r\n}\r\n\r\nexport interface UploadResult {\r\n files: number;\r\n artifacts: number;\r\n bytes: number;\r\n deleted: string[];\r\n /** Files with a map but no debug ID: run inject first. */\r\n skipped: string[];\r\n}\r\n\r\n/**\r\n * Upload every JS file under `dir` that has a debug ID, with its source map, keyed by that ID.\r\n * `connection` may be null in a dry run.\r\n */\r\nexport async function uploadSourcemaps(dir: string, connection: Connection | null, options: UploadOptions = {}): Promise<UploadResult> {\r\n const logger = options.logger ?? consoleLogger();\r\n const files = findSourceFiles(dir, options);\r\n const result: UploadResult = { files: 0, artifacts: 0, bytes: 0, deleted: [], skipped: [] };\r\n const work: Array<{ source: SourceFile; debugId: string; code: Buffer; map: Buffer }> = [];\r\n for (const source of files) {\r\n const code = readFileSync(source.file);\r\n const debugId = existingDebugId(code.toString('utf8'));\r\n if (!debugId) {\r\n result.skipped.push(source.name);\r\n continue;\r\n }\r\n work.push({ source, debugId, code, map: readFileSync(source.map) });\r\n }\r\n if (result.skipped.length) {\r\n logger.warn(`${result.skipped.length} file(s) have a source map but no debug ID — run \\`zharp sourcemaps inject\\` first: ${result.skipped.slice(0, 3).join(', ')}${result.skipped.length > 3 ? ', …' : ''}`);\r\n }\r\n if (work.length === 0) {\r\n logger.warn(`Nothing to upload in ${dir}.`);\r\n return result;\r\n }\r\n\r\n const total = work.length;\r\n logger.info(`${options.dryRun ? 'Would upload' : 'Uploading'} ${total} file(s) and their source maps${options.release ? ` for release ${options.release}` : ''}${connection ? ` to ${connection.url}, app ${connection.app}` : ''}`);\r\n let done = 0;\r\n await eachLimit(work, options.concurrency ?? 4, async ({ source, debugId, code, map }) => {\r\n const size = code.length + map.length;\r\n if (!options.dryRun) {\r\n if (!connection) throw new Error('No connection to upload to.');\r\n const common = { debugId, release: options.release };\r\n const opts = { fetch: options.fetch, retries: options.retries };\r\n await uploadArtifact(connection, { ...common, kind: 'minified-source', name: source.name, data: code }, opts);\r\n await uploadArtifact(connection, { ...common, kind: 'sourcemap', name: source.mapName, data: map }, opts);\r\n }\r\n done += 1;\r\n result.files += 1;\r\n result.artifacts += 2;\r\n result.bytes += size;\r\n logger.info(` [${done}/${total}] ${options.dryRun ? 'would upload' : 'uploaded'} ${source.name} + ${source.mapName} (${formatBytes(size)}) ${debugId}`);\r\n });\r\n\r\n if (options.deleteAfter && !options.dryRun) {\r\n result.deleted = deleteSourcemaps(work.map((w) => w.source), { stripSourceMappingUrl: options.stripSourceMappingUrl });\r\n logger.info(`Deleted ${result.deleted.length} source map(s) from the output.`);\r\n }\r\n logger.info(`${options.dryRun ? 'Dry run: would have uploaded' : 'Uploaded'} ${result.artifacts} artifact(s), ${formatBytes(result.bytes)}.`);\r\n return result;\r\n}\r\n\r\n/** Delete these files' source maps (and, if asked, the comments pointing at them). */\r\nexport function deleteSourcemaps(files: SourceFile[], options: { stripSourceMappingUrl?: boolean } = {}): string[] {\r\n const deleted: string[] = [];\r\n for (const source of files) {\r\n if (options.stripSourceMappingUrl && existsSync(source.file)) {\r\n const code = readFileSync(source.file, 'utf8');\r\n const stripped = withoutSourceMappingUrl(code);\r\n if (stripped !== code) writeFileSync(source.file, stripped);\r\n }\r\n if (existsSync(source.map)) {\r\n unlinkSync(source.map);\r\n deleted.push(source.mapName);\r\n }\r\n }\r\n return deleted;\r\n}\r\n","/**\r\n * Debug IDs for JavaScript, after the TC39 source map \"debug ID\" proposal: one UUID per emitted\r\n * file, written into the file (`//# debugId=<uuid>`) and into its source map (`\"debugId\"`), so an\r\n * error's frames can be matched to the exact map whatever URL the file was served from.\r\n *\r\n * Besides the comment, each file gets one line that registers it at runtime — the SDKs read\r\n * `globalThis.__zharpDebugIds` to know which build each file in a stack came from.\r\n */\r\nimport { createHash } from 'node:crypto';\r\nimport { existsSync, readFileSync, statSync } from 'node:fs';\r\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\r\nimport { fileURLToPath } from 'node:url';\r\n\r\nexport const DEBUG_ID_COMMENT = '//# debugId=';\r\nconst DEBUG_ID_PATTERN = /^\\/\\/# debugId=([0-9a-fA-F-]{36})\\s*$/m;\r\nconst SOURCE_MAPPING_URL = /^\\/\\/[#@] sourceMappingURL=(.*?)\\s*$/;\r\n\r\n/**\r\n * The UUID for a file's content: the first 16 bytes of its SHA-256, with the version and variant\r\n * bits of a v4 UUID. The same output always gets the same ID, so a rebuild of unchanged code\r\n * does not need a new upload.\r\n */\r\nexport function debugIdFromContent(content: string | Uint8Array): string {\r\n const bytes = createHash('sha256').update(content).digest().subarray(0, 16);\r\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\r\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\r\n const hex = bytes.toString('hex');\r\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\r\n}\r\n\r\n/**\r\n * The runtime registration: ES5, so it is safe in any bundle whatever its target, and wrapped in\r\n * a try so it can never break the file it is in. The key is a stack taken inside the file — its\r\n * top frame is the file's own URL or path, as the runtime names it.\r\n */\r\nexport function registrationSnippet(debugId: string): string {\r\n return (\r\n ';!function(){try{var g=\"undefined\"!=typeof globalThis?globalThis:\"undefined\"!=typeof self?self:' +\r\n '\"undefined\"!=typeof window?window:\"undefined\"!=typeof global?global:{},s=(new Error).stack;' +\r\n `s&&((g.__zharpDebugIds=g.__zharpDebugIds||{})[s]=\"${debugId}\")}catch(e){}}();`\r\n );\r\n}\r\n\r\n/** The debug ID already in a file, if it has one. */\r\nexport function existingDebugId(code: string): string | undefined {\r\n // Only at the end of the file: a bundle may contain another file's comment in its middle.\r\n const lines = code.trimEnd().split('\\n');\r\n for (let i = lines.length - 1; i >= 0 && i >= lines.length - 4; i--) {\r\n const match = DEBUG_ID_PATTERN.exec(lines[i].trim());\r\n if (match) return match[1].toLowerCase();\r\n }\r\n return undefined;\r\n}\r\n\r\n/** Whether the file's tail already registers it at runtime. */\r\nexport function hasRegistration(code: string): boolean {\r\n return code.slice(-2000).includes('.__zharpDebugIds=');\r\n}\r\n\r\n/** The `sourceMappingURL` the file's last line points at, if any (data: URLs included). */\r\nexport function sourceMappingUrl(code: string): string | undefined {\r\n const lines = code.trimEnd().split('\\n');\r\n for (let i = lines.length - 1; i >= 0 && i >= lines.length - 3; i--) {\r\n const match = SOURCE_MAPPING_URL.exec(lines[i].trim());\r\n if (match) return match[1];\r\n }\r\n return undefined;\r\n}\r\n\r\nexport interface InjectedCode {\r\n code: string;\r\n debugId: string;\r\n /** False when the file already had a debug ID: nothing was changed. */\r\n changed: boolean;\r\n}\r\n\r\n/**\r\n * The file with its debug ID: the registration line and the comment, appended after the code —\r\n * before a trailing `sourceMappingURL` comment, if there is one. Appending leaves every existing\r\n * line and column where it was, so the source map stays valid without being rewritten.\r\n *\r\n * A file that already has a debug ID is returned as it is, with that ID.\r\n */\r\nexport function injectCode(code: string, options: { stripSourceMappingUrl?: boolean } = {}): InjectedCode {\r\n const existing = existingDebugId(code);\r\n const eol = code.includes('\\r\\n') ? '\\r\\n' : '\\n';\r\n if (existing) {\r\n let out = code;\r\n // A bundler that writes debug IDs itself (Rollup's sourcemapDebugIds, webpack's\r\n // `-debugids` devtools, Turbopack) adds the comment but not Zharp's registration.\r\n if (!hasRegistration(code)) {\r\n const lines = code.split(/\\r?\\n/);\r\n let at = lines.length - 1;\r\n while (at > 0 && !lines[at].trim().startsWith(DEBUG_ID_COMMENT)) at--;\r\n lines.splice(at, 0, registrationSnippet(existing));\r\n out = lines.join(eol);\r\n }\r\n if (options.stripSourceMappingUrl) out = withoutSourceMappingUrl(out);\r\n return { code: out, debugId: existing, changed: out !== code };\r\n }\r\n const debugId = debugIdFromContent(code);\r\n const lines = code.split(/\\r?\\n/);\r\n // The trailing sourceMappingURL comment (and the blank lines after it) stays last.\r\n let tail: string[] = [];\r\n let end = lines.length;\r\n while (end > 0 && lines[end - 1].trim() === '') end--;\r\n if (end > 0 && SOURCE_MAPPING_URL.test(lines[end - 1].trim())) {\r\n tail = options.stripSourceMappingUrl ? [] : [lines[end - 1]];\r\n end--;\r\n }\r\n const body = lines.slice(0, end);\r\n const out = [...body, registrationSnippet(debugId), `${DEBUG_ID_COMMENT}${debugId}`, ...tail].join(eol) + eol;\r\n return { code: out, debugId, changed: true };\r\n}\r\n\r\n/** The code without its trailing `sourceMappingURL` comment — for maps that are not shipped. */\r\nexport function withoutSourceMappingUrl(code: string): string {\r\n const lines = code.split(/\\r?\\n/);\r\n const eol = code.includes('\\r\\n') ? '\\r\\n' : '\\n';\r\n let end = lines.length;\r\n while (end > 0 && lines[end - 1].trim() === '') end--;\r\n if (end > 0 && SOURCE_MAPPING_URL.test(lines[end - 1].trim())) return lines.slice(0, end - 1).join(eol) + eol;\r\n return code;\r\n}\r\n\r\n/**\r\n * The source map with the debug ID in it, under both spellings in use (`debugId` from the TC39\r\n * proposal, `debug_id` from earlier tooling). Returns the text unchanged when it already matches.\r\n */\r\nexport function injectMap(mapText: string, debugId: string, mapPath?: string): { text: string; changed: boolean; hasSourcesContent: boolean } {\r\n const map = JSON.parse(mapText);\r\n if (!map || typeof map !== 'object') throw new Error('not a source map');\r\n // The build machine has the sources: the app's own files go into the map, so the code shows.\r\n const filled = mapPath ? fillSourcesContent(map, mapPath) : 0;\r\n const hasSourcesContent = Array.isArray(map.sourcesContent) && map.sourcesContent.some((s: unknown) => typeof s === 'string');\r\n if (!filled && map.debugId === debugId && map.debug_id === debugId) return { text: mapText, changed: false, hasSourcesContent };\r\n map.debugId = debugId;\r\n map.debug_id = debugId;\r\n return { text: JSON.stringify(map), changed: true, hasSourcesContent };\r\n}\r\n\r\nconst MAX_SOURCE_BYTES = 1_000_000;\r\n\r\n/** A map source's path on this machine, for the bundlers' ways of naming them. */\r\nexport function sourcePathCandidates(source: string, mapPath: string, sourceRoot = ''): string[] {\r\n const mapDir = dirname(mapPath);\r\n // turbopack:///[project]/app/page.tsx, webpack://_N_E/./app/page.tsx, webpack:///src/x.ts, file:///abs\r\n let stripped = source;\r\n let projectRelative = false;\r\n if (/^turbopack:\\/\\/\\/\\[project\\]\\//.test(source)) {\r\n stripped = source.replace(/^turbopack:\\/\\/\\/\\[project\\]\\//, '');\r\n projectRelative = true;\r\n } else if (/^webpack:\\/\\//.test(source)) {\r\n stripped = source.replace(/^webpack:\\/\\/[^/]*\\//, '').replace(/^\\.\\//, '');\r\n projectRelative = true;\r\n } else if (/^file:\\/\\//.test(source)) {\r\n try {\r\n return [fileURLToPath(source)];\r\n } catch {\r\n return [];\r\n }\r\n } else if (/^[a-z][\\w+.-]*:\\/\\//i.test(source)) {\r\n return [];\r\n }\r\n if (isAbsolute(stripped)) return [stripped];\r\n const out = [resolve(mapDir, sourceRoot, stripped)];\r\n if (projectRelative) {\r\n // Relative to the project: the nearest folder above the map that has a package.json.\r\n for (let dir = mapDir, i = 0; i < 12; i++) {\r\n if (existsSync(join(dir, 'package.json'))) {\r\n out.unshift(join(dir, stripped));\r\n break;\r\n }\r\n const up = dirname(dir);\r\n if (up === dir) break;\r\n dir = up;\r\n }\r\n }\r\n return out;\r\n}\r\n\r\n/** Fills the app's own sources into a map that left them out. Returns how many it filled. */\r\nexport function fillSourcesContent(map: any, mapPath: string): number {\r\n if (!Array.isArray(map.sources)) return 0;\r\n const contents: Array<string | null> = Array.isArray(map.sourcesContent) ? [...map.sourcesContent] : [];\r\n let filled = 0;\r\n map.sources.forEach((source: unknown, i: number) => {\r\n if (typeof contents[i] === 'string' || typeof source !== 'string') return;\r\n if (/node_modules|^\\[externals\\]|\\(ignored\\)|^webpack\\/runtime/.test(source)) return;\r\n for (const path of sourcePathCandidates(source, mapPath, typeof map.sourceRoot === 'string' ? map.sourceRoot : '')) {\r\n if (/[\\\\/]node_modules[\\\\/]/.test(path)) continue;\r\n try {\r\n const stat = statSync(path);\r\n if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) continue;\r\n contents[i] = readFileSync(path, 'utf8');\r\n filled++;\r\n break;\r\n } catch {\r\n // Not here: the next candidate.\r\n }\r\n }\r\n });\r\n if (filled) {\r\n while (contents.length < map.sources.length) contents.push(null);\r\n map.sourcesContent = contents.map((c) => (typeof c === 'string' ? c : null));\r\n }\r\n return filled;\r\n}\r\n","export const VERSION = '0.2.0';\r\n","/**\r\n * `zharp init`: connect this project to Zharp and wire the SDK in.\r\n *\r\n * 1. find what the project is (Next.js, React with Vite, NestJS…);\r\n * 2. connect it in the browser — sign in, pick the workspace and app, approve;\r\n * 3. show every change, and make them only on a yes (`--yes` for scripts);\r\n * 4. install the packages, write the keys to an env file git ignores;\r\n * 5. send a test error and print where to see it.\r\n */\r\nimport { spawnSync } from 'node:child_process';\r\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\r\nimport { createInterface } from 'node:readline/promises';\r\nimport { dirname, join, resolve } from 'node:path';\r\nimport { connect, SetupFailed, type Connected } from './connect';\r\nimport { detect, type Project } from './detect';\r\nimport { DEFAULT_API, GUIDES, planFor, type Plan } from './recipes';\r\n\r\nexport interface InitOptions {\r\n dir?: string;\r\n url?: string;\r\n yes?: boolean;\r\n dryRun?: boolean;\r\n /** Install the SDK from these .tgz files instead of npm (testing unreleased versions). */\r\n tarballs?: string;\r\n}\r\n\r\nconst green = (s: string) => `\\u001b[32m${s}\\u001b[39m`;\r\nconst dim = (s: string) => `\\u001b[2m${s}\\u001b[22m`;\r\nconst bold = (s: string) => `\\u001b[1m${s}\\u001b[22m`;\r\nconst yellow = (s: string) => `\\u001b[33m${s}\\u001b[39m`;\r\nconst bar = dim('│');\r\n\r\nfunction say(line = ''): void {\r\n process.stdout.write(`${line}\\n`);\r\n}\r\n\r\n/** The env file with these keys set: existing lines kept, ours replaced or added. */\r\nexport function mergeEnv(existing: string, vars: Record<string, string>): string {\r\n const lines = existing ? existing.replace(/\\s+$/, '').split(/\\r?\\n/) : [];\r\n const seen = new Set<string>();\r\n const out = lines.map((line) => {\r\n const name = /^\\s*(?:export\\s+)?([A-Z0-9_]+)\\s*=/.exec(line)?.[1];\r\n if (name && name in vars) {\r\n seen.add(name);\r\n return `${name}=${vars[name]}`;\r\n }\r\n return line;\r\n });\r\n const added = Object.entries(vars).filter(([k]) => !seen.has(k));\r\n if (added.length) {\r\n if (out.length) out.push('');\r\n out.push('# Zharp (npx zharp init)');\r\n for (const [k, v] of added) out.push(`${k}=${v}`);\r\n }\r\n return `${out.join('\\n')}\\n`;\r\n}\r\n\r\n/** Whether git would ignore `file` by the project's .gitignore (the common patterns). */\r\nexport function ignoredByGit(gitignore: string, file: string): boolean {\r\n return gitignore.split(/\\r?\\n/).map((l) => l.trim()).some((l) =>\r\n l === file || l === `/${file}` || l === '.env*' || l === '.env*.local' && file.endsWith('.local') || l === '*.local' && file.endsWith('.local') || l === '.env.*' && file !== '.env');\r\n}\r\n\r\nfunction installCommand(project: Project, packages: string[], dev: boolean, tarballs?: string): [string, string[]] {\r\n const specs = tarballs ? packages.map((p) => join(tarballs, `${p.replace('@', '').replace('/', '-')}.tgz`)) : packages;\r\n switch (project.packageManager) {\r\n case 'pnpm':\r\n return ['pnpm', ['add', ...(dev ? ['-D'] : []), ...specs]];\r\n case 'yarn':\r\n return ['yarn', ['add', ...(dev ? ['-D'] : []), ...specs]];\r\n case 'bun':\r\n return ['bun', ['add', ...(dev ? ['-d'] : []), ...specs]];\r\n default:\r\n return ['npm', ['install', ...(dev ? ['--save-dev'] : []), ...specs]];\r\n }\r\n}\r\n\r\nasync function ask(question: string): Promise<string> {\r\n const rl = createInterface({ input: process.stdin, output: process.stdout });\r\n try {\r\n return (await rl.question(question)).trim().toLowerCase();\r\n } finally {\r\n rl.close();\r\n }\r\n}\r\n\r\n/** A test error, straight to OTLP with the app's key, so the person sees one arrive. */\r\nasync function sendTestError(api: string, c: Connected): Promise<boolean> {\r\n const now = `${Date.now()}000000`;\r\n const attr = (key: string, value: string) => ({ key, value: { stringValue: value } });\r\n const body = {\r\n resourceLogs: [{\r\n resource: { attributes: [attr('service.name', c.application.serviceName), attr('telemetry.sdk.name', 'zharp-cli')] },\r\n scopeLogs: [{\r\n logRecords: [{\r\n timeUnixNano: now,\r\n severityNumber: 17,\r\n severityText: 'ERROR',\r\n body: { stringValue: 'ZharpSetupTest: Zharp is connected — this is the test error npx zharp init sent' },\r\n attributes: [\r\n attr('exception.type', 'ZharpSetupTest'),\r\n attr('exception.message', 'Zharp is connected — this is the test error npx zharp init sent'),\r\n attr('exception.stacktrace', 'ZharpSetupTest: Zharp is connected — this is the test error npx zharp init sent\\n at zharp init'),\r\n attr('zharp.handled', 'true'),\r\n ],\r\n }],\r\n }],\r\n }],\r\n };\r\n try {\r\n const res = await fetch(`${api.replace(/\\/+$/, '')}/api/v1/otlp/v1/logs`, {\r\n method: 'POST',\r\n headers: { 'content-type': 'application/json', authorization: `Bearer ${c.application.ingestKey}` },\r\n body: JSON.stringify(body),\r\n });\r\n return res.ok;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\nfunction showPlan(plan: Plan, c: Connected): void {\r\n say(`${green('◆')} ${bold('These changes will be made:')}`);\r\n const deps = [...plan.install, ...plan.devInstall];\r\n if (deps.length) say(`${bar} ${green('+')} install ${deps.join(' ')}`);\r\n for (const ch of plan.changes) say(`${bar} ${ch.kind === 'create' ? green('+') : yellow('~')} ${bold(ch.path)} ${dim(ch.kind === 'create' ? `(new) ${ch.note}` : ch.note)}`);\r\n say(`${bar} ${green('+')} ${bold(plan.env.file)} ${dim(Object.keys(plan.env.vars).join(', '))}`);\r\n for (const m of plan.manual) say(`${bar} ${yellow('!')} ${m.path}: ${dim(`left as it is — ${m.why}`)}`);\r\n void c;\r\n}\r\n\r\nexport async function runInit(options: InitOptions): Promise<number> {\r\n const dir = resolve(options.dir ?? process.cwd());\r\n const api = (options.url ?? process.env.ZHARP_URL ?? DEFAULT_API).replace(/\\/+$/, '');\r\n const project = detect(dir);\r\n\r\n say();\r\n say(`${green('◆')} ${bold('Zharp setup')}`);\r\n say(`${bar} Found ${bold(project.label)} in ${dim(dir)}`);\r\n say(bar);\r\n\r\n let connected: Connected;\r\n try {\r\n connected = await connect(api, project, {\r\n showCode(code, url) {\r\n say(`${bar} Open ${url} and check this code:`);\r\n say(bar);\r\n say(`${bar} ${bold(code)}`);\r\n say(bar);\r\n say(`${bar} ${dim('Waiting for you to approve it in the browser…')}`);\r\n },\r\n });\r\n } catch (error) {\r\n say(`${yellow('■')} ${error instanceof SetupFailed ? error.message : String(error)}`);\r\n return 1;\r\n }\r\n say(`${green('◇')} Connected to ${bold(`${connected.workspace.name} / ${connected.application.name}`)}`);\r\n say(bar);\r\n\r\n const plan = planFor(project, connected, api);\r\n if (!plan) {\r\n say(`${green('◆')} ${bold(`${project.label}: add the SDK with these keys`)}`);\r\n say(`${bar} ZHARP_KEY=${connected.application.ingestKey}`);\r\n say(`${bar} ${dim('Upload key (source maps): ZHARP_AUTH_TOKEN=')}${connected.uploadKey}`);\r\n const guide = GUIDES[project.framework];\r\n say(`${bar} ${dim(`How: ${guide ?? 'https://zharp.io/docs'}`)}`);\r\n return 0;\r\n }\r\n\r\n showPlan(plan, connected);\r\n say(bar);\r\n if (options.dryRun) {\r\n say(`${green('◇')} Dry run: nothing was changed.`);\r\n return 0;\r\n }\r\n if (!options.yes) {\r\n for (;;) {\r\n const answer = await ask(`${green('◆')} Apply? ${dim('[Y]es / [n]o / show the [d]iff')} `);\r\n if (answer === 'd' || answer === 'diff') {\r\n for (const ch of plan.changes) {\r\n say(`\\n${bold(`── ${ch.path} ${ch.kind === 'create' ? '(new)' : '(edited)'}`)}`);\r\n say(ch.content);\r\n }\r\n continue;\r\n }\r\n if (answer === 'n' || answer === 'no') {\r\n say(`${yellow('■')} Nothing was changed. The app is set up in Zharp: ${connected.appUrl}`);\r\n return 0;\r\n }\r\n break;\r\n }\r\n }\r\n\r\n // The files first: a failed install still leaves the setup in place, to finish by hand.\r\n for (const ch of plan.changes) {\r\n const path = join(dir, ch.path);\r\n mkdirSync(dirname(path), { recursive: true });\r\n writeFileSync(path, ch.content);\r\n }\r\n const envPath = join(dir, plan.env.file);\r\n writeFileSync(envPath, mergeEnv(existsSync(envPath) ? readFileSync(envPath, 'utf8') : '', plan.env.vars));\r\n const gitignorePath = join(dir, '.gitignore');\r\n if (existsSync(join(dir, '.git')) || existsSync(gitignorePath)) {\r\n const gitignore = existsSync(gitignorePath) ? readFileSync(gitignorePath, 'utf8') : '';\r\n if (!ignoredByGit(gitignore, plan.env.file)) writeFileSync(gitignorePath, `${gitignore.replace(/\\s*$/, '\\n')}${plan.env.file}\\n`);\r\n }\r\n say(`${green('◇')} Files written`);\r\n\r\n for (const [packages, dev] of [[plan.install, false], [plan.devInstall, true]] as const) {\r\n if (!packages.length) continue;\r\n const [command, args] = installCommand(project, [...packages], dev, options.tarballs);\r\n say(`${bar} ${dim(`${command} ${args.join(' ')}`)}`);\r\n // Windows runs npm/pnpm through their .cmd shims, which need a shell: one command line, quoted.\r\n const result = process.platform === 'win32'\r\n ? spawnSync([command, ...args].map((a) => (/[\\s\"&|<>^]/.test(a) ? `\"${a.replace(/\"/g, '\\\\\"')}\"` : a)).join(' '), { cwd: dir, stdio: 'inherit', shell: true })\r\n : spawnSync(command, args, { cwd: dir, stdio: 'inherit' });\r\n if (result.status !== 0) {\r\n say(`${yellow('■')} The install failed. Run it yourself: ${command} ${args.join(' ')}`);\r\n return 1;\r\n }\r\n }\r\n say(`${green('◇')} Packages installed`);\r\n\r\n for (const m of plan.manual) {\r\n say(bar);\r\n say(`${yellow('!')} ${bold(m.path)} — ${m.why}:`);\r\n for (const line of m.snippet.split('\\n')) say(`${bar} ${line}`);\r\n }\r\n for (const note of plan.notes) say(`${bar} ${yellow('!')} ${note}`);\r\n\r\n const sent = await sendTestError(api, connected);\r\n say(bar);\r\n say(sent\r\n ? `${green('◇')} Done. Sent a test error — see it at ${connected.appUrl}`\r\n : `${green('◇')} Done. Open ${connected.appUrl} — errors show up as your app sends them.`);\r\n return 0;\r\n}\r\n","/**\r\n * The handshake with Zharp: open a setup session, show its code, open the page in the browser,\r\n * and wait until the person approves it there — then collect the app's key and an upload key.\r\n */\r\nimport { spawn } from 'node:child_process';\r\nimport { platform as osPlatform, release } from 'node:os';\r\nimport type { Project } from './detect';\r\nimport { VERSION } from '../version';\r\n\r\nexport interface Connected {\r\n application: { id: number; name: string; serviceName: string; ingestKey: string };\r\n workspace: { id: number; name: string };\r\n uploadKey: string;\r\n appUrl: string;\r\n}\r\n\r\nexport interface ConnectHooks {\r\n /** Show the code and the link (the browser is opened too, where there is one). */\r\n showCode(code: string, url: string): void;\r\n /** While waiting: called each poll. */\r\n waiting?(): void;\r\n /** For tests: no browser, a fake clock. */\r\n openBrowser?: (url: string) => void;\r\n sleep?: (ms: number) => Promise<void>;\r\n fetch?: typeof fetch;\r\n}\r\n\r\nconst OS_NAMES: Record<string, string> = { win32: 'Windows', darwin: 'macOS', linux: 'Linux' };\r\n\r\nexport function openBrowser(url: string): void {\r\n // CI, SSH, or asked not to: the link is printed, nothing is opened.\r\n if (process.env.ZHARP_NO_BROWSER || process.env.CI || (process.platform === 'linux' && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY)) return;\r\n try {\r\n const command = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open';\r\n const args = process.platform === 'win32' ? ['/c', 'start', '\"\"', url.replace(/&/g, '^&')] : [url];\r\n spawn(command, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref();\r\n } catch {\r\n // No browser here (SSH, CI): the link is printed.\r\n }\r\n}\r\n\r\nexport class SetupFailed extends Error {}\r\n\r\nexport async function connect(api: string, project: Project, hooks: ConnectHooks): Promise<Connected> {\r\n const http = hooks.fetch ?? fetch;\r\n const sleep = hooks.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));\r\n const base = `${api.replace(/\\/+$/, '')}/api/v1/cli-setup`;\r\n\r\n const opened = await http(`${base}/sessions`, {\r\n method: 'POST',\r\n headers: { 'content-type': 'application/json', 'user-agent': `zharp-cli/${VERSION}` },\r\n body: JSON.stringify({ name: project.name, framework: project.label, platform: project.platform, os: OS_NAMES[osPlatform()] ?? `${osPlatform()} ${release()}`, cliVersion: VERSION }),\r\n }).catch((error) => {\r\n throw new SetupFailed(`Could not reach Zharp at ${api} (${error?.cause?.code ?? error?.message ?? error}).`);\r\n });\r\n if (!opened.ok) throw new SetupFailed(`Zharp refused to start a setup (${opened.status}).`);\r\n const session = (await opened.json()).data as { userCode: string; deviceToken: string; verificationUrl: string; expiresIn: number; interval: number };\r\n\r\n hooks.showCode(session.userCode, session.verificationUrl);\r\n (hooks.openBrowser ?? openBrowser)(session.verificationUrl);\r\n\r\n const until = Date.now() + session.expiresIn * 1000;\r\n while (Date.now() < until) {\r\n await sleep(Math.max(1, session.interval) * 1000);\r\n hooks.waiting?.();\r\n const res = await http(`${base}/collect`, {\r\n method: 'POST',\r\n headers: { 'content-type': 'application/json', 'user-agent': `zharp-cli/${VERSION}` },\r\n body: JSON.stringify({ deviceToken: session.deviceToken }),\r\n }).catch(() => null);\r\n if (!res) continue; // a blip: try again\r\n const body = await res.json().catch(() => ({}));\r\n if (res.status === 200 && body?.data?.status === 'approved') return body.data as Connected;\r\n if (res.status === 200) continue;\r\n throw new SetupFailed(body?.message ?? `The setup stopped (${res.status}).`);\r\n }\r\n throw new SetupFailed('The code expired before it was approved. Run it again.');\r\n}\r\n","/**\r\n * What kind of project this is, from its own files: package.json's dependencies, and the files\r\n * other ecosystems keep (requirements.txt, composer.json, go.mod). Only what the setup can act on\r\n * or point the person to.\r\n */\r\nimport { existsSync, readFileSync } from 'node:fs';\r\nimport { basename, join } from 'node:path';\r\n\r\nexport type Framework = 'nextjs' | 'vite-react' | 'nestjs' | 'express' | 'node' | 'django' | 'fastapi' | 'flask' | 'laravel' | 'go' | 'unknown';\r\n\r\nexport interface Project {\r\n dir: string;\r\n name: string;\r\n framework: Framework;\r\n /** \"Next.js 16\", \"React (Vite)\", \"NestJS 11\"… for the terminal and the page. */\r\n label: string;\r\n /** The Zharp platform the app is created with. */\r\n platform: 'browser' | 'node' | 'python' | 'php' | 'go' | 'otel';\r\n packageManager: 'pnpm' | 'yarn' | 'bun' | 'npm';\r\n typescript: boolean;\r\n /** Next.js: the app directory (\"app\" or \"src/app\"), when it uses the app router. */\r\n appDir?: string;\r\n packageJson?: Record<string, any>;\r\n}\r\n\r\nconst read = (path: string): string | null => {\r\n try {\r\n return readFileSync(path, 'utf8');\r\n } catch {\r\n return null;\r\n }\r\n};\r\n\r\nfunction majorOf(range: string | undefined): string {\r\n const m = /(\\d+)/.exec(range ?? '');\r\n return m ? ` ${m[1]}` : '';\r\n}\r\n\r\nexport function packageManagerOf(dir: string): Project['packageManager'] {\r\n if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm';\r\n if (existsSync(join(dir, 'yarn.lock'))) return 'yarn';\r\n if (existsSync(join(dir, 'bun.lockb')) || existsSync(join(dir, 'bun.lock'))) return 'bun';\r\n return 'npm';\r\n}\r\n\r\nexport function detect(dir: string): Project {\r\n const pkgText = read(join(dir, 'package.json'));\r\n const pkg = pkgText ? (() => { try { return JSON.parse(pkgText); } catch { return null; } })() : null;\r\n const deps: Record<string, string> = { ...(pkg?.dependencies ?? {}), ...(pkg?.devDependencies ?? {}) };\r\n const name = (typeof pkg?.name === 'string' && pkg.name.replace(/^@[^/]+\\//, '')) || basename(dir);\r\n const base = { dir, name, packageManager: packageManagerOf(dir), typescript: !!deps.typescript || existsSync(join(dir, 'tsconfig.json')), packageJson: pkg ?? undefined };\r\n\r\n if (deps.next) {\r\n const appDir = existsSync(join(dir, 'src', 'app')) ? 'src/app' : existsSync(join(dir, 'app')) ? 'app' : undefined;\r\n return { ...base, framework: 'nextjs', label: `Next.js${majorOf(deps.next)}`, platform: 'browser', appDir };\r\n }\r\n if (deps['@nestjs/core']) return { ...base, framework: 'nestjs', label: `NestJS${majorOf(deps['@nestjs/core'])}`, platform: 'node' };\r\n if (deps.vite && deps.react) return { ...base, framework: 'vite-react', label: 'React (Vite)', platform: 'browser' };\r\n if (deps.express) return { ...base, framework: 'express', label: `Express${majorOf(deps.express)}`, platform: 'node' };\r\n\r\n const py = [read(join(dir, 'requirements.txt')), read(join(dir, 'pyproject.toml')), read(join(dir, 'Pipfile'))].filter(Boolean).join('\\n').toLowerCase();\r\n if (py) {\r\n const pyName = basename(dir);\r\n if (/\\bdjango\\b/.test(py)) return { ...base, name: pyName, framework: 'django', label: 'Django', platform: 'python' };\r\n if (/\\bfastapi\\b/.test(py)) return { ...base, name: pyName, framework: 'fastapi', label: 'FastAPI', platform: 'python' };\r\n if (/\\bflask\\b/.test(py)) return { ...base, name: pyName, framework: 'flask', label: 'Flask', platform: 'python' };\r\n }\r\n const composer = read(join(dir, 'composer.json'));\r\n if (composer && /laravel\\/framework/.test(composer)) return { ...base, name: basename(dir), framework: 'laravel', label: 'Laravel', platform: 'php' };\r\n if (existsSync(join(dir, 'go.mod'))) return { ...base, name: basename(dir), framework: 'go', label: 'Go', platform: 'go' };\r\n if (pkg) return { ...base, framework: 'node', label: 'Node.js', platform: 'node' };\r\n return { ...base, framework: 'unknown', label: 'an unknown project', platform: 'otel' };\r\n}\r\n","/**\r\n * What `zharp init` changes in a project, per framework — worked out first, as a plan the person\r\n * sees before anything is written. Only standard files are touched, each in the one way that is\r\n * safe: a new file is created only where none exists; an existing file is edited only where its\r\n * shape is the common one (a plain `export default`, a `plugins: [` array, a `createRoot(…)` call).\r\n * Anything else becomes a snippet to paste, never a guess.\r\n */\r\nimport { existsSync, readFileSync } from 'node:fs';\r\nimport { join } from 'node:path';\r\nimport type { Project } from './detect';\r\nimport type { Connected } from './connect';\r\n\r\nexport interface Change {\r\n path: string;\r\n kind: 'create' | 'edit';\r\n content: string;\r\n /** What it is, in a few words: \"wrapped with withZharp\". */\r\n note: string;\r\n}\r\n\r\nexport interface Manual {\r\n path: string;\r\n why: string;\r\n snippet: string;\r\n}\r\n\r\nexport interface Plan {\r\n install: string[];\r\n devInstall: string[];\r\n changes: Change[];\r\n /** Keys go in this file, which is checked to be ignored by git. */\r\n env: { file: string; vars: Record<string, string> };\r\n manual: Manual[];\r\n /** Said at the end: what to set up elsewhere (CI). */\r\n notes: string[];\r\n}\r\n\r\nexport const DEFAULT_API = 'https://api.zharp.io';\r\n\r\nconst read = (dir: string, path: string): string | null => {\r\n try {\r\n return readFileSync(join(dir, path), 'utf8');\r\n } catch {\r\n return null;\r\n }\r\n};\r\nconst first = (dir: string, paths: string[]) => paths.find((p) => existsSync(join(dir, p))) ?? null;\r\nconst mentionsZharp = (text: string | null) => !!text && /@zharp\\//.test(text);\r\n\r\n/** Lines added to a file follow its style: no semicolons where its imports have none. */\r\nfunction styled(text: string, line: string): string {\r\n const imports = [...text.matchAll(/^import .*$/gm)].map((m) => m[0].trimEnd());\r\n const bare = imports.length > 0 && imports.every((l) => !l.endsWith(';'));\r\n // Double-quoted imports: the line's strings in double quotes too.\r\n const double = imports.filter((l) => /from \"/.test(l)).length > imports.filter((l) => /from '/.test(l)).length;\r\n const quoted = double ? line.replace(/'([^'\"]*)'/g, '\"$1\"') : line;\r\n return bare ? quoted.replace(/;$/, '') : quoted;\r\n}\r\n\r\n/** The OTLP endpoint, said only when it isn't Zharp's own. */\r\nfunction endpointOf(api: string): string | null {\r\n const clean = api.replace(/\\/+$/, '');\r\n return clean === DEFAULT_API ? null : `${clean}/api/v1/otlp`;\r\n}\r\n\r\n// ── Next.js ──────────────────────────────────────────────────────────────────────\r\n\r\n/** `export default X;` → `export default withZharp(X, { app: 42 });`, the import added. */\r\nexport function wrapNextConfig(text: string, appId: number, esm: boolean): string | null {\r\n if (/withZharp/.test(text)) return null;\r\n const exportDefault = /export\\s+default\\s+([\\s\\S]+?);?\\s*$/.exec(text);\r\n if (esm && exportDefault) {\r\n const value = exportDefault[1].trim().replace(/;$/, '');\r\n const head = text.slice(0, exportDefault.index);\r\n return `import { withZharp } from '@zharp/nextjs';\\n${head}export default withZharp(${value}, { app: ${appId} });\\n`;\r\n }\r\n const moduleExports = /module\\.exports\\s*=\\s*([\\s\\S]+?);?\\s*$/.exec(text);\r\n if (!esm && moduleExports) {\r\n const value = moduleExports[1].trim().replace(/;$/, '');\r\n const head = text.slice(0, moduleExports.index);\r\n return `const { withZharp } = require('@zharp/nextjs');\\n${head}module.exports = withZharp(${value}, { app: ${appId} });\\n`;\r\n }\r\n return null;\r\n}\r\n\r\n/** The client component rendered first in <body>, with its import, in the root layout. */\r\nexport function addToLayout(text: string, importPath: string): string | null {\r\n if (/ZharpClient/.test(text)) return null;\r\n const body = /<body\\b[^>]*>/.exec(text);\r\n if (!body) return null;\r\n const at = body.index + body[0].length;\r\n // On its own line, indented one step in from <body>; what followed <body> keeps its own line.\r\n const bodyIndent = /[ \\t]*$/.exec(text.slice(0, body.index))![0];\r\n const inner = `${bodyIndent} `;\r\n const rest = text.slice(at);\r\n const after = /^\\s*\\n/.test(rest) ? rest : `\\n${inner}${rest.replace(/^[ \\t]+/, '')}`;\r\n const withComponent = `${text.slice(0, at)}\\n${inner}<ZharpClient />${after}`;\r\n const imports = [...withComponent.matchAll(/^import .*$/gm)];\r\n const line = styled(text, `import { ZharpClient } from '${importPath}';`);\r\n if (!imports.length) return `${line}\\n${withComponent}`;\r\n const last = imports[imports.length - 1];\r\n const end = last.index! + last[0].length;\r\n return `${withComponent.slice(0, end)}\\n${line}${withComponent.slice(end)}`;\r\n}\r\n\r\nfunction nextjs(project: Project, c: Connected, api: string): Plan {\r\n const dir = project.dir;\r\n const ts = project.typescript;\r\n const plan: Plan = { install: ['@zharp/browser', '@zharp/node'], devInstall: ['@zharp/nextjs'], changes: [], manual: [], notes: [], env: { file: '.env.local', vars: {} } };\r\n const endpoint = endpointOf(api);\r\n\r\n // Server: instrumentation.ts, next to app/ (in src/ when the app lives there).\r\n const instrumentationPath = `${project.appDir?.startsWith('src/') ? 'src/' : ''}instrumentation.${ts ? 'ts' : 'js'}`;\r\n const instrumentation = [\r\n 'export async function register() {',\r\n \" if (process.env.NEXT_RUNTIME === 'nodejs') {\",\r\n \" const { Zharp } = await import('@zharp/node');\",\r\n ` Zharp.init({ service: '${c.application.serviceName}' });`,\r\n ' }',\r\n '}',\r\n '',\r\n '// Errors Next.js answers with an error page: reported with their route.',\r\n `export async function onRequestError(...args${ts ? \": Parameters<typeof import('@zharp/node').Zharp.onRequestError>\" : ''}) {`,\r\n \" if (process.env.NEXT_RUNTIME === 'nodejs') {\",\r\n \" const { Zharp } = await import('@zharp/node');\",\r\n ' Zharp.onRequestError(...args);',\r\n ' }',\r\n '}',\r\n '',\r\n ].join('\\n');\r\n const existingInstrumentation = first(dir, ['instrumentation.ts', 'instrumentation.js', 'src/instrumentation.ts', 'src/instrumentation.js']);\r\n if (!existingInstrumentation) plan.changes.push({ path: instrumentationPath, kind: 'create', content: instrumentation, note: 'starts Zharp on the server' });\r\n else if (!mentionsZharp(read(dir, existingInstrumentation))) plan.manual.push({ path: existingInstrumentation, why: 'it already exists — add Zharp to it', snippet: instrumentation });\r\n\r\n // Build: next.config wrapped with withZharp (source maps uploaded, @zharp/node kept external).\r\n const configPath = first(dir, ['next.config.ts', 'next.config.mjs', 'next.config.js', 'next.config.cjs']);\r\n if (!configPath) {\r\n plan.changes.push({ path: ts ? 'next.config.ts' : 'next.config.mjs', kind: 'create', content: `import { withZharp } from '@zharp/nextjs';\\n\\nexport default withZharp({}, { app: ${c.application.id} });\\n`, note: 'source maps uploaded on build' });\r\n } else {\r\n const text = read(dir, configPath) ?? '';\r\n const esm = /\\.(ts|mjs)$/.test(configPath) || /^\\s*(import|export)\\s/m.test(text);\r\n const wrapped = mentionsZharp(text) ? null : wrapNextConfig(text, c.application.id, esm);\r\n if (wrapped) plan.changes.push({ path: configPath, kind: 'edit', content: wrapped, note: 'wrapped with withZharp' });\r\n else if (!mentionsZharp(text)) plan.manual.push({ path: configPath, why: \"its export isn't a plain value — wrap it yourself\", snippet: `import { withZharp } from '@zharp/nextjs';\\n\\nexport default withZharp(nextConfig, { app: ${c.application.id} });` });\r\n }\r\n\r\n // Browser: a client component started from the root layout (app router).\r\n if (project.appDir) {\r\n const ext = ts ? 'tsx' : 'jsx';\r\n const clientPath = `${project.appDir}/zharp-client.${ext}`;\r\n const client = [\r\n \"'use client';\",\r\n \"import { Zharp } from '@zharp/browser';\",\r\n '',\r\n \"if (typeof window !== 'undefined' && !Zharp.isActive) {\",\r\n ` Zharp.init({ key: process.env.NEXT_PUBLIC_ZHARP_KEY${ts ? '!' : ''}${endpoint ? ', endpoint: process.env.NEXT_PUBLIC_ZHARP_ENDPOINT' : ''}, service: '${c.application.serviceName}' });`,\r\n '}',\r\n '',\r\n '/** Starts Zharp in the browser; rendered once, in the root layout. */',\r\n 'export function ZharpClient() {',\r\n ' return null;',\r\n '}',\r\n '',\r\n ].join('\\n');\r\n if (!existsSync(join(dir, clientPath))) plan.changes.push({ path: clientPath, kind: 'create', content: client, note: `starts Zharp in the browser` });\r\n const layoutPath = first(dir, [`${project.appDir}/layout.tsx`, `${project.appDir}/layout.jsx`, `${project.appDir}/layout.js`]);\r\n const layout = layoutPath ? read(dir, layoutPath) : null;\r\n const edited = layout ? addToLayout(layout, './zharp-client') : null;\r\n if (layoutPath && edited) plan.changes.push({ path: layoutPath, kind: 'edit', content: edited, note: 'renders <ZharpClient />' });\r\n else if (layoutPath && !/ZharpClient/.test(layout ?? '')) plan.manual.push({ path: layoutPath, why: 'add the component inside <body>', snippet: \"import { ZharpClient } from './zharp-client';\\n…\\n<body>\\n <ZharpClient />\" });\r\n } else {\r\n plan.manual.push({ path: 'pages/_app', why: 'pages router: start Zharp in your _app', snippet: \"import { Zharp } from '@zharp/browser';\\n\\nif (typeof window !== 'undefined') Zharp.init({ key: process.env.NEXT_PUBLIC_ZHARP_KEY });\" });\r\n }\r\n\r\n plan.env.vars = {\r\n NEXT_PUBLIC_ZHARP_KEY: c.application.ingestKey,\r\n ZHARP_KEY: c.application.ingestKey,\r\n ZHARP_AUTH_TOKEN: c.uploadKey,\r\n ...(endpoint ? { NEXT_PUBLIC_ZHARP_ENDPOINT: endpoint, ZHARP_ENDPOINT: endpoint, ZHARP_URL: api.replace(/\\/+$/, '') } : {}),\r\n };\r\n plan.notes.push('Add ZHARP_AUTH_TOKEN (and the keys) to your CI and hosting, so production builds upload their source maps.');\r\n return plan;\r\n}\r\n\r\n// ── React with Vite ──────────────────────────────────────────────────────────────\r\n\r\n/** `plugins: [react()]` → `plugins: [react(), zharp({ app: 42 })]`, the import added. */\r\nexport function addVitePlugin(text: string, appId: number): string | null {\r\n if (/@zharp\\/vite-plugin/.test(text)) return null;\r\n const plugins = /plugins\\s*:\\s*\\[/.exec(text);\r\n if (!plugins) return null;\r\n // The array's closing bracket: the first `]` at depth zero after the opening one.\r\n let depth = 0;\r\n let close = -1;\r\n for (let i = plugins.index + plugins[0].length; i < text.length; i++) {\r\n const ch = text[i];\r\n if (ch === '[' || ch === '(' || ch === '{') depth++;\r\n else if (ch === ']' || ch === ')' || ch === '}') {\r\n if (depth === 0 && ch === ']') {\r\n close = i;\r\n break;\r\n }\r\n depth--;\r\n }\r\n }\r\n if (close < 0) return null;\r\n const inside = text.slice(plugins.index + plugins[0].length, close).trimEnd();\r\n const sep = inside.length === 0 ? '' : inside.endsWith(',') ? ' ' : ', ';\r\n const withPlugin = `${text.slice(0, plugins.index + plugins[0].length)}${inside}${sep}zharp({ app: ${appId} })${text.slice(close)}`;\r\n const imports = [...withPlugin.matchAll(/^import .*$/gm)];\r\n const line = styled(text, \"import { zharp } from '@zharp/vite-plugin';\");\r\n if (!imports.length) return `${line}\\n${withPlugin}`;\r\n const last = imports[imports.length - 1];\r\n const end = last.index! + last[0].length;\r\n return `${withPlugin.slice(0, end)}\\n${line}${withPlugin.slice(end)}`;\r\n}\r\n\r\n/** Zharp started before React renders; createRoot given React 19's error handlers. */\r\nexport function addToViteMain(text: string, serviceName: string, withEndpoint: boolean): string | null {\r\n if (/@zharp\\/browser/.test(text)) return null;\r\n const call = /createRoot\\(([^()]*(?:\\([^()]*\\)[^()]*)*)\\)/.exec(text);\r\n let next = text;\r\n if (call && !call[1].includes(',')) {\r\n next = `${text.slice(0, call.index)}createRoot(${call[1]}, {\\n onUncaughtError: Zharp.reactErrorHandler(),\\n onCaughtError: Zharp.reactErrorHandler(),\\n})${text.slice(call.index + call[0].length)}`;\r\n }\r\n const imports = [...next.matchAll(/^import .*$/gm)];\r\n const start = styled(text, `Zharp.init({ key: import.meta.env.VITE_ZHARP_KEY${withEndpoint ? ', endpoint: import.meta.env.VITE_ZHARP_ENDPOINT' : ''}, service: '${serviceName}' });`);\r\n const init = `\\n${start}\\n`;\r\n const line = styled(text, \"import { Zharp } from '@zharp/browser';\");\r\n if (!imports.length) return `${line}\\n${init}\\n${next}`;\r\n const last = imports[imports.length - 1];\r\n const end = last.index! + last[0].length;\r\n return `${next.slice(0, end)}\\n${line}\\n${init}${next.slice(end).replace(/^\\n+/, '\\n')}`;\r\n}\r\n\r\nfunction viteReact(project: Project, c: Connected, api: string): Plan {\r\n const dir = project.dir;\r\n const endpoint = endpointOf(api);\r\n const plan: Plan = { install: ['@zharp/browser'], devInstall: ['@zharp/vite-plugin'], changes: [], manual: [], notes: [], env: { file: '.env.local', vars: {} } };\r\n const configPath = first(dir, ['vite.config.ts', 'vite.config.mts', 'vite.config.js', 'vite.config.mjs']);\r\n const config = configPath ? read(dir, configPath) : null;\r\n const editedConfig = config ? addVitePlugin(config, c.application.id) : null;\r\n if (configPath && editedConfig) plan.changes.push({ path: configPath, kind: 'edit', content: editedConfig, note: 'source maps uploaded on build' });\r\n else if (!mentionsZharp(config)) plan.manual.push({ path: configPath ?? 'vite.config.ts', why: 'add the plugin to plugins', snippet: `import { zharp } from '@zharp/vite-plugin';\\n…\\nplugins: [react(), zharp({ app: ${c.application.id} })]` });\r\n\r\n const mainPath = first(dir, ['src/main.tsx', 'src/main.jsx', 'src/main.ts', 'src/main.js', 'src/index.tsx', 'src/index.jsx']);\r\n const main = mainPath ? read(dir, mainPath) : null;\r\n const editedMain = main ? addToViteMain(main, c.application.serviceName, !!endpoint) : null;\r\n if (mainPath && editedMain) plan.changes.push({ path: mainPath, kind: 'edit', content: editedMain, note: 'starts Zharp; React errors with their component stack' });\r\n else if (!mentionsZharp(main)) plan.manual.push({ path: mainPath ?? 'src/main.tsx', why: 'start Zharp before React renders', snippet: \"import { Zharp } from '@zharp/browser';\\n\\nZharp.init({ key: import.meta.env.VITE_ZHARP_KEY });\\n\\ncreateRoot(el, { onUncaughtError: Zharp.reactErrorHandler(), onCaughtError: Zharp.reactErrorHandler() })\" });\r\n\r\n plan.env.vars = {\r\n VITE_ZHARP_KEY: c.application.ingestKey,\r\n ZHARP_AUTH_TOKEN: c.uploadKey,\r\n ...(endpoint ? { VITE_ZHARP_ENDPOINT: endpoint, ZHARP_URL: api.replace(/\\/+$/, '') } : {}),\r\n };\r\n plan.notes.push('Add ZHARP_AUTH_TOKEN and VITE_ZHARP_KEY to your CI, so production builds upload their source maps.');\r\n return plan;\r\n}\r\n\r\n// ── NestJS ───────────────────────────────────────────────────────────────────────\r\n\r\nfunction nestjs(project: Project, c: Connected, api: string): Plan {\r\n const dir = project.dir;\r\n const endpoint = endpointOf(api);\r\n const plan: Plan = { install: ['@zharp/node'], devInstall: [], changes: [], manual: [], notes: [], env: { file: '.env', vars: {} } };\r\n const ext = project.typescript ? 'ts' : 'js';\r\n const instrumentPath = `src/instrument.${ext}`;\r\n const instrument = [\r\n \"import { Zharp } from '@zharp/node';\",\r\n '',\r\n '// Before anything else: http, the database drivers and NestJS are instrumented as they load.',\r\n \"try { process.loadEnvFile?.('.env'); } catch { /* no .env: the environment has the keys */ }\",\r\n `Zharp.init({ service: '${c.application.serviceName}' });`,\r\n '',\r\n ].join('\\n');\r\n if (!existsSync(join(dir, instrumentPath))) plan.changes.push({ path: instrumentPath, kind: 'create', content: instrument, note: 'starts Zharp before the app loads' });\r\n\r\n const mainPath = first(dir, [`src/main.${ext}`]);\r\n const main = mainPath ? read(dir, mainPath) : null;\r\n const esm = project.packageJson?.type === 'module' || /from '\\.{1,2}\\/[^']+\\.js'/.test(main ?? '');\r\n if (esm) {\r\n // ES modules load every import before any code runs, so a first import is too late for\r\n // NestJS: Node preloads the file instead (--import), from the project's own start scripts.\r\n const pkgText = read(dir, 'package.json');\r\n const scripts = { ...(project.packageJson?.scripts ?? {}) } as Record<string, string>;\r\n const preload = '--import ./dist/instrument.js';\r\n let changed = false;\r\n for (const [name, command] of Object.entries(scripts)) {\r\n if (command.includes(preload)) continue;\r\n if (/^nest start\\b/.test(command) && !/--exec\\b/.test(command)) {\r\n scripts[name] = `${command} --exec \"node ${preload}\"`;\r\n changed = true;\r\n } else if (/^node (?:--[^\\s]+ )*dist\\/main(?:\\.js)?\\s*$/.test(command)) {\r\n scripts[name] = command.replace(/^node /, `node ${preload} `);\r\n changed = true;\r\n }\r\n }\r\n if (changed && pkgText) {\r\n // Only those lines change: the rest of package.json keeps its formatting.\r\n let text = pkgText;\r\n for (const [name, command] of Object.entries(scripts)) {\r\n const before = (project.packageJson?.scripts ?? {})[name];\r\n if (before === command) continue;\r\n const line = new RegExp(`(\"${name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\"\\\\s*:\\\\s*)${JSON.stringify(before).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}`);\r\n text = text.replace(line, (_, key: string) => `${key}${JSON.stringify(command)}`);\r\n }\r\n plan.changes.push({ path: 'package.json', kind: 'edit', content: text, note: 'start scripts preload Zharp (--import)' });\r\n }\r\n plan.manual.push({ path: 'your start command', why: 'ES modules: wherever the app is started outside these scripts (a Dockerfile, a process manager), preload Zharp', snippet: `node ${preload} dist/main.js` });\r\n } else if (mainPath && main && !main.includes('./instrument')) {\r\n plan.changes.push({ path: mainPath, kind: 'edit', content: `${styled(main, \"import './instrument';\")}\\n${main}`, note: 'loads it first' });\r\n } else if (!mainPath) {\r\n plan.manual.push({ path: 'src/main.ts', why: 'import it first in your entry file', snippet: \"import './instrument';\" });\r\n }\r\n plan.env.vars = { ZHARP_KEY: c.application.ingestKey, ...(endpoint ? { ZHARP_ENDPOINT: endpoint } : {}) };\r\n plan.notes.push('Set ZHARP_KEY where the app runs in production.');\r\n return plan;\r\n}\r\n\r\nexport function planFor(project: Project, c: Connected, api: string): Plan | null {\r\n switch (project.framework) {\r\n case 'nextjs':\r\n return nextjs(project, c, api);\r\n case 'vite-react':\r\n return viteReact(project, c, api);\r\n case 'nestjs':\r\n return nestjs(project, c, api);\r\n default:\r\n return null;\r\n }\r\n}\r\n\r\n/** Frameworks without a recipe yet: where to read how. */\r\nexport const GUIDES: Record<string, string> = {\r\n express: 'https://zharp.io/docs/sdks/node',\r\n node: 'https://zharp.io/docs/sdks/node',\r\n django: 'https://zharp.io/docs/sdks/python',\r\n fastapi: 'https://zharp.io/docs/sdks/python',\r\n flask: 'https://zharp.io/docs/sdks/python',\r\n laravel: 'https://zharp.io/docs/sdks/php',\r\n go: 'https://zharp.io/docs/sdks/go',\r\n};\r\n"],"mappings":";;;;AAIA,uBAA0B;AAC1B,IAAAA,kBAA2B;;;ACD3B,uBAAyB;AAElB,IAAM,cAAc;AAyBpB,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YACE,SACS,QAEA,YAAY,OACrB;AACA,UAAM,OAAO;AAJJ;AAEA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAAA,EAEA;AAKb;AAMO,SAAS,kBAAkB,SAAkF;AAClH,QAAM,YAAY,QAAQ,aAAa,QAAQ,IAAI;AACnD,QAAM,MAAM,QAAQ,OAAO,QA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AAe,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACvJ,UAAQ,WAAW;AACrB,CAAC;","names":["import_node_fs","resolve","import_node_fs","import_node_path","hex","import_node_fs","import_node_path","import_node_fs","import_node_path","hex","out","lines","import_node_child_process","import_node_fs","import_node_path","sleep","osPlatform","import_node_fs","import_node_path","import_node_fs","import_node_path","read","sep","main","release","connect"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/api.ts","../src/log.ts","../src/native.ts","../src/elf.ts","../src/files.ts","../src/macho.ts","../src/swift-names.ts","../src/source-bundle.ts","../src/react-native.ts","../src/sourcemaps.ts","../src/debug-id.ts","../src/version.ts","../src/init/index.ts","../src/init/connect.ts","../src/init/detect.ts","../src/init/recipes.ts","../src/init/recipes-more.ts","../src/init/recipes-rn.ts"],"sourcesContent":["#!/usr/bin/env node\r\n/**\r\n * `zharp` — upload what Zharp needs to turn minified and obfuscated stacks back into source.\r\n */\r\nimport { parseArgs } from 'node:util';\r\nimport { existsSync } from 'node:fs';\r\nimport { resolveConnection, UploadError, type Connection } from './api';\r\nimport { consoleLogger } from './log';\r\nimport { uploadDartSymbols, uploadDsyms, uploadProguard } from './native';\r\nimport { uploadReactNative, uploadReactNativeDir } from './react-native';\r\nimport { injectDirectory, uploadSourcemaps } from './sourcemaps';\r\nimport { VERSION } from './version';\r\nimport { runInit } from './init';\r\n\r\nconst HELP = `zharp ${VERSION} — readable stack traces for Zharp\r\n\r\nUsage:\r\n zharp init Connect this project to Zharp and set it up\r\n (also: npm init zharp@latest)\r\n [--yes] [--dry-run] (signs in through the browser)\r\n zharp sourcemaps inject <dir> Add debug IDs to JS files and their maps\r\n zharp sourcemaps upload <dir> --app <id> Upload JS files and their maps\r\n [--release <r>] [--delete-after]\r\n zharp proguard upload <mapping.txt> --app <id> --uuid <uuid>\r\n zharp dart-symbols upload <dir> --app <id> Flutter --split-debug-info output\r\n [--obfuscation-map <file>] (and its obfuscation map)\r\n zharp dsym upload <path> --app <id> A .dSYM, or a folder of them\r\n zharp react-native upload --bundle <file> --map <file> --app <id>\r\n A React Native release bundle's source map\r\n zharp react-native upload --dir dist --app <id> Every bundle an \\`npx expo export\\` wrote (EAS Update)\r\n\r\nOptions:\r\n --app <id> Application ID (or ZHARP_APP)\r\n --release <r> Release name to file the upload under (or ZHARP_RELEASE)\r\n --include <glob> Only these files (repeatable; sourcemaps)\r\n --exclude <glob> Not these files (repeatable; sourcemaps)\r\n --sources <dir> The project whose sources go with the symbols (dart-symbols, dsym; default: found)\r\n --no-sources Don't upload the app's sources (errors then show code only from a linked repo)\r\n --delete-after Delete .map files after uploading them\r\n --dry-run Show what would happen; change and send nothing\r\n --url <url> Zharp API (default ZHARP_URL or https://api.zharp.io)\r\n -h, --help, -v, --version\r\n\r\nEnvironment:\r\n ZHARP_AUTH_TOKEN A workspace API key with the \"artifacts:write\" scope (required to upload)\r\n ZHARP_URL The Zharp API, default https://api.zharp.io\r\n`;\r\n\r\nclass UsageError extends Error {}\r\n\r\nfunction fail(message: string): never {\r\n throw new UsageError(message);\r\n}\r\n\r\nasync function main(argv: string[]): Promise<void> {\r\n const { values, positionals } = parseArgs({\r\n args: argv,\r\n allowPositionals: true,\r\n options: {\r\n app: { type: 'string' },\r\n release: { type: 'string' },\r\n uuid: { type: 'string' },\r\n 'obfuscation-map': { type: 'string' },\r\n sources: { type: 'string' },\r\n bundle: { type: 'string' },\r\n dir: { type: 'string' },\r\n map: { type: 'string' },\r\n 'no-sources': { type: 'boolean' },\r\n include: { type: 'string', multiple: true },\r\n exclude: { type: 'string', multiple: true },\r\n 'delete-after': { type: 'boolean' },\r\n 'dry-run': { type: 'boolean' },\r\n yes: { type: 'boolean', short: 'y' },\r\n tarballs: { type: 'string' },\r\n url: { type: 'string' },\r\n help: { type: 'boolean', short: 'h' },\r\n version: { type: 'boolean', short: 'v' },\r\n },\r\n });\r\n if (values.version) {\r\n console.log(VERSION);\r\n return;\r\n }\r\n const [group, command, target] = positionals;\r\n if (values.help || !group) {\r\n console.log(HELP);\r\n return;\r\n }\r\n if (group === 'init') {\r\n process.exitCode = await runInit({ url: values.url, yes: values.yes === true, dryRun: values['dry-run'] === true, tarballs: values.tarballs, dir: command });\r\n return;\r\n }\r\n const logger = consoleLogger();\r\n const dryRun = values['dry-run'] === true;\r\n const release = values.release ?? process.env.ZHARP_RELEASE;\r\n const needTarget = (what: string) => {\r\n if (!target) fail(`${group} ${command} needs ${what}. See \\`zharp --help\\`.`);\r\n if (!existsSync(target)) fail(`${target} does not exist.`);\r\n return target;\r\n };\r\n const connect = (): Connection | null => (dryRun ? null : resolveConnection({ app: values.app, url: values.url }));\r\n\r\n switch (`${group} ${command}`) {\r\n case 'sourcemaps inject': {\r\n const dir = needTarget('a directory');\r\n const files = injectDirectory(dir, { include: values.include, exclude: values.exclude, dryRun, logger });\r\n logger.info(`${dryRun ? 'Would inject' : 'Injected'} debug IDs into ${files.filter((f) => f.changed).length} file(s); ${files.filter((f) => !f.changed).length} already had one.`);\r\n return;\r\n }\r\n case 'sourcemaps upload': {\r\n const dir = needTarget('a directory');\r\n const connection = connect();\r\n const result = await uploadSourcemaps(dir, connection, {\r\n release,\r\n include: values.include,\r\n exclude: values.exclude,\r\n deleteAfter: values['delete-after'] === true,\r\n dryRun,\r\n logger,\r\n });\r\n if (result.files === 0) process.exitCode = 1;\r\n return;\r\n }\r\n case 'proguard upload': {\r\n const file = needTarget('the mapping.txt file');\r\n if (!values.uuid) fail('proguard upload needs --uuid <uuid>: the build UUID the Zharp Gradle plugin put into the app.');\r\n await uploadProguard(file, values.uuid, connect(), { release, dryRun, logger });\r\n return;\r\n }\r\n case 'dart-symbols upload': {\r\n const sources = values['no-sources'] ? false : values.sources;\r\n await uploadDartSymbols(needTarget('the --split-debug-info directory'), connect(), { release, dryRun, logger, obfuscationMap: values['obfuscation-map'], sources });\r\n return;\r\n }\r\n case 'react-native upload': {\r\n if (values.dir) {\r\n if (!existsSync(values.dir)) fail(`${values.dir} does not exist.`);\r\n await uploadReactNativeDir(values.dir, connect(), { release, dryRun, logger });\r\n return;\r\n }\r\n if (!values.bundle || !values.map) fail('react-native upload needs --bundle <index.android.bundle | main.jsbundle> and --map <its source map>, or --dir <expo export output>.');\r\n for (const file of [values.bundle!, values.map!]) if (!existsSync(file)) fail(`${file} does not exist.`);\r\n await uploadReactNative(values.bundle!, values.map!, connect(), { release, dryRun, logger });\r\n return;\r\n }\r\n case 'dsym upload': {\r\n const sources = values['no-sources'] ? false : values.sources;\r\n await uploadDsyms(needTarget('a .dSYM bundle or a folder of them'), connect(), { release, dryRun, logger, sources });\r\n return;\r\n }\r\n default:\r\n fail(`Unknown command \"${positionals.join(' ')}\". See \\`zharp --help\\`.`);\r\n }\r\n}\r\n\r\n// Errors set the exit code rather than calling process.exit(): uploads still in flight finish\r\n// (or fail) cleanly first.\r\nmain(process.argv.slice(2)).catch((error) => {\r\n console.error(`[zharp] error: ${error instanceof UsageError || error instanceof UploadError || error instanceof Error ? error.message : String(error)}`);\r\n process.exitCode = 1;\r\n});\r\n","/**\r\n * The artifact upload API: `POST /api/v1/applications/:id/artifacts`, multipart, with a\r\n * workspace API key that has the `artifacts:write` scope.\r\n */\r\nimport { gzipSync } from 'node:zlib';\r\n\r\nexport const DEFAULT_URL = 'https://api.zharp.io';\r\n\r\nexport type ArtifactKind = 'sourcemap' | 'minified-source' | 'proguard' | 'dart-symbols' | 'dart-obfuscation-map' | 'dsym' | 'source-bundle' | 'symbol-names';\r\n\r\nexport interface Connection {\r\n /** The Zharp API's base URL, e.g. https://api.zharp.io. */\r\n url: string;\r\n /** A workspace API key with the `artifacts:write` scope. */\r\n authToken: string;\r\n /** The application's ID, as in the dashboard URL. */\r\n app: string | number;\r\n}\r\n\r\nexport interface Artifact {\r\n kind: ArtifactKind;\r\n debugId: string;\r\n /** The file's path or URL (JS), or file name. */\r\n name: string;\r\n release?: string;\r\n arch?: string;\r\n data: Uint8Array;\r\n /** Send gzipped (large native symbol files). */\r\n gzip?: boolean;\r\n}\r\n\r\nexport class UploadError extends Error {\r\n constructor(\r\n message: string,\r\n readonly status?: number,\r\n /** Retrying will not help: a rejected key, a missing app, a bad request. */\r\n readonly permanent = false,\r\n ) {\r\n super(message);\r\n this.name = 'UploadError';\r\n }\r\n}\r\n\r\n/**\r\n * The connection from options and the environment (`ZHARP_AUTH_TOKEN`, `ZHARP_URL`,\r\n * `ZHARP_APP`). Throws with what is missing.\r\n */\r\nexport function resolveConnection(options: { url?: string; authToken?: string; app?: string | number }): Connection {\r\n const authToken = options.authToken || process.env.ZHARP_AUTH_TOKEN;\r\n const app = options.app ?? process.env.ZHARP_APP;\r\n const missing: string[] = [];\r\n if (!authToken) missing.push('an auth token (ZHARP_AUTH_TOKEN, or the authToken option): a workspace API key with the \"artifacts:write\" scope');\r\n if (app === undefined || app === '') missing.push('the application ID (--app, the app option, or ZHARP_APP)');\r\n if (missing.length) throw new UploadError(`Cannot upload without ${missing.join(' and ')}.`, undefined, true);\r\n return { url: (options.url || process.env.ZHARP_URL || DEFAULT_URL).replace(/\\/+$/, ''), authToken: authToken!, app: app! };\r\n}\r\n\r\nexport function artifactsUrl(connection: Connection): string {\r\n return `${connection.url}/api/v1/applications/${encodeURIComponent(String(connection.app))}/artifacts`;\r\n}\r\n\r\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\r\n\r\n/** Upload one artifact, retrying network failures, 408, 429 and 5xx with backoff. */\r\nexport async function uploadArtifact(\r\n connection: Connection,\r\n artifact: Artifact,\r\n options: { retries?: number; fetch?: typeof fetch; backoffMs?: number } = {},\r\n): Promise<unknown> {\r\n const doFetch = options.fetch ?? fetch;\r\n const retries = options.retries ?? 3;\r\n const backoff = options.backoffMs ?? 1000;\r\n const fileName = (artifact.name.split('/').pop() || 'artifact') + (artifact.gzip ? '.gz' : '');\r\n const payload = artifact.gzip ? gzipSync(artifact.data) : artifact.data;\r\n\r\n for (let attempt = 0; ; attempt++) {\r\n // A fresh body per attempt: a FormData is consumed by the request that sends it.\r\n const form = new FormData();\r\n form.set('kind', artifact.kind);\r\n form.set('debugId', artifact.debugId);\r\n form.set('name', artifact.name);\r\n if (artifact.release) form.set('release', artifact.release);\r\n if (artifact.arch) form.set('arch', artifact.arch);\r\n const type = artifact.gzip ? 'application/gzip' : artifact.kind === 'sourcemap' ? 'application/json' : 'application/octet-stream';\r\n form.set('file', new Blob([payload as Uint8Array<ArrayBuffer>], { type }), fileName);\r\n\r\n let retryAfter = 0;\r\n let error: UploadError;\r\n try {\r\n const response = await doFetch(artifactsUrl(connection), {\r\n method: 'POST',\r\n headers: { Authorization: `Bearer ${connection.authToken}`, 'User-Agent': 'zharp-cli' },\r\n body: form,\r\n });\r\n const text = await response.text().catch(() => '');\r\n if (response.ok) {\r\n try {\r\n return text ? JSON.parse(text) : null;\r\n } catch {\r\n return text;\r\n }\r\n }\r\n error = describeFailure(response.status, text, connection);\r\n retryAfter = Number(response.headers.get('retry-after')) * 1000 || 0;\r\n } catch (cause) {\r\n error = new UploadError(`Could not reach ${connection.url}: ${(cause as Error)?.message ?? cause}`);\r\n }\r\n if (error.permanent || attempt >= retries) throw error;\r\n await sleep(Math.max(retryAfter, backoff * 2 ** attempt));\r\n }\r\n}\r\n\r\nfunction serverMessage(text: string): string {\r\n try {\r\n const body = JSON.parse(text);\r\n const message = body?.message ?? body?.error;\r\n if (typeof message === 'string') return message;\r\n if (Array.isArray(message)) return message.join('; ');\r\n } catch {}\r\n return text.slice(0, 300);\r\n}\r\n\r\nfunction describeFailure(status: number, text: string, connection: Connection): UploadError {\r\n const detail = serverMessage(text);\r\n const retryable = status === 408 || status === 429 || status >= 500;\r\n const explain: Record<number, string> = {\r\n 401: 'The auth token was rejected — check ZHARP_AUTH_TOKEN (a workspace API key, not the app key).',\r\n 403: 'The API key cannot upload here — it needs the \"artifacts:write\" scope, in the workspace that owns the app.',\r\n 404: `Application ${connection.app} was not found — check --app (the ID in the app's dashboard URL) and ZHARP_URL.`,\r\n 413: 'The file is larger than the server accepts.',\r\n };\r\n const message = `${explain[status] ?? `Upload failed with HTTP ${status}.`}${detail ? ` Server said: ${detail}` : ''}`;\r\n return new UploadError(message, status, !retryable);\r\n}\r\n\r\n/** Run `fn` over `items`, `limit` at a time. Stops at the first error. */\r\nexport async function eachLimit<T>(items: T[], limit: number, fn: (item: T, index: number) => Promise<void>): Promise<void> {\r\n let next = 0;\r\n let failed: unknown;\r\n const worker = async () => {\r\n while (failed === undefined && next < items.length) {\r\n const index = next++;\r\n try {\r\n await fn(items[index], index);\r\n } catch (error) {\r\n failed ??= error;\r\n }\r\n }\r\n };\r\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\r\n if (failed !== undefined) throw failed;\r\n}\r\n","/** Where progress goes. The CLI prints it; the bundler plugins prefix it with their name. */\r\nexport interface Logger {\r\n info(message: string): void;\r\n warn(message: string): void;\r\n}\r\n\r\nexport const consoleLogger = (prefix = '[zharp]'): Logger => ({\r\n info: (message) => console.log(`${prefix} ${message}`),\r\n warn: (message) => console.warn(`${prefix} ${message}`),\r\n});\r\n\r\nexport const silentLogger: Logger = { info() {}, warn() {} };\r\n","/**\r\n * Mobile symbol files: R8/ProGuard mappings (Android), Dart symbol files (Flutter\r\n * `--split-debug-info`) and dSYMs (iOS). Each is uploaded gzipped, keyed by the ID its platform's\r\n * errors carry.\r\n */\r\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\r\nimport { basename, dirname, join, resolve } from 'node:path';\r\nimport { eachLimit, uploadArtifact, type Artifact, type Connection } from './api';\r\nimport { readElf, isElf } from './elf';\r\nimport { formatBytes, walk } from './files';\r\nimport { consoleLogger, type Logger } from './log';\r\nimport { isMachO, readMachO } from './macho';\r\nimport { swiftNames, type XcodeTool } from './swift-names';\r\nimport { APPLE_SOURCES, collectSources, FLUTTER_SOURCES, isAppleRoot, isFlutterRoot, projectRoot, sourceBundleArtifacts } from './source-bundle';\r\n\r\nexport interface NativeUploadOptions {\r\n release?: string;\r\n dryRun?: boolean;\r\n logger?: Logger;\r\n fetch?: typeof fetch;\r\n retries?: number;\r\n /**\r\n * The app's source files go with the symbols, so errors show the code of the build (default:\r\n * on). `false` leaves them out; a path is the project folder to read them from (default: found\r\n * from the working directory — pubspec.yaml for Flutter, the .xcodeproj or $SRCROOT for iOS).\r\n */\r\n sources?: string | false;\r\n /** dsym upload: how Xcode's tools are run (tests); default xcrun on a Mac, none elsewhere. */\r\n xcodeTool?: XcodeTool | null;\r\n}\r\n\r\n/** The source bundle for these build IDs, when sources are on and the project is found. */\r\nfunction withSources(kind: 'flutter' | 'apple', buildIds: string[], options: NativeUploadOptions, logger: Logger): Artifact[] {\r\n if (options.sources === false || !buildIds.length) return [];\r\n const root = typeof options.sources === 'string'\r\n ? resolve(options.sources)\r\n : kind === 'apple' && process.env.SRCROOT ? process.env.SRCROOT\r\n : projectRoot(process.cwd(), kind === 'flutter' ? isFlutterRoot : isAppleRoot);\r\n if (!root || !existsSync(root)) {\r\n logger.info(`Sources: no ${kind === 'flutter' ? 'Flutter project (pubspec.yaml)' : 'Xcode project'} found from ${process.cwd()} — pass --sources <project folder>, or --no-sources.`);\r\n return [];\r\n }\r\n const sources = collectSources(root, kind === 'flutter' ? FLUTTER_SOURCES : APPLE_SOURCES);\r\n if (!sources.count) return [];\r\n logger.info(`With the app's sources: ${sources.count} file(s), ${formatBytes(sources.bytes)} from ${root}${sources.skipped ? ` (${sources.skipped} over the size caps left out)` : ''} — errors show the code of this build. --no-sources to leave them out.`);\r\n return sourceBundleArtifacts(sources, buildIds, options.release);\r\n}\r\n\r\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\r\n\r\nasync function send(connection: Connection | null, artifacts: Artifact[], options: NativeUploadOptions): Promise<Artifact[]> {\r\n const logger = options.logger ?? consoleLogger();\r\n let done = 0;\r\n await eachLimit(artifacts, 2, async (artifact) => {\r\n if (!options.dryRun) {\r\n if (!connection) throw new Error('No connection to upload to.');\r\n await uploadArtifact(connection, artifact, { fetch: options.fetch, retries: options.retries });\r\n }\r\n done += 1;\r\n const extra = artifact.arch ? ` ${artifact.arch}` : '';\r\n logger.info(` [${done}/${artifacts.length}] ${options.dryRun ? 'would upload' : 'uploaded'} ${artifact.kind} ${artifact.name}${extra} (${formatBytes(artifact.data.length)}) ${artifact.debugId}`);\r\n });\r\n return artifacts;\r\n}\r\n\r\n// ── Android ──────────────────────────────────────────────────────────────────\r\n\r\n/** Upload an R8/ProGuard `mapping.txt` under the build's UUID (the one the Gradle plugin put in the app). */\r\nexport async function uploadProguard(mappingFile: string, uuid: string, connection: Connection | null, options: NativeUploadOptions = {}) {\r\n if (!UUID.test(uuid)) throw new Error(`--uuid must be a UUID, got \"${uuid}\".`);\r\n const data = readFileSync(mappingFile);\r\n return send(connection, [{ kind: 'proguard', debugId: uuid.toLowerCase(), name: basename(mappingFile), release: options.release, data, gzip: true }], options);\r\n}\r\n\r\n// ── Flutter ──────────────────────────────────────────────────────────────────\r\n\r\nexport interface DartSymbolFile {\r\n path: string;\r\n buildId: string;\r\n os?: string;\r\n arch?: string;\r\n}\r\n\r\nconst DART_ARCH: Record<string, string> = { x86_64: 'x64', x86: 'ia32' };\r\n\r\n/**\r\n * The Dart symbol files in a `--split-debug-info` directory (`app.android-arm64.symbols`, …), or\r\n * the one file given. The debug ID is the ELF GNU build ID — the `build_id` an obfuscated\r\n * stack prints.\r\n */\r\nexport function findDartSymbols(path: string, logger: Logger = consoleLogger()): DartSymbolFile[] {\r\n const files = statSync(path).isDirectory() ? walk(resolve(path)) : [resolve(path)];\r\n const out: DartSymbolFile[] = [];\r\n for (const file of files) {\r\n const named = /\\.symbols$/.test(file);\r\n const data = readFileSync(file);\r\n if (!isElf(data)) {\r\n if (named) logger.warn(`Skipped ${basename(file)}: not an ELF file.`);\r\n continue;\r\n }\r\n const elf = readElf(data);\r\n if (!elf.buildId) {\r\n logger.warn(`Skipped ${basename(file)}: it has no GNU build ID.`);\r\n continue;\r\n }\r\n const match = /\\.([a-z]+)-([a-z0-9_]+)\\.symbols$/.exec(basename(file));\r\n out.push({ path: file, buildId: elf.buildId, os: match?.[1], arch: match?.[2] ?? (elf.arch && (DART_ARCH[elf.arch] ?? elf.arch)) });\r\n }\r\n return out;\r\n}\r\n\r\n/**\r\n * The obfuscation map Flutter writes with\r\n * `--extra-gen-snapshot-options=--save-obfuscation-map=<file>`: `obfuscation.json` or\r\n * `*.obfuscation.json`, in the symbols directory or the directory next to it.\r\n */\r\nexport function findObfuscationMap(symbolsPath: string): string | undefined {\r\n const dir = statSync(symbolsPath).isDirectory() ? resolve(symbolsPath) : dirname(resolve(symbolsPath));\r\n for (const where of [dir, dirname(dir)]) {\r\n let names: string[];\r\n try {\r\n names = readdirSync(where).sort();\r\n } catch {\r\n continue;\r\n }\r\n const found = names.find((n) => n === 'obfuscation.json') ?? names.find((n) => n.endsWith('.obfuscation.json'));\r\n if (found && statSync(join(where, found)).isFile()) return join(where, found);\r\n }\r\n return undefined;\r\n}\r\n\r\n/** The map's contents, checked: a JSON array of obfuscated/original name pairs (flat or nested). */\r\nfunction readObfuscationMap(file: string): Buffer {\r\n const data = readFileSync(file);\r\n let parsed: unknown;\r\n try {\r\n parsed = JSON.parse(data.toString('utf8'));\r\n } catch (error) {\r\n throw new Error(`${file} is not valid JSON (${(error as Error).message}).`);\r\n }\r\n if (!Array.isArray(parsed)) throw new Error(`${file} is not a Dart obfuscation map: expected a JSON array of [obfuscated, original] names.`);\r\n return data;\r\n}\r\n\r\nexport interface DartSymbolsUploadOptions extends NativeUploadOptions {\r\n /** The obfuscation map to upload with the symbols. Default: found next to them (see findObfuscationMap). */\r\n obfuscationMap?: string;\r\n}\r\n\r\nexport async function uploadDartSymbols(path: string, connection: Connection | null, options: DartSymbolsUploadOptions = {}) {\r\n const logger = options.logger ?? consoleLogger();\r\n const files = findDartSymbols(path, logger);\r\n if (files.length === 0) throw new Error(`No Dart symbol files in ${path} — build with \\`flutter build … --obfuscate --split-debug-info=<dir>\\` and pass that directory.`);\r\n logger.info(`${options.dryRun ? 'Would upload' : 'Uploading'} ${files.length} Dart symbol file(s)`);\r\n const artifacts: Artifact[] = files.map((f) => ({\r\n kind: 'dart-symbols',\r\n debugId: f.buildId,\r\n name: basename(f.path),\r\n arch: f.arch,\r\n release: options.release,\r\n data: readFileSync(f.path),\r\n gzip: true,\r\n }));\r\n if (options.obfuscationMap && !existsSync(options.obfuscationMap)) throw new Error(`${options.obfuscationMap} does not exist.`);\r\n const mapFile = options.obfuscationMap ?? findObfuscationMap(path);\r\n if (mapFile) {\r\n const data = readObfuscationMap(mapFile);\r\n // One map serves every architecture of the build: once per build ID.\r\n const buildIds = [...new Set(files.map((f) => f.buildId))];\r\n logger.info(`With obfuscation map ${basename(mapFile)} for ${buildIds.length} build ID(s)`);\r\n for (const debugId of buildIds) {\r\n artifacts.push({ kind: 'dart-obfuscation-map', debugId, name: basename(mapFile), release: options.release, data, gzip: true });\r\n }\r\n } else {\r\n logger.info('No obfuscation map found (build with --extra-gen-snapshot-options=--save-obfuscation-map=build/obfuscation.json, or pass --obfuscation-map): obfuscated names in error messages stay as they are.');\r\n }\r\n artifacts.push(...withSources('flutter', [...new Set(files.map((f) => f.buildId))], options, logger));\r\n return send(connection, artifacts, options);\r\n}\r\n\r\n// ── iOS ──────────────────────────────────────────────────────────────────────\r\n\r\nexport interface DsymImage {\r\n /** The DWARF file inside the .dSYM bundle. */\r\n path: string;\r\n uuid: string;\r\n arch: string;\r\n offset: number;\r\n size: number;\r\n}\r\n\r\n/**\r\n * The binary images in a .dSYM bundle, a folder of them (Xcode's `$DWARF_DSYM_FOLDER_PATH`), or\r\n * a DWARF file itself. Universal files give one image per architecture.\r\n */\r\nexport function findDsymImages(path: string): DsymImage[] {\r\n const root = resolve(path);\r\n const candidates = statSync(root).isDirectory()\r\n ? walk(root).filter((f) => /[\\\\/]Contents[\\\\/]Resources[\\\\/]DWARF[\\\\/][^\\\\/]+$/.test(f))\r\n : [root];\r\n const out: DsymImage[] = [];\r\n for (const file of candidates) {\r\n const data = readFileSync(file);\r\n if (!isMachO(data)) continue;\r\n for (const image of readMachO(data)) out.push({ path: file, ...image });\r\n }\r\n return out;\r\n}\r\n\r\nexport async function uploadDsyms(path: string, connection: Connection | null, options: NativeUploadOptions = {}) {\r\n const logger = options.logger ?? consoleLogger();\r\n const images = findDsymImages(path);\r\n if (images.length === 0) throw new Error(`No dSYM DWARF files in ${path} — pass a .dSYM bundle or the folder that holds them ($DWARF_DSYM_FOLDER_PATH).`);\r\n logger.info(`${options.dryRun ? 'Would upload' : 'Uploading'} ${images.length} dSYM image(s)`);\r\n const cache = new Map<string, Buffer>();\r\n const artifacts: Artifact[] = images.map((image) => {\r\n let data = cache.get(image.path);\r\n if (!data) cache.set(image.path, (data = readFileSync(image.path)));\r\n return {\r\n kind: 'dsym',\r\n debugId: image.uuid,\r\n name: basename(image.path),\r\n arch: image.arch,\r\n release: options.release,\r\n // One architecture's slice of a universal file is a complete Mach-O file on its own.\r\n data: data.subarray(image.offset, image.offset + image.size),\r\n gzip: true,\r\n };\r\n });\r\n // Swift's mangled names, decoded by this Mac's swift-demangle: crashes read \"Cart.total() -> Int\".\r\n const names = swiftNames(images.map((image) => image.path), options.xcodeTool === undefined ? undefined : options.xcodeTool);\r\n if (names && Object.keys(names).length) {\r\n const data = Buffer.from(JSON.stringify({ names }), 'utf8');\r\n logger.info(`With readable names for ${Object.keys(names).length} Swift symbol(s)`);\r\n for (const uuid of new Set(images.map((image) => image.uuid))) {\r\n artifacts.push({ kind: 'symbol-names', debugId: uuid, name: 'swift-names.json', release: options.release, data, gzip: true });\r\n }\r\n } else if (names === null) {\r\n logger.info('Swift names stay mangled: run the upload on a Mac with Xcode (xcrun swift-demangle) to send readable ones.');\r\n }\r\n artifacts.push(...withSources('apple', [...new Set(images.map((image) => image.uuid))], options, logger));\r\n return send(connection, artifacts, options);\r\n}\r\n","/**\r\n * The GNU build ID of an ELF file — what a Dart AOT snapshot prints as `build_id: '…'` in an\r\n * obfuscated stack, and what its `--split-debug-info` symbol file carries too.\r\n */\r\n\r\nconst NT_GNU_BUILD_ID = 3;\r\nconst SHT_NOTE = 7;\r\nconst PT_NOTE = 4;\r\n\r\nexport interface ElfInfo {\r\n /** Lowercase hex, as Dart prints it. */\r\n buildId?: string;\r\n bits: 32 | 64;\r\n littleEndian: boolean;\r\n /** e_machine, as an architecture name where known. */\r\n arch?: string;\r\n}\r\n\r\nconst MACHINES: Record<number, string> = { 3: 'x86', 40: 'arm', 62: 'x86_64', 183: 'arm64', 243: 'riscv64' };\r\n\r\nexport function isElf(data: Uint8Array): boolean {\r\n return data.length >= 16 && data[0] === 0x7f && data[1] === 0x45 && data[2] === 0x4c && data[3] === 0x46;\r\n}\r\n\r\n/** Parse just enough of an ELF file to find its GNU build ID. Throws on a file that is not ELF. */\r\nexport function readElf(data: Uint8Array): ElfInfo {\r\n if (!isElf(data)) throw new Error('not an ELF file');\r\n const bits = data[4] === 2 ? 64 : 32;\r\n const littleEndian = data[5] !== 2;\r\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\r\n const u16 = (o: number) => view.getUint16(o, littleEndian);\r\n const u32 = (o: number) => view.getUint32(o, littleEndian);\r\n const addr = (o: number) => (bits === 64 ? Number(view.getBigUint64(o, littleEndian)) : u32(o));\r\n const info: ElfInfo = { bits, littleEndian, arch: MACHINES[u16(18)] };\r\n\r\n const notes = (offset: number, size: number): string | undefined => {\r\n let p = offset;\r\n const end = Math.min(offset + size, data.length);\r\n while (p + 12 <= end) {\r\n const nameSize = u32(p);\r\n const descSize = u32(p + 4);\r\n const type = u32(p + 8);\r\n const nameStart = p + 12;\r\n const descStart = nameStart + align4(nameSize);\r\n if (descStart + descSize > end) break;\r\n const name = String.fromCharCode(...data.subarray(nameStart, nameStart + Math.max(0, nameSize - 1)));\r\n if (name === 'GNU' && type === NT_GNU_BUILD_ID) return hex(data.subarray(descStart, descStart + descSize));\r\n p = descStart + align4(descSize);\r\n }\r\n return undefined;\r\n };\r\n\r\n // Section headers first (symbol files keep them), then program headers (stripped binaries).\r\n const shoff = addr(bits === 64 ? 0x28 : 0x20);\r\n const shentsize = u16(bits === 64 ? 0x3a : 0x2e);\r\n const shnum = u16(bits === 64 ? 0x3c : 0x30);\r\n for (let i = 0; i < shnum && shoff > 0; i++) {\r\n const h = shoff + i * shentsize;\r\n if (h + shentsize > data.length) break;\r\n if (u32(h + 4) !== SHT_NOTE) continue;\r\n const offset = addr(bits === 64 ? h + 0x18 : h + 0x10);\r\n const size = addr(bits === 64 ? h + 0x20 : h + 0x14);\r\n const id = notes(offset, size);\r\n if (id) return { ...info, buildId: id };\r\n }\r\n const phoff = addr(bits === 64 ? 0x20 : 0x1c);\r\n const phentsize = u16(bits === 64 ? 0x36 : 0x2a);\r\n const phnum = u16(bits === 64 ? 0x38 : 0x2c);\r\n for (let i = 0; i < phnum && phoff > 0; i++) {\r\n const h = phoff + i * phentsize;\r\n if (h + phentsize > data.length) break;\r\n if (u32(h) !== PT_NOTE) continue;\r\n const offset = addr(bits === 64 ? h + 0x08 : h + 0x04);\r\n const size = addr(bits === 64 ? h + 0x20 : h + 0x10);\r\n const id = notes(offset, size);\r\n if (id) return { ...info, buildId: id };\r\n }\r\n return info;\r\n}\r\n\r\nconst align4 = (n: number) => (n + 3) & ~3;\r\n\r\nfunction hex(bytes: Uint8Array): string {\r\n let out = '';\r\n for (const b of bytes) out += b.toString(16).padStart(2, '0');\r\n return out;\r\n}\r\n","/** Walking a directory, and include/exclude patterns. */\r\nimport { readdirSync, statSync } from 'node:fs';\r\nimport { join, relative, sep } from 'node:path';\r\n\r\n/** A glob (`**`, `*`, `?`), a regular expression, or a list of them. */\r\nexport type Pattern = string | RegExp | Array<string | RegExp>;\r\n\r\n/** Every file under `dir`, recursively, as absolute paths. `node_modules` is skipped. */\r\nexport function walk(dir: string): string[] {\r\n const out: string[] = [];\r\n const visit = (current: string) => {\r\n for (const entry of readdirSync(current, { withFileTypes: true })) {\r\n const full = join(current, entry.name);\r\n if (entry.isDirectory()) {\r\n if (entry.name !== 'node_modules') visit(full);\r\n } else if (entry.isFile()) out.push(full);\r\n else if (entry.isSymbolicLink()) {\r\n try {\r\n if (statSync(full).isFile()) out.push(full);\r\n } catch {}\r\n }\r\n }\r\n };\r\n visit(dir);\r\n return out.sort();\r\n}\r\n\r\n/** `path` relative to `dir`, with forward slashes. */\r\nexport function relativePath(dir: string, path: string): string {\r\n return relative(dir, path).split(sep).join('/');\r\n}\r\n\r\n/** A glob as a regular expression over a relative path with forward slashes. */\r\nexport function globToRegExp(glob: string): RegExp {\r\n let out = '';\r\n for (let i = 0; i < glob.length; i++) {\r\n const c = glob[i];\r\n if (c === '*') {\r\n if (glob[i + 1] === '*') {\r\n // `**/` matches any number of directories, including none.\r\n const slash = glob[i + 2] === '/';\r\n out += slash ? '(?:.*/)?' : '.*';\r\n i += slash ? 2 : 1;\r\n } else out += '[^/]*';\r\n } else if (c === '?') out += '[^/]';\r\n else out += /[.+^${}()|[\\]\\\\]/.test(c) ? `\\\\${c}` : c;\r\n }\r\n // A pattern without a slash matches a file name at any depth, as .gitignore does.\r\n return new RegExp(glob.includes('/') ? `^${out}$` : `(?:^|/)${out}$`);\r\n}\r\n\r\nfunction toList(pattern: Pattern | undefined): RegExp[] {\r\n if (pattern === undefined) return [];\r\n return (Array.isArray(pattern) ? pattern : [pattern]).map((p) => (typeof p === 'string' ? globToRegExp(p) : p));\r\n}\r\n\r\n/** A filter over relative paths: in `include` (when given) and not in `exclude`. */\r\nexport function pathFilter(include?: Pattern, exclude?: Pattern): (relativePath: string) => boolean {\r\n const inc = toList(include);\r\n const exc = toList(exclude);\r\n return (path) => (inc.length === 0 || inc.some((r) => r.test(path))) && !exc.some((r) => r.test(path));\r\n}\r\n\r\nexport function formatBytes(bytes: number): string {\r\n if (bytes < 1024) return `${bytes} B`;\r\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;\r\n return `${(bytes / 1024 / 1024).toFixed(1)} MB`;\r\n}\r\n","/**\r\n * The LC_UUID of each architecture in a Mach-O file (thin or universal) — the UUID an iOS crash\r\n * report lists for each binary image, and the key its dSYM is found by.\r\n */\r\n\r\nconst LC_UUID = 0x1b;\r\n\r\nexport interface MachOImage {\r\n /** Uppercase with dashes, as the iOS SDK (`UUID.uuidString`) and Apple's tools print it. */\r\n uuid: string;\r\n arch: string;\r\n /** Where the image is in the file: the whole file, or its slice of a universal one. */\r\n offset: number;\r\n size: number;\r\n}\r\n\r\nconst MH_MAGIC = 0xfeedface;\r\nconst MH_MAGIC_64 = 0xfeedfacf;\r\nconst FAT_MAGIC = 0xcafebabe;\r\nconst FAT_MAGIC_64 = 0xcafebabf;\r\n\r\nexport function isMachO(data: Uint8Array): boolean {\r\n if (data.length < 8) return false;\r\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\r\n const be = view.getUint32(0, false);\r\n const le = view.getUint32(0, true);\r\n return be === FAT_MAGIC || be === FAT_MAGIC_64 || [MH_MAGIC, MH_MAGIC_64].includes(le) || [MH_MAGIC, MH_MAGIC_64].includes(be);\r\n}\r\n\r\nexport function archName(cpuType: number, cpuSubtype: number): string {\r\n const sub = cpuSubtype & 0x00ffffff;\r\n switch (cpuType) {\r\n case 0x0100000c:\r\n return sub === 2 ? 'arm64e' : 'arm64';\r\n case 0x0200000c:\r\n return 'arm64_32';\r\n case 0x0000000c:\r\n return sub === 9 ? 'armv7' : sub === 11 ? 'armv7s' : sub === 12 ? 'armv7k' : 'arm';\r\n case 0x01000007:\r\n return sub === 8 ? 'x86_64h' : 'x86_64';\r\n case 0x00000007:\r\n return 'i386';\r\n default:\r\n return `cpu${cpuType}`;\r\n }\r\n}\r\n\r\n/** The images in a Mach-O file: one for a thin file, one per slice for a universal one. */\r\nexport function readMachO(data: Uint8Array): MachOImage[] {\r\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\r\n const magic = view.getUint32(0, false);\r\n if (magic === FAT_MAGIC || magic === FAT_MAGIC_64) {\r\n const wide = magic === FAT_MAGIC_64;\r\n const count = view.getUint32(4, false);\r\n const images: MachOImage[] = [];\r\n for (let i = 0; i < count; i++) {\r\n const h = 8 + i * (wide ? 32 : 20);\r\n const offset = wide ? Number(view.getBigUint64(h + 8, false)) : view.getUint32(h + 8, false);\r\n const size = wide ? Number(view.getBigUint64(h + 16, false)) : view.getUint32(h + 12, false);\r\n images.push(...readThin(data.subarray(offset, offset + size)).map((image) => ({ ...image, offset })));\r\n }\r\n return images;\r\n }\r\n return readThin(data);\r\n}\r\n\r\nfunction readThin(data: Uint8Array): MachOImage[] {\r\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\r\n let little: boolean;\r\n if ([MH_MAGIC, MH_MAGIC_64].includes(view.getUint32(0, true))) little = true;\r\n else if ([MH_MAGIC, MH_MAGIC_64].includes(view.getUint32(0, false))) little = false;\r\n else throw new Error('not a Mach-O file');\r\n const wide = view.getUint32(0, little) === MH_MAGIC_64;\r\n const cpuType = view.getUint32(4, little);\r\n const cpuSubtype = view.getUint32(8, little);\r\n const ncmds = view.getUint32(16, little);\r\n let p = wide ? 32 : 28;\r\n for (let i = 0; i < ncmds && p + 8 <= data.length; i++) {\r\n const cmd = view.getUint32(p, little);\r\n const size = view.getUint32(p + 4, little);\r\n if (cmd === LC_UUID && p + 24 <= data.length) {\r\n return [{ uuid: formatUuid(data.subarray(p + 8, p + 24)), arch: archName(cpuType, cpuSubtype), offset: 0, size: data.length }];\r\n }\r\n if (size < 8) break;\r\n p += size;\r\n }\r\n return [];\r\n}\r\n\r\nfunction formatUuid(bytes: Uint8Array): string {\r\n let hex = '';\r\n for (const b of bytes) hex += b.toString(16).padStart(2, '0');\r\n hex = hex.toUpperCase();\r\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\r\n}\r\n","/**\r\n * Readable names for a dSYM's Swift symbols, uploaded beside it (`kind: symbol-names`), so a\r\n * crash reads \"Cart.total() -> Int\", not \"$s9CrashTest4CartV5totalSiyF\". Decoded by Xcode's own\r\n * `swift-demangle` — exactly the toolchain that compiled the app — on the Mac that uploads the\r\n * dSYMs (an Xcode build phase or a macOS CI job). Elsewhere, or without Xcode, nothing is added.\r\n */\r\nimport { spawnSync } from 'node:child_process';\r\nimport { readFileSync } from 'node:fs';\r\n\r\n/** Runs an Xcode tool with `input` on stdin; its stdout, or null when it isn't there or fails. */\r\nexport type XcodeTool = (tool: string, args: string[], input?: string) => string | null;\r\n\r\nexport const xcrun: XcodeTool = (tool, args, input) => {\r\n const result = spawnSync('xcrun', [tool, ...args], { input, encoding: 'utf8', maxBuffer: 512 * 1024 * 1024 });\r\n return result.status === 0 && typeof result.stdout === 'string' ? result.stdout : null;\r\n};\r\n\r\n/**\r\n * Swift 4.2+ mangled names anywhere in a DWARF file: its symbol table and its debug strings. A\r\n * Release build inlines functions, which then exist only in the debug info (DW_AT_linkage_name)\r\n * — what llvm-symbolizer names an inlined frame by — so the symbol table alone is not enough.\r\n */\r\nconst SWIFT = /\\$s[0-9A-Za-z_$]{3,}/g;\r\n\r\n/** What swift-demangle calls data symbols (metadata, descriptors, records), not code. */\r\nconst NOT_CODE = /^(type metadata(?! accessor)|full type metadata|(nominal type|protocol|protocol conformance|associated (type|conformance)|method|property|module|extension|anonymous|reflection metadata|opaque type) descriptor|reflection metadata|protocol (requirements base|witness table)(?! accessor)|value witness table|field offset|enum case for|lazy cache variable|demangling cache variable|flag for loading|metaclass for|class metadata base offset|objc metaclass|type metadata (pattern|completion|instantiation cache)|generic (type|protocol witness table) (instantiation cache|pattern))/;\r\n\r\n/** The mangled Swift names in a DWARF file (read as bytes; no tools needed). */\r\nexport function mangledNamesIn(data: Buffer): Set<string> {\r\n return new Set(data.toString('latin1').match(SWIFT) ?? []);\r\n}\r\n\r\n/**\r\n * Mangled → readable for the Swift symbols in these DWARF files. Null when the tools aren't\r\n * there (not a Mac, no Xcode); empty when the files have no Swift.\r\n */\r\nexport function swiftNames(\r\n files: string[],\r\n tool: XcodeTool | null = process.platform === 'darwin' ? xcrun : null,\r\n read: (file: string) => Buffer = readFileSync,\r\n): Record<string, string> | null {\r\n if (!tool) return null;\r\n const symbols = new Set<string>();\r\n for (const file of new Set(files)) {\r\n for (const name of mangledNamesIn(read(file))) symbols.add(name);\r\n }\r\n if (!symbols.size) return {};\r\n const mangled = [...symbols];\r\n const decoded = tool('swift-demangle', ['--simplified', '--compact'], `${mangled.join('\\n')}\\n`);\r\n if (decoded === null) return null;\r\n const lines = decoded.split('\\n');\r\n const out: Record<string, string> = {};\r\n mangled.forEach((name, i) => {\r\n const readable = lines[i]?.trim();\r\n // Descriptors and metadata records are data, never a frame: left out, the map is smaller.\r\n if (readable && readable !== name && !NOT_CODE.test(readable)) out[name] = readable;\r\n });\r\n return out;\r\n}\r\n","/**\r\n * Source bundles: the app's own source files, uploaded with a build's symbols so an error's\r\n * frames show the exact code of the build that crashed — without a linked repository.\r\n *\r\n * On by default for `dart-symbols upload` and `dsym upload`; `--no-sources` turns it off. The\r\n * bundle is gzipped JSON, {\"files\": {\"<path from the project root>\": \"<text>\"}}, uploaded once per\r\n * build ID the errors can carry.\r\n */\r\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\r\nimport { dirname, join, resolve } from 'node:path';\r\nimport type { Artifact } from './api';\r\nimport { relativePath } from './files';\r\n\r\n/** Folders that are never the app's own code: dependencies, build output, tool caches. */\r\nconst SKIP_DIRS = new Set([\r\n 'node_modules', '.git', '.svn', '.hg', 'build', '.build', '.dart_tool', '.pub-cache', '.gradle', '.idea', '.vscode',\r\n 'test', 'integration_test', 'Pods', 'Carthage', 'DerivedData', 'xcuserdata', '.swiftpm', 'SourcePackages', 'vendor', '.fvm', '.symlinks', 'ephemeral',\r\n]);\r\n\r\n/** Each file at most this big, and the bundle at most this much: an app's code, not its assets. */\r\nconst MAX_FILE_BYTES = 1024 * 1024;\r\nconst MAX_TOTAL_BYTES = 50 * 1024 * 1024;\r\nconst MAX_FILES = 20_000;\r\n\r\nexport interface CollectedSources {\r\n root: string;\r\n files: Record<string, string>;\r\n count: number;\r\n bytes: number;\r\n /** Files left out for being over the caps. */\r\n skipped: number;\r\n}\r\n\r\n/** The source files under `root` with these extensions, by path from `root`. */\r\nexport function collectSources(root: string, extensions: string[], skipDirs: string[] = []): CollectedSources {\r\n const skip = new Set([...SKIP_DIRS, ...skipDirs]);\r\n const wanted = new Set(extensions.map((e) => e.toLowerCase()));\r\n const out: CollectedSources = { root, files: {}, count: 0, bytes: 0, skipped: 0 };\r\n const visit = (dir: string) => {\r\n let entries;\r\n try {\r\n entries = readdirSync(dir, { withFileTypes: true });\r\n } catch {\r\n return;\r\n }\r\n for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {\r\n const full = join(dir, entry.name);\r\n if (entry.isDirectory()) {\r\n // Tests never crash in the shipped app: test/, integration_test/, Xcode's ShopTests/ShopUITests.\r\n if (!skip.has(entry.name) && !/\\.(xcassets|dSYM)$|Tests$/.test(entry.name)) visit(full);\r\n continue;\r\n }\r\n if (!entry.isFile()) continue;\r\n const dot = entry.name.lastIndexOf('.');\r\n if (dot < 0 || !wanted.has(entry.name.slice(dot).toLowerCase())) continue;\r\n const size = statSync(full).size;\r\n if (size > MAX_FILE_BYTES || out.bytes + size > MAX_TOTAL_BYTES || out.count >= MAX_FILES) {\r\n out.skipped += 1;\r\n continue;\r\n }\r\n out.files[relativePath(root, full)] = readFileSync(full, 'utf8');\r\n out.count += 1;\r\n out.bytes += size;\r\n }\r\n };\r\n visit(root);\r\n return out;\r\n}\r\n\r\n/** The bundle as uploaded, once per build ID. */\r\nexport function sourceBundleArtifacts(sources: CollectedSources, buildIds: string[], release?: string): Artifact[] {\r\n if (!sources.count) return [];\r\n const data = Buffer.from(JSON.stringify({ files: sources.files }), 'utf8');\r\n return [...new Set(buildIds)].map((debugId) => ({ kind: 'source-bundle', debugId, name: 'sources.json', release, data, gzip: true }));\r\n}\r\n\r\n/** The nearest folder at or above `from` that has `marker` (pubspec.yaml, an .xcodeproj…). */\r\nexport function projectRoot(from: string, marker: (dir: string) => boolean): string | null {\r\n let dir = resolve(from);\r\n for (;;) {\r\n if (marker(dir)) return dir;\r\n const parent = dirname(dir);\r\n if (parent === dir) return null;\r\n dir = parent;\r\n }\r\n}\r\n\r\nexport const FLUTTER_SOURCES = ['.dart'];\r\nexport const APPLE_SOURCES = ['.swift', '.m', '.mm', '.h', '.c', '.cc', '.cpp', '.hpp'];\r\n\r\n/** A Flutter app's root: where pubspec.yaml is. */\r\nexport const isFlutterRoot = (dir: string) => existsSync(join(dir, 'pubspec.yaml'));\r\n\r\n/** An Xcode project's root: the folder with the .xcodeproj / .xcworkspace or Package.swift. */\r\nexport const isAppleRoot = (dir: string) => {\r\n try {\r\n return existsSync(join(dir, 'Package.swift')) || readdirSync(dir).some((name) => name.endsWith('.xcodeproj') || name.endsWith('.xcworkspace'));\r\n } catch {\r\n return false;\r\n }\r\n};\r\n","/**\r\n * `zharp react-native upload`: a React Native release build's source map, filed under the debug\r\n * ID @zharp/react-native/metro gave the bundle, so its errors read as the app's own source.\r\n *\r\n * The bundle is Hermes bytecode (or plain JS on JSC); either way it holds the marker string\r\n * `zharp-debug-id:<uuid>` the serializer wrote. The map is the composed one (Metro's mapped\r\n * through Hermes', as React Native's build writes it), with the sources inside.\r\n */\r\nimport { existsSync, readFileSync } from 'node:fs';\r\nimport { basename } from 'node:path';\r\nimport { walk } from './files';\r\nimport { uploadArtifact, type Artifact, type Connection } from './api';\r\nimport { formatBytes } from './files';\r\nimport { consoleLogger, type Logger } from './log';\r\n\r\nconst MARKER = /zharp-debug-id:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/;\r\n\r\n/** The debug ID a bundle was built with, or null when it was built without the Zharp serializer. */\r\nexport function bundleDebugId(bundle: Buffer): string | null {\r\n return MARKER.exec(bundle.toString('latin1'))?.[1] ?? null;\r\n}\r\n\r\nexport interface ReactNativeUploadOptions {\r\n release?: string;\r\n dryRun?: boolean;\r\n logger?: Logger;\r\n fetch?: typeof fetch;\r\n}\r\n\r\nexport async function uploadReactNative(bundlePath: string, mapPath: string, connection: Connection | null, options: ReactNativeUploadOptions = {}): Promise<Artifact | null> {\r\n const logger = options.logger ?? consoleLogger();\r\n const id = bundleDebugId(readFileSync(bundlePath));\r\n if (!id) {\r\n throw new Error(`${bundlePath} has no Zharp debug ID — add withZharpConfig from @zharp/react-native/metro to metro.config.js, then build again.`);\r\n }\r\n const map = JSON.parse(readFileSync(mapPath, 'utf8'));\r\n map.debugId = id;\r\n const withSources = Array.isArray(map.sourcesContent) ? map.sourcesContent.filter(Boolean).length : 0;\r\n const data = Buffer.from(JSON.stringify(map), 'utf8');\r\n // Keyed by the file name frames name it by: \"index.android.bundle\", \"main.jsbundle\".\r\n const artifact: Artifact = { kind: 'sourcemap', debugId: id, name: basename(bundlePath), release: options.release, data, gzip: true };\r\n if (!options.dryRun) {\r\n if (!connection) throw new Error('No connection to upload to.');\r\n await uploadArtifact(connection, artifact, { fetch: options.fetch });\r\n }\r\n logger.info(`${options.dryRun ? 'Would upload' : 'Uploaded'} the source map of ${basename(bundlePath)} (${formatBytes(data.length)}, ${withSources} source file(s) inside) ${id}`);\r\n return artifact;\r\n}\r\n\r\n/**\r\n * Every bundle an `npx expo export` (EAS Update) wrote under `dir` — `_expo/static/js/<platform>/\r\n * *.hbc` or `*.js`, each with its `.map` — uploaded under its own debug ID.\r\n */\r\nexport async function uploadReactNativeDir(dir: string, connection: Connection | null, options: ReactNativeUploadOptions = {}): Promise<Artifact[]> {\r\n const logger = options.logger ?? consoleLogger();\r\n const bundles = walk(dir).filter((file) => /\\.(hbc|js|bundle|jsbundle)$/.test(file) && existsSync(`${file}.map`));\r\n if (!bundles.length) throw new Error(`No bundles with source maps in ${dir} — export with \\`npx expo export --source-maps\\`.`);\r\n const out: Artifact[] = [];\r\n for (const bundle of bundles) {\r\n if (!bundleDebugId(readFileSync(bundle))) {\r\n logger.info(` ${basename(bundle)}: no Zharp debug ID (metro.config.js without withZharpConfig?), skipped`);\r\n continue;\r\n }\r\n const artifact = await uploadReactNative(bundle, `${bundle}.map`, connection, options);\r\n if (artifact) out.push(artifact);\r\n }\r\n return out;\r\n}\r\n","/**\r\n * Source maps for JavaScript: inject debug IDs into a build's output, upload each file and its\r\n * map, and delete the maps so they are not served.\r\n */\r\nimport { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';\r\nimport { dirname, isAbsolute, resolve } from 'node:path';\r\nimport { eachLimit, uploadArtifact, type Connection } from './api';\r\nimport { existingDebugId, injectCode, injectMap, sourceMappingUrl, withoutSourceMappingUrl } from './debug-id';\r\nimport { formatBytes, pathFilter, relativePath, walk, type Pattern } from './files';\r\nimport { consoleLogger, type Logger } from './log';\r\n\r\nconst JS_FILE = /\\.(?:js|mjs|cjs)$/;\r\n\r\nexport interface SourceFile {\r\n /** Absolute path of the JavaScript file. */\r\n file: string;\r\n /** Absolute path of its source map. */\r\n map: string;\r\n /** Path of the file relative to the directory, with forward slashes. */\r\n name: string;\r\n mapName: string;\r\n}\r\n\r\nexport interface FindOptions {\r\n include?: Pattern;\r\n exclude?: Pattern;\r\n /** Only these files (absolute paths) — the bundler plugins pass what the build wrote. */\r\n files?: string[];\r\n}\r\n\r\n/** The source map a JS file has: `<file>.map` next to it, or the file its `sourceMappingURL` names. */\r\nexport function mapFor(file: string, code?: string): string | undefined {\r\n const sibling = `${file}.map`;\r\n if (existsSync(sibling)) return sibling;\r\n const url = sourceMappingUrl(code ?? readFileSync(file, 'utf8'));\r\n if (!url || /^[a-z][a-z0-9+.-]*:/i.test(url)) return undefined; // data:, http:… are not files here\r\n let path: string;\r\n try {\r\n path = decodeURIComponent(url.split(/[?#]/)[0]);\r\n } catch {\r\n return undefined;\r\n }\r\n const full = isAbsolute(path) ? path : resolve(dirname(file), path);\r\n return existsSync(full) ? full : undefined;\r\n}\r\n\r\n/** Every JS file under `dir` that has a source map. */\r\nexport function findSourceFiles(dir: string, options: FindOptions = {}): SourceFile[] {\r\n const root = resolve(dir);\r\n const keep = pathFilter(options.include, options.exclude);\r\n const candidates = options.files ? options.files.map((f) => resolve(f)) : walk(root);\r\n const out: SourceFile[] = [];\r\n for (const file of candidates) {\r\n if (!JS_FILE.test(file) || !existsSync(file)) continue;\r\n const name = relativePath(root, file);\r\n if (!keep(name)) continue;\r\n const map = mapFor(file);\r\n if (map) out.push({ file, map, name, mapName: relativePath(root, map) });\r\n }\r\n return out;\r\n}\r\n\r\nexport interface InjectOptions extends FindOptions {\r\n /** Remove the `sourceMappingURL` comment too — for maps that are deleted after upload. */\r\n stripSourceMappingUrl?: boolean;\r\n dryRun?: boolean;\r\n logger?: Logger;\r\n}\r\n\r\nexport interface InjectedFile extends SourceFile {\r\n debugId: string;\r\n /** False when the file already had this debug ID. */\r\n changed: boolean;\r\n}\r\n\r\n/**\r\n * Add a debug ID to every JS file under `dir` that has a source map, and to the map. Running it\r\n * again changes nothing: a file that has a debug ID keeps it.\r\n */\r\nexport function injectDirectory(dir: string, options: InjectOptions = {}): InjectedFile[] {\r\n const logger = options.logger ?? consoleLogger();\r\n const files = findSourceFiles(dir, options);\r\n const out: InjectedFile[] = [];\r\n const noSourcesContent: string[] = [];\r\n for (const source of files) {\r\n const code = readFileSync(source.file, 'utf8');\r\n const injected = injectCode(code, { stripSourceMappingUrl: options.stripSourceMappingUrl });\r\n let map;\r\n try {\r\n map = injectMap(readFileSync(source.map, \"utf8\"), injected.debugId, source.map);\r\n } catch (error) {\r\n logger.warn(`Skipped ${source.name}: ${source.mapName} is not a readable source map (${(error as Error).message}).`);\r\n continue;\r\n }\r\n if (!options.dryRun) {\r\n if (injected.changed) writeFileSync(source.file, injected.code);\r\n if (map.changed) writeFileSync(source.map, map.text);\r\n }\r\n if (!map.hasSourcesContent) noSourcesContent.push(source.mapName);\r\n const changed = injected.changed || map.changed;\r\n out.push({ ...source, debugId: injected.debugId, changed });\r\n logger.info(`${changed ? (options.dryRun ? 'would inject' : 'injected') : 'already has'} ${injected.debugId} ${source.name}`);\r\n }\r\n if (noSourcesContent.length) {\r\n logger.warn(\r\n `${noSourcesContent.length} source map(s) have no sourcesContent, so Zharp can show original names and lines but not the code around them: ${noSourcesContent.slice(0, 3).join(', ')}${noSourcesContent.length > 3 ? ', …' : ''}`,\r\n );\r\n }\r\n if (out.length === 0) logger.warn(`No JavaScript files with source maps found in ${dir}.`);\r\n return out;\r\n}\r\n\r\nexport interface UploadOptions extends FindOptions {\r\n release?: string;\r\n /** Delete the .map files once they are uploaded. */\r\n deleteAfter?: boolean;\r\n /** Also strip the `sourceMappingURL` comments that pointed at deleted maps. */\r\n stripSourceMappingUrl?: boolean;\r\n dryRun?: boolean;\r\n concurrency?: number;\r\n logger?: Logger;\r\n fetch?: typeof fetch;\r\n retries?: number;\r\n}\r\n\r\nexport interface UploadResult {\r\n files: number;\r\n artifacts: number;\r\n bytes: number;\r\n deleted: string[];\r\n /** Files with a map but no debug ID: run inject first. */\r\n skipped: string[];\r\n}\r\n\r\n/**\r\n * Upload every JS file under `dir` that has a debug ID, with its source map, keyed by that ID.\r\n * `connection` may be null in a dry run.\r\n */\r\nexport async function uploadSourcemaps(dir: string, connection: Connection | null, options: UploadOptions = {}): Promise<UploadResult> {\r\n const logger = options.logger ?? consoleLogger();\r\n const files = findSourceFiles(dir, options);\r\n const result: UploadResult = { files: 0, artifacts: 0, bytes: 0, deleted: [], skipped: [] };\r\n const work: Array<{ source: SourceFile; debugId: string; code: Buffer; map: Buffer }> = [];\r\n for (const source of files) {\r\n const code = readFileSync(source.file);\r\n const debugId = existingDebugId(code.toString('utf8'));\r\n if (!debugId) {\r\n result.skipped.push(source.name);\r\n continue;\r\n }\r\n work.push({ source, debugId, code, map: readFileSync(source.map) });\r\n }\r\n if (result.skipped.length) {\r\n logger.warn(`${result.skipped.length} file(s) have a source map but no debug ID — run \\`zharp sourcemaps inject\\` first: ${result.skipped.slice(0, 3).join(', ')}${result.skipped.length > 3 ? ', …' : ''}`);\r\n }\r\n if (work.length === 0) {\r\n logger.warn(`Nothing to upload in ${dir}.`);\r\n return result;\r\n }\r\n\r\n const total = work.length;\r\n logger.info(`${options.dryRun ? 'Would upload' : 'Uploading'} ${total} file(s) and their source maps${options.release ? ` for release ${options.release}` : ''}${connection ? ` to ${connection.url}, app ${connection.app}` : ''}`);\r\n let done = 0;\r\n await eachLimit(work, options.concurrency ?? 4, async ({ source, debugId, code, map }) => {\r\n const size = code.length + map.length;\r\n if (!options.dryRun) {\r\n if (!connection) throw new Error('No connection to upload to.');\r\n const common = { debugId, release: options.release };\r\n const opts = { fetch: options.fetch, retries: options.retries };\r\n await uploadArtifact(connection, { ...common, kind: 'minified-source', name: source.name, data: code }, opts);\r\n await uploadArtifact(connection, { ...common, kind: 'sourcemap', name: source.mapName, data: map }, opts);\r\n }\r\n done += 1;\r\n result.files += 1;\r\n result.artifacts += 2;\r\n result.bytes += size;\r\n logger.info(` [${done}/${total}] ${options.dryRun ? 'would upload' : 'uploaded'} ${source.name} + ${source.mapName} (${formatBytes(size)}) ${debugId}`);\r\n });\r\n\r\n if (options.deleteAfter && !options.dryRun) {\r\n result.deleted = deleteSourcemaps(work.map((w) => w.source), { stripSourceMappingUrl: options.stripSourceMappingUrl });\r\n logger.info(`Deleted ${result.deleted.length} source map(s) from the output.`);\r\n }\r\n logger.info(`${options.dryRun ? 'Dry run: would have uploaded' : 'Uploaded'} ${result.artifacts} artifact(s), ${formatBytes(result.bytes)}.`);\r\n return result;\r\n}\r\n\r\n/** Delete these files' source maps (and, if asked, the comments pointing at them). */\r\nexport function deleteSourcemaps(files: SourceFile[], options: { stripSourceMappingUrl?: boolean } = {}): string[] {\r\n const deleted: string[] = [];\r\n for (const source of files) {\r\n if (options.stripSourceMappingUrl && existsSync(source.file)) {\r\n const code = readFileSync(source.file, 'utf8');\r\n const stripped = withoutSourceMappingUrl(code);\r\n if (stripped !== code) writeFileSync(source.file, stripped);\r\n }\r\n if (existsSync(source.map)) {\r\n unlinkSync(source.map);\r\n deleted.push(source.mapName);\r\n }\r\n }\r\n return deleted;\r\n}\r\n","/**\r\n * Debug IDs for JavaScript, after the TC39 source map \"debug ID\" proposal: one UUID per emitted\r\n * file, written into the file (`//# debugId=<uuid>`) and into its source map (`\"debugId\"`), so an\r\n * error's frames can be matched to the exact map whatever URL the file was served from.\r\n *\r\n * Besides the comment, each file gets one line that registers it at runtime — the SDKs read\r\n * `globalThis.__zharpDebugIds` to know which build each file in a stack came from.\r\n */\r\nimport { createHash } from 'node:crypto';\r\nimport { existsSync, readFileSync, statSync } from 'node:fs';\r\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\r\nimport { fileURLToPath } from 'node:url';\r\n\r\nexport const DEBUG_ID_COMMENT = '//# debugId=';\r\nconst DEBUG_ID_PATTERN = /^\\/\\/# debugId=([0-9a-fA-F-]{36})\\s*$/m;\r\nconst SOURCE_MAPPING_URL = /^\\/\\/[#@] sourceMappingURL=(.*?)\\s*$/;\r\n\r\n/**\r\n * The UUID for a file's content: the first 16 bytes of its SHA-256, with the version and variant\r\n * bits of a v4 UUID. The same output always gets the same ID, so a rebuild of unchanged code\r\n * does not need a new upload.\r\n */\r\nexport function debugIdFromContent(content: string | Uint8Array): string {\r\n const bytes = createHash('sha256').update(content).digest().subarray(0, 16);\r\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\r\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\r\n const hex = bytes.toString('hex');\r\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\r\n}\r\n\r\n/**\r\n * The runtime registration: ES5, so it is safe in any bundle whatever its target, and wrapped in\r\n * a try so it can never break the file it is in. The key is a stack taken inside the file — its\r\n * top frame is the file's own URL or path, as the runtime names it.\r\n */\r\nexport function registrationSnippet(debugId: string): string {\r\n return (\r\n ';!function(){try{var g=\"undefined\"!=typeof globalThis?globalThis:\"undefined\"!=typeof self?self:' +\r\n '\"undefined\"!=typeof window?window:\"undefined\"!=typeof global?global:{},s=(new Error).stack;' +\r\n `s&&((g.__zharpDebugIds=g.__zharpDebugIds||{})[s]=\"${debugId}\")}catch(e){}}();`\r\n );\r\n}\r\n\r\n/** The debug ID already in a file, if it has one. */\r\nexport function existingDebugId(code: string): string | undefined {\r\n // Only at the end of the file: a bundle may contain another file's comment in its middle.\r\n const lines = code.trimEnd().split('\\n');\r\n for (let i = lines.length - 1; i >= 0 && i >= lines.length - 4; i--) {\r\n const match = DEBUG_ID_PATTERN.exec(lines[i].trim());\r\n if (match) return match[1].toLowerCase();\r\n }\r\n return undefined;\r\n}\r\n\r\n/** Whether the file's tail already registers it at runtime. */\r\nexport function hasRegistration(code: string): boolean {\r\n return code.slice(-2000).includes('.__zharpDebugIds=');\r\n}\r\n\r\n/** The `sourceMappingURL` the file's last line points at, if any (data: URLs included). */\r\nexport function sourceMappingUrl(code: string): string | undefined {\r\n const lines = code.trimEnd().split('\\n');\r\n for (let i = lines.length - 1; i >= 0 && i >= lines.length - 3; i--) {\r\n const match = SOURCE_MAPPING_URL.exec(lines[i].trim());\r\n if (match) return match[1];\r\n }\r\n return undefined;\r\n}\r\n\r\nexport interface InjectedCode {\r\n code: string;\r\n debugId: string;\r\n /** False when the file already had a debug ID: nothing was changed. */\r\n changed: boolean;\r\n}\r\n\r\n/**\r\n * The file with its debug ID: the registration line and the comment, appended after the code —\r\n * before a trailing `sourceMappingURL` comment, if there is one. Appending leaves every existing\r\n * line and column where it was, so the source map stays valid without being rewritten.\r\n *\r\n * A file that already has a debug ID is returned as it is, with that ID.\r\n */\r\nexport function injectCode(code: string, options: { stripSourceMappingUrl?: boolean } = {}): InjectedCode {\r\n const existing = existingDebugId(code);\r\n const eol = code.includes('\\r\\n') ? '\\r\\n' : '\\n';\r\n if (existing) {\r\n let out = code;\r\n // A bundler that writes debug IDs itself (Rollup's sourcemapDebugIds, webpack's\r\n // `-debugids` devtools, Turbopack) adds the comment but not Zharp's registration.\r\n if (!hasRegistration(code)) {\r\n const lines = code.split(/\\r?\\n/);\r\n let at = lines.length - 1;\r\n while (at > 0 && !lines[at].trim().startsWith(DEBUG_ID_COMMENT)) at--;\r\n lines.splice(at, 0, registrationSnippet(existing));\r\n out = lines.join(eol);\r\n }\r\n if (options.stripSourceMappingUrl) out = withoutSourceMappingUrl(out);\r\n return { code: out, debugId: existing, changed: out !== code };\r\n }\r\n const debugId = debugIdFromContent(code);\r\n const lines = code.split(/\\r?\\n/);\r\n // The trailing sourceMappingURL comment (and the blank lines after it) stays last.\r\n let tail: string[] = [];\r\n let end = lines.length;\r\n while (end > 0 && lines[end - 1].trim() === '') end--;\r\n if (end > 0 && SOURCE_MAPPING_URL.test(lines[end - 1].trim())) {\r\n tail = options.stripSourceMappingUrl ? [] : [lines[end - 1]];\r\n end--;\r\n }\r\n const body = lines.slice(0, end);\r\n const out = [...body, registrationSnippet(debugId), `${DEBUG_ID_COMMENT}${debugId}`, ...tail].join(eol) + eol;\r\n return { code: out, debugId, changed: true };\r\n}\r\n\r\n/** The code without its trailing `sourceMappingURL` comment — for maps that are not shipped. */\r\nexport function withoutSourceMappingUrl(code: string): string {\r\n const lines = code.split(/\\r?\\n/);\r\n const eol = code.includes('\\r\\n') ? '\\r\\n' : '\\n';\r\n let end = lines.length;\r\n while (end > 0 && lines[end - 1].trim() === '') end--;\r\n if (end > 0 && SOURCE_MAPPING_URL.test(lines[end - 1].trim())) return lines.slice(0, end - 1).join(eol) + eol;\r\n return code;\r\n}\r\n\r\n/**\r\n * The source map with the debug ID in it, under both spellings in use (`debugId` from the TC39\r\n * proposal, `debug_id` from earlier tooling). Returns the text unchanged when it already matches.\r\n */\r\nexport function injectMap(mapText: string, debugId: string, mapPath?: string): { text: string; changed: boolean; hasSourcesContent: boolean } {\r\n const map = JSON.parse(mapText);\r\n if (!map || typeof map !== 'object') throw new Error('not a source map');\r\n // The build machine has the sources: the app's own files go into the map, so the code shows.\r\n const filled = mapPath ? fillSourcesContent(map, mapPath) : 0;\r\n const hasSourcesContent = Array.isArray(map.sourcesContent) && map.sourcesContent.some((s: unknown) => typeof s === 'string');\r\n if (!filled && map.debugId === debugId && map.debug_id === debugId) return { text: mapText, changed: false, hasSourcesContent };\r\n map.debugId = debugId;\r\n map.debug_id = debugId;\r\n return { text: JSON.stringify(map), changed: true, hasSourcesContent };\r\n}\r\n\r\nconst MAX_SOURCE_BYTES = 1_000_000;\r\n\r\n/** A map source's path on this machine, for the bundlers' ways of naming them. */\r\nexport function sourcePathCandidates(source: string, mapPath: string, sourceRoot = ''): string[] {\r\n const mapDir = dirname(mapPath);\r\n // turbopack:///[project]/app/page.tsx, webpack://_N_E/./app/page.tsx, webpack:///src/x.ts, file:///abs\r\n let stripped = source;\r\n let projectRelative = false;\r\n if (/^turbopack:\\/\\/\\/\\[project\\]\\//.test(source)) {\r\n stripped = source.replace(/^turbopack:\\/\\/\\/\\[project\\]\\//, '');\r\n projectRelative = true;\r\n } else if (/^webpack:\\/\\//.test(source)) {\r\n stripped = source.replace(/^webpack:\\/\\/[^/]*\\//, '').replace(/^\\.\\//, '');\r\n projectRelative = true;\r\n } else if (/^file:\\/\\//.test(source)) {\r\n try {\r\n return [fileURLToPath(source)];\r\n } catch {\r\n return [];\r\n }\r\n } else if (/^[a-z][\\w+.-]*:\\/\\//i.test(source)) {\r\n return [];\r\n }\r\n if (isAbsolute(stripped)) return [stripped];\r\n const out = [resolve(mapDir, sourceRoot, stripped)];\r\n if (projectRelative) {\r\n // Relative to the project: the nearest folder above the map that has a package.json.\r\n for (let dir = mapDir, i = 0; i < 12; i++) {\r\n if (existsSync(join(dir, 'package.json'))) {\r\n out.unshift(join(dir, stripped));\r\n break;\r\n }\r\n const up = dirname(dir);\r\n if (up === dir) break;\r\n dir = up;\r\n }\r\n }\r\n return out;\r\n}\r\n\r\n/** Fills the app's own sources into a map that left them out. Returns how many it filled. */\r\nexport function fillSourcesContent(map: any, mapPath: string): number {\r\n if (!Array.isArray(map.sources)) return 0;\r\n const contents: Array<string | null> = Array.isArray(map.sourcesContent) ? [...map.sourcesContent] : [];\r\n let filled = 0;\r\n map.sources.forEach((source: unknown, i: number) => {\r\n if (typeof contents[i] === 'string' || typeof source !== 'string') return;\r\n if (/node_modules|^\\[externals\\]|\\(ignored\\)|^webpack\\/runtime/.test(source)) return;\r\n for (const path of sourcePathCandidates(source, mapPath, typeof map.sourceRoot === 'string' ? map.sourceRoot : '')) {\r\n if (/[\\\\/]node_modules[\\\\/]/.test(path)) continue;\r\n try {\r\n const stat = statSync(path);\r\n if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) continue;\r\n contents[i] = readFileSync(path, 'utf8');\r\n filled++;\r\n break;\r\n } catch {\r\n // Not here: the next candidate.\r\n }\r\n }\r\n });\r\n if (filled) {\r\n while (contents.length < map.sources.length) contents.push(null);\r\n map.sourcesContent = contents.map((c) => (typeof c === 'string' ? c : null));\r\n }\r\n return filled;\r\n}\r\n","export const VERSION = '0.3.0';\r\n","/**\r\n * `zharp init`: connect this project to Zharp and wire the SDK in.\r\n *\r\n * 1. find what the project is (Next.js, React with Vite, NestJS…);\r\n * 2. connect it in the browser — sign in, pick the workspace and app, approve;\r\n * 3. show every change, and make them only on a yes (`--yes` for scripts);\r\n * 4. install the packages, write the keys to an env file git ignores;\r\n * 5. send a test error and print where to see it.\r\n */\r\nimport { spawnSync } from 'node:child_process';\r\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\r\nimport { createInterface } from 'node:readline/promises';\r\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\r\nimport { connect, SetupFailed, type Connected } from './connect';\r\nimport { detect, type Project } from './detect';\r\nimport { DEFAULT_API, GUIDES, planFor, type Plan } from './recipes';\r\n\r\nexport interface InitOptions {\r\n dir?: string;\r\n url?: string;\r\n yes?: boolean;\r\n dryRun?: boolean;\r\n /** Install the SDK from these .tgz files instead of npm (testing unreleased versions). */\r\n tarballs?: string;\r\n}\r\n\r\nconst green = (s: string) => `\\u001b[32m${s}\\u001b[39m`;\r\nconst dim = (s: string) => `\\u001b[2m${s}\\u001b[22m`;\r\nconst bold = (s: string) => `\\u001b[1m${s}\\u001b[22m`;\r\nconst yellow = (s: string) => `\\u001b[33m${s}\\u001b[39m`;\r\nconst bar = dim('│');\r\n\r\nfunction say(line = ''): void {\r\n process.stdout.write(`${line}\\n`);\r\n}\r\n\r\n/** The env file with these keys set: existing lines kept, ours replaced or added. */\r\nexport function mergeEnv(existing: string, vars: Record<string, string>): string {\r\n const lines = existing ? existing.replace(/\\s+$/, '').split(/\\r?\\n/) : [];\r\n const seen = new Set<string>();\r\n const out = lines.map((line) => {\r\n const name = /^\\s*(?:export\\s+)?([A-Z0-9_]+)\\s*=/.exec(line)?.[1];\r\n if (name && name in vars) {\r\n seen.add(name);\r\n return `${name}=${vars[name]}`;\r\n }\r\n return line;\r\n });\r\n const added = Object.entries(vars).filter(([k]) => !seen.has(k));\r\n if (added.length) {\r\n if (out.length) out.push('');\r\n out.push('# Zharp (npm init zharp@latest)');\r\n for (const [k, v] of added) out.push(`${k}=${v}`);\r\n }\r\n return `${out.join('\\n')}\\n`;\r\n}\r\n\r\n/** Whether git would ignore `file` by the project's .gitignore (the common patterns). */\r\nexport function ignoredByGit(gitignore: string, file: string): boolean {\r\n return gitignore.split(/\\r?\\n/).map((l) => l.trim()).some((l) =>\r\n l === file || l === `/${file}` || l === '.env*' || l === '.env*.local' && file.endsWith('.local') || l === '*.local' && file.endsWith('.local') || l === '.env.*' && file !== '.env');\r\n}\r\n\r\nfunction installCommand(project: Project, packages: string[], dev: boolean, tarballs?: string): [string, string[]] {\r\n const specs = tarballs ? packages.map((p) => join(tarballs, `${p.replace('@', '').replace('/', '-')}.tgz`)) : packages;\r\n switch (project.packageManager) {\r\n case 'pnpm':\r\n return ['pnpm', ['add', ...(dev ? ['-D'] : []), ...specs]];\r\n case 'yarn':\r\n return ['yarn', ['add', ...(dev ? ['-D'] : []), ...specs]];\r\n case 'bun':\r\n return ['bun', ['add', ...(dev ? ['-d'] : []), ...specs]];\r\n default:\r\n return ['npm', ['install', ...(dev ? ['--save-dev'] : []), ...specs]];\r\n }\r\n}\r\n\r\n/** Whether `command` is on the PATH (composer, go, uv…). */\r\nfunction installed(command: string): boolean {\r\n const found = process.platform === 'win32'\r\n ? spawnSync('where', [command], { stdio: 'ignore' })\r\n : spawnSync('sh', ['-c', 'command -v \"$0\"', command], { stdio: 'ignore' });\r\n return found.status === 0;\r\n}\r\n\r\nasync function ask(question: string): Promise<string> {\r\n const rl = createInterface({ input: process.stdin, output: process.stdout });\r\n try {\r\n return (await rl.question(question)).trim().toLowerCase();\r\n } finally {\r\n rl.close();\r\n }\r\n}\r\n\r\n/** A test error, straight to OTLP with the app's key, so the person sees one arrive. */\r\nasync function sendTestError(api: string, c: Connected): Promise<boolean> {\r\n const now = `${Date.now()}000000`;\r\n const attr = (key: string, value: string) => ({ key, value: { stringValue: value } });\r\n const body = {\r\n resourceLogs: [{\r\n resource: { attributes: [attr('service.name', c.application.serviceName), attr('telemetry.sdk.name', 'zharp-cli')] },\r\n scopeLogs: [{\r\n logRecords: [{\r\n timeUnixNano: now,\r\n severityNumber: 17,\r\n severityText: 'ERROR',\r\n body: { stringValue: 'ZharpSetupTest: Zharp is connected — this is the test error npm init zharp@latest sent' },\r\n attributes: [\r\n attr('exception.type', 'ZharpSetupTest'),\r\n attr('exception.message', 'Zharp is connected — this is the test error npm init zharp@latest sent'),\r\n attr('exception.stacktrace', 'ZharpSetupTest: Zharp is connected — this is the test error npm init zharp@latest sent\\n at zharp init'),\r\n attr('zharp.handled', 'true'),\r\n ],\r\n }],\r\n }],\r\n }],\r\n };\r\n try {\r\n const res = await fetch(`${api.replace(/\\/+$/, '')}/api/v1/otlp/v1/logs`, {\r\n method: 'POST',\r\n headers: { 'content-type': 'application/json', authorization: `Bearer ${c.application.ingestKey}` },\r\n body: JSON.stringify(body),\r\n });\r\n return res.ok;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\nfunction showPlan(plan: Plan, c: Connected): void {\r\n say(`${green('◆')} ${bold('These changes will be made:')}`);\r\n const deps = [...plan.install, ...plan.devInstall];\r\n if (deps.length) say(`${bar} ${green('+')} install ${deps.join(' ')}`);\r\n for (const cmd of plan.commands ?? []) say(`${bar} ${green('+')} ${cmd.label}`);\r\n for (const ch of plan.changes) say(`${bar} ${ch.kind === 'create' ? green('+') : yellow('~')} ${bold(ch.path)} ${dim(ch.kind === 'create' ? `(new) ${ch.note}` : ch.note)}`);\r\n if (plan.env.file) say(`${bar} ${green('+')} ${bold(plan.env.file)} ${dim(Object.keys(plan.env.vars).join(', '))}`);\r\n for (const m of plan.manual) say(`${bar} ${yellow('!')} ${m.path}: ${dim(`left as it is — ${m.why}`)}`);\r\n void c;\r\n}\r\n\r\nexport async function runInit(options: InitOptions): Promise<number> {\r\n const dir = resolve(options.dir ?? process.cwd());\r\n const api = (options.url ?? process.env.ZHARP_URL ?? DEFAULT_API).replace(/\\/+$/, '');\r\n const project = detect(dir);\r\n\r\n say();\r\n say(`${green('◆')} ${bold('Zharp setup')}`);\r\n say(`${bar} Found ${bold(project.label)} in ${dim(dir)}`);\r\n say(bar);\r\n\r\n let connected: Connected;\r\n try {\r\n connected = await connect(api, project, {\r\n showCode(code, url) {\r\n say(`${bar} Open ${url} and check this code:`);\r\n say(bar);\r\n say(`${bar} ${bold(code)}`);\r\n say(bar);\r\n say(`${bar} ${dim('Waiting for you to approve it in the browser…')}`);\r\n },\r\n });\r\n } catch (error) {\r\n say(`${yellow('■')} ${error instanceof SetupFailed ? error.message : String(error)}`);\r\n return 1;\r\n }\r\n say(`${green('◇')} Connected to ${bold(`${connected.workspace.name} / ${connected.application.name}`)}`);\r\n say(bar);\r\n\r\n const plan = planFor(project, connected, api);\r\n if (!plan) {\r\n say(`${green('◆')} ${bold(`${project.label}: add the SDK with these keys`)}`);\r\n say(`${bar} ZHARP_KEY=${connected.application.ingestKey}`);\r\n say(`${bar} ${dim('Upload key (source maps): ZHARP_AUTH_TOKEN=')}${connected.uploadKey}`);\r\n const guide = GUIDES[project.framework];\r\n say(`${bar} ${dim(`How: ${guide ?? 'https://zharp.io/docs'}`)}`);\r\n return 0;\r\n }\r\n\r\n showPlan(plan, connected);\r\n say(bar);\r\n if (options.dryRun) {\r\n say(`${green('◇')} Dry run: nothing was changed.`);\r\n return 0;\r\n }\r\n if (!options.yes) {\r\n for (;;) {\r\n const answer = await ask(`${green('◆')} Apply? ${dim('[Y]es / [n]o / show the [d]iff')} `);\r\n if (answer === 'd' || answer === 'diff') {\r\n for (const ch of plan.changes) {\r\n say(`\\n${bold(`── ${ch.path} ${ch.kind === 'create' ? '(new)' : '(edited)'}`)}`);\r\n say(ch.content);\r\n }\r\n continue;\r\n }\r\n if (answer === 'n' || answer === 'no') {\r\n say(`${yellow('■')} Nothing was changed. The app is set up in Zharp: ${connected.appUrl}`);\r\n return 0;\r\n }\r\n break;\r\n }\r\n }\r\n\r\n // The files first: a failed install still leaves the setup in place, to finish by hand.\r\n for (const ch of plan.changes) {\r\n const path = join(dir, ch.path);\r\n mkdirSync(dirname(path), { recursive: true });\r\n writeFileSync(path, ch.content);\r\n }\r\n if (plan.env.file) {\r\n const envPath = join(dir, plan.env.file);\r\n writeFileSync(envPath, mergeEnv(existsSync(envPath) ? readFileSync(envPath, 'utf8') : '', plan.env.vars));\r\n const gitignorePath = join(dir, '.gitignore');\r\n if (existsSync(join(dir, '.git')) || existsSync(gitignorePath)) {\r\n const gitignore = existsSync(gitignorePath) ? readFileSync(gitignorePath, 'utf8') : '';\r\n if (!ignoredByGit(gitignore, plan.env.file)) writeFileSync(gitignorePath, `${gitignore.replace(/\\s*$/, '\\n')}${plan.env.file}\\n`);\r\n }\r\n }\r\n say(`${green('◇')} Files written`);\r\n\r\n /** Runs one command in the project: 'ok', 'failed', or 'missing' when the tool isn't installed. */\r\n const run = (command: string, args: string[]): 'ok' | 'failed' | 'missing' => {\r\n // A tool that isn't installed is said once, in our words, not in the shell's.\r\n if (!isAbsolute(command) && !installed(command)) return 'missing';\r\n say(`${bar} ${dim(`${command} ${args.join(' ')}`)}`);\r\n // Windows runs npm/pnpm/composer through .cmd shims, which need a shell: one command line, quoted.\r\n const result = process.platform === 'win32'\r\n ? spawnSync([command, ...args].map((a) => (/[\\s\"&|<>^]/.test(a) ? `\"${a.replace(/\"/g, '\\\\\"')}\"` : a)).join(' '), { cwd: dir, stdio: 'inherit', shell: true })\r\n : spawnSync(command, args, { cwd: dir, stdio: 'inherit' });\r\n if ((result.error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT' || (process.platform === 'win32' && result.status === 9009) || (process.platform !== 'win32' && result.status === 127)) return 'missing';\r\n return result.status === 0 ? 'ok' : 'failed';\r\n };\r\n\r\n for (const [packages, dev] of [[plan.install, false], [plan.devInstall, true]] as const) {\r\n if (!packages.length) continue;\r\n const [command, args] = installCommand(project, [...packages], dev, options.tarballs);\r\n if (run(command, args) !== 'ok') {\r\n say(`${yellow('■')} The install failed. Run it yourself: ${command} ${args.join(' ')}`);\r\n return 1;\r\n }\r\n }\r\n const leftToDo: string[] = [];\r\n for (const cmd of plan.commands ?? []) {\r\n const [command, ...args] = cmd.argv;\r\n const result = run(command, args);\r\n if (result === 'missing') leftToDo.push(`${cmd.argv.join(' ')} ${dim(`(${command} isn't installed here)`)}`);\r\n else if (result === 'failed') leftToDo.push(cmd.argv.join(' '));\r\n }\r\n say(`${green('◇')} ${leftToDo.length ? 'Set up — finish with:' : 'Packages installed'}`);\r\n for (const line of leftToDo) say(`${bar} ${line}`);\r\n\r\n for (const m of plan.manual) {\r\n say(bar);\r\n say(`${yellow('!')} ${bold(m.path)} — ${m.why}:`);\r\n for (const line of m.snippet.split('\\n')) say(`${bar} ${line}`);\r\n }\r\n for (const note of plan.notes) say(`${bar} ${yellow('!')} ${note}`);\r\n\r\n const sent = await sendTestError(api, connected);\r\n say(bar);\r\n say(sent\r\n ? `${green('◇')} Done. Sent a test error — see it at ${connected.appUrl}`\r\n : `${green('◇')} Done. Open ${connected.appUrl} — errors show up as your app sends them.`);\r\n return 0;\r\n}\r\n","/**\r\n * The handshake with Zharp: open a setup session, show its code, open the page in the browser,\r\n * and wait until the person approves it there — then collect the app's key and an upload key.\r\n */\r\nimport { spawn } from 'node:child_process';\r\nimport { platform as osPlatform, release } from 'node:os';\r\nimport type { Project } from './detect';\r\nimport { VERSION } from '../version';\r\n\r\nexport interface Connected {\r\n application: { id: number; name: string; serviceName: string; ingestKey: string };\r\n workspace: { id: number; name: string };\r\n uploadKey: string;\r\n appUrl: string;\r\n}\r\n\r\nexport interface ConnectHooks {\r\n /** Show the code and the link (the browser is opened too, where there is one). */\r\n showCode(code: string, url: string): void;\r\n /** While waiting: called each poll. */\r\n waiting?(): void;\r\n /** For tests: no browser, a fake clock. */\r\n openBrowser?: (url: string) => void;\r\n sleep?: (ms: number) => Promise<void>;\r\n fetch?: typeof fetch;\r\n}\r\n\r\nconst OS_NAMES: Record<string, string> = { win32: 'Windows', darwin: 'macOS', linux: 'Linux' };\r\n\r\nexport function openBrowser(url: string): void {\r\n // CI, SSH, or asked not to: the link is printed, nothing is opened.\r\n if (process.env.ZHARP_NO_BROWSER || process.env.CI || (process.platform === 'linux' && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY)) return;\r\n try {\r\n const command = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open';\r\n const args = process.platform === 'win32' ? ['/c', 'start', '\"\"', url.replace(/&/g, '^&')] : [url];\r\n spawn(command, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref();\r\n } catch {\r\n // No browser here (SSH, CI): the link is printed.\r\n }\r\n}\r\n\r\nexport class SetupFailed extends Error {}\r\n\r\nexport async function connect(api: string, project: Project, hooks: ConnectHooks): Promise<Connected> {\r\n const http = hooks.fetch ?? fetch;\r\n const sleep = hooks.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));\r\n const base = `${api.replace(/\\/+$/, '')}/api/v1/cli-setup`;\r\n\r\n const opened = await http(`${base}/sessions`, {\r\n method: 'POST',\r\n headers: { 'content-type': 'application/json', 'user-agent': `zharp-cli/${VERSION}` },\r\n body: JSON.stringify({ name: project.name, framework: project.label, platform: project.platform, os: OS_NAMES[osPlatform()] ?? `${osPlatform()} ${release()}`, cliVersion: VERSION }),\r\n }).catch((error) => {\r\n throw new SetupFailed(`Could not reach Zharp at ${api} (${error?.cause?.code ?? error?.message ?? error}).`);\r\n });\r\n if (!opened.ok) throw new SetupFailed(`Zharp refused to start a setup (${opened.status}).`);\r\n const session = (await opened.json()).data as { userCode: string; deviceToken: string; verificationUrl: string; expiresIn: number; interval: number };\r\n\r\n hooks.showCode(session.userCode, session.verificationUrl);\r\n (hooks.openBrowser ?? openBrowser)(session.verificationUrl);\r\n\r\n const until = Date.now() + session.expiresIn * 1000;\r\n while (Date.now() < until) {\r\n await sleep(Math.max(1, session.interval) * 1000);\r\n hooks.waiting?.();\r\n const res = await http(`${base}/collect`, {\r\n method: 'POST',\r\n headers: { 'content-type': 'application/json', 'user-agent': `zharp-cli/${VERSION}` },\r\n body: JSON.stringify({ deviceToken: session.deviceToken }),\r\n }).catch(() => null);\r\n if (!res) continue; // a blip: try again\r\n const body = await res.json().catch(() => ({}));\r\n if (res.status === 200 && body?.data?.status === 'approved') return body.data as Connected;\r\n if (res.status === 200) continue;\r\n throw new SetupFailed(body?.message ?? `The setup stopped (${res.status}).`);\r\n }\r\n throw new SetupFailed('The code expired before it was approved. Run it again.');\r\n}\r\n","/**\r\n * What kind of project this is, from its own files: package.json's dependencies, and the files\r\n * other ecosystems keep (requirements.txt, composer.json, go.mod). Only what the setup can act on\r\n * or point the person to.\r\n */\r\nimport { existsSync, readFileSync } from 'node:fs';\r\nimport { basename, join } from 'node:path';\r\n\r\nexport type Framework = 'expo' | 'react-native' | 'nextjs' | 'vite-react' | 'nestjs' | 'express' | 'node' | 'django' | 'fastapi' | 'flask' | 'laravel' | 'go' | 'unknown';\r\n\r\nexport interface Project {\r\n dir: string;\r\n name: string;\r\n framework: Framework;\r\n /** \"Next.js 16\", \"React (Vite)\", \"NestJS 11\"… for the terminal and the page. */\r\n label: string;\r\n /** The Zharp platform the app is created with. */\r\n platform: 'browser' | 'node' | 'python' | 'php' | 'go' | 'react-native' | 'otel';\r\n packageManager: 'pnpm' | 'yarn' | 'bun' | 'npm';\r\n typescript: boolean;\r\n /** Next.js: the app directory (\"app\" or \"src/app\"), when it uses the app router. */\r\n appDir?: string;\r\n packageJson?: Record<string, any>;\r\n}\r\n\r\nconst read = (path: string): string | null => {\r\n try {\r\n return readFileSync(path, 'utf8');\r\n } catch {\r\n return null;\r\n }\r\n};\r\n\r\nfunction majorOf(range: string | undefined): string {\r\n const m = /(\\d+)/.exec(range ?? '');\r\n return m ? ` ${m[1]}` : '';\r\n}\r\n\r\nexport function packageManagerOf(dir: string): Project['packageManager'] {\r\n if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm';\r\n if (existsSync(join(dir, 'yarn.lock'))) return 'yarn';\r\n if (existsSync(join(dir, 'bun.lockb')) || existsSync(join(dir, 'bun.lock'))) return 'bun';\r\n return 'npm';\r\n}\r\n\r\nexport function detect(dir: string): Project {\r\n const pkgText = read(join(dir, 'package.json'));\r\n const pkg = pkgText ? (() => { try { return JSON.parse(pkgText); } catch { return null; } })() : null;\r\n const deps: Record<string, string> = { ...(pkg?.dependencies ?? {}), ...(pkg?.devDependencies ?? {}) };\r\n const name = (typeof pkg?.name === 'string' && pkg.name.replace(/^@[^/]+\\//, '')) || basename(dir);\r\n const base = { dir, name, packageManager: packageManagerOf(dir), typescript: !!deps.typescript || existsSync(join(dir, 'tsconfig.json')), packageJson: pkg ?? undefined };\r\n\r\n // Before React and Node: an app with react-native depends on react too.\r\n if (deps.expo) return { ...base, framework: 'expo', label: `Expo${majorOf(deps.expo).replace(/^ (\\d+)$/, ' SDK $1')}`, platform: 'react-native' };\r\n if (deps['react-native']) return { ...base, framework: 'react-native', label: `React Native${/(\\d+\\.\\d+)/.exec(deps['react-native'])?.[1] ? ` ${/(\\d+\\.\\d+)/.exec(deps['react-native'])![1]}` : ''}`, platform: 'react-native' };\r\n if (deps.next) {\r\n const appDir = existsSync(join(dir, 'src', 'app')) ? 'src/app' : existsSync(join(dir, 'app')) ? 'app' : undefined;\r\n return { ...base, framework: 'nextjs', label: `Next.js${majorOf(deps.next)}`, platform: 'browser', appDir };\r\n }\r\n if (deps['@nestjs/core']) return { ...base, framework: 'nestjs', label: `NestJS${majorOf(deps['@nestjs/core'])}`, platform: 'node' };\r\n if (deps.vite && deps.react) return { ...base, framework: 'vite-react', label: 'React (Vite)', platform: 'browser' };\r\n if (deps.express) return { ...base, framework: 'express', label: `Express${majorOf(deps.express)}`, platform: 'node' };\r\n\r\n const py = [read(join(dir, 'requirements.txt')), read(join(dir, 'pyproject.toml')), read(join(dir, 'Pipfile'))].filter(Boolean).join('\\n').toLowerCase();\r\n if (py) {\r\n const pyName = basename(dir);\r\n if (/\\bdjango\\b/.test(py)) return { ...base, name: pyName, framework: 'django', label: 'Django', platform: 'python' };\r\n if (/\\bfastapi\\b/.test(py)) return { ...base, name: pyName, framework: 'fastapi', label: 'FastAPI', platform: 'python' };\r\n if (/\\bflask\\b/.test(py)) return { ...base, name: pyName, framework: 'flask', label: 'Flask', platform: 'python' };\r\n }\r\n const composer = read(join(dir, 'composer.json'));\r\n if (composer && /laravel\\/framework/.test(composer)) return { ...base, name: basename(dir), framework: 'laravel', label: 'Laravel', platform: 'php' };\r\n const goMod = read(join(dir, 'go.mod'));\r\n if (goMod !== null) {\r\n const router = /github\\.com\\/gin-gonic\\/gin/.test(goMod) ? ' (Gin)' : /github\\.com\\/labstack\\/echo/.test(goMod) ? ' (Echo)' : '';\r\n const moduleName = /^module\\s+(\\S+)/m.exec(goMod)?.[1]?.split('/').pop();\r\n return { ...base, name: moduleName || basename(dir), framework: 'go', label: `Go${router}`, platform: 'go' };\r\n }\r\n if (pkg) return { ...base, framework: 'node', label: 'Node.js', platform: 'node' };\r\n return { ...base, framework: 'unknown', label: 'an unknown project', platform: 'otel' };\r\n}\r\n","/**\r\n * What `zharp init` changes in a project, per framework — worked out first, as a plan the person\r\n * sees before anything is written. Only standard files are touched, each in the one way that is\r\n * safe: a new file is created only where none exists; an existing file is edited only where its\r\n * shape is the common one (a plain `export default`, a `plugins: [` array, a `createRoot(…)` call).\r\n * Anything else becomes a snippet to paste, never a guess.\r\n */\r\nimport { existsSync, readFileSync } from 'node:fs';\r\nimport { join } from 'node:path';\r\nimport type { Project } from './detect';\r\nimport type { Connected } from './connect';\r\nimport { morePlanFor, type Command } from './recipes-more';\r\nimport { reactNativePlanFor } from './recipes-rn';\r\n\r\nexport interface Change {\r\n path: string;\r\n kind: 'create' | 'edit';\r\n content: string;\r\n /** What it is, in a few words: \"wrapped with withZharp\". */\r\n note: string;\r\n}\r\n\r\nexport interface Manual {\r\n path: string;\r\n why: string;\r\n snippet: string;\r\n}\r\n\r\nexport interface Plan {\r\n install: string[];\r\n devInstall: string[];\r\n changes: Change[];\r\n /** Keys go in this file, which is checked to be ignored by git. */\r\n env: { file: string; vars: Record<string, string> };\r\n manual: Manual[];\r\n /** Said at the end: what to set up elsewhere (CI). */\r\n notes: string[];\r\n /** Installs outside npm: pip, composer, go get. Run after the files are written. */\r\n commands?: Command[];\r\n}\r\n\r\nexport const DEFAULT_API = 'https://api.zharp.io';\r\n\r\nconst read = (dir: string, path: string): string | null => {\r\n try {\r\n // Worked on with \\n line endings; a file that had \\r\\n gets them back (see planFor).\r\n return readFileSync(join(dir, path), 'utf8').replace(/\\r\\n/g, '\\n');\r\n } catch {\r\n return null;\r\n }\r\n};\r\nconst first = (dir: string, paths: string[]) => paths.find((p) => existsSync(join(dir, p))) ?? null;\r\nconst mentionsZharp = (text: string | null) => !!text && /@zharp\\//.test(text);\r\n\r\n/** Lines added to a file follow its style: no semicolons where its imports have none. */\r\nfunction styled(text: string, line: string): string {\r\n const imports = [...text.matchAll(/^import .*$/gm)].map((m) => m[0].trimEnd());\r\n const bare = imports.length > 0 && imports.every((l) => !l.endsWith(';'));\r\n // Double-quoted imports: the line's strings in double quotes too.\r\n const double = imports.filter((l) => /from \"/.test(l)).length > imports.filter((l) => /from '/.test(l)).length;\r\n const quoted = double ? line.replace(/'([^'\"]*)'/g, '\"$1\"') : line;\r\n return bare ? quoted.replace(/;$/, '') : quoted;\r\n}\r\n\r\n/** The OTLP endpoint, said only when it isn't Zharp's own. */\r\nfunction endpointOf(api: string): string | null {\r\n const clean = api.replace(/\\/+$/, '');\r\n return clean === DEFAULT_API ? null : `${clean}/api/v1/otlp`;\r\n}\r\n\r\n// ── Next.js ──────────────────────────────────────────────────────────────────────\r\n\r\n/** `export default X;` → `export default withZharp(X, { app: 42 });`, the import added. */\r\nexport function wrapNextConfig(text: string, appId: number, esm: boolean): string | null {\r\n if (/withZharp/.test(text)) return null;\r\n const exportDefault = /export\\s+default\\s+([\\s\\S]+?);?\\s*$/.exec(text);\r\n if (esm && exportDefault) {\r\n const value = exportDefault[1].trim().replace(/;$/, '');\r\n const head = text.slice(0, exportDefault.index);\r\n return `import { withZharp } from '@zharp/nextjs';\\n${head}export default withZharp(${value}, { app: ${appId} });\\n`;\r\n }\r\n const moduleExports = /module\\.exports\\s*=\\s*([\\s\\S]+?);?\\s*$/.exec(text);\r\n if (!esm && moduleExports) {\r\n const value = moduleExports[1].trim().replace(/;$/, '');\r\n const head = text.slice(0, moduleExports.index);\r\n return `const { withZharp } = require('@zharp/nextjs');\\n${head}module.exports = withZharp(${value}, { app: ${appId} });\\n`;\r\n }\r\n return null;\r\n}\r\n\r\n/** The client component rendered first in <body>, with its import, in the root layout. */\r\nexport function addToLayout(text: string, importPath: string): string | null {\r\n if (/ZharpClient/.test(text)) return null;\r\n const body = /<body\\b[^>]*>/.exec(text);\r\n if (!body) return null;\r\n const at = body.index + body[0].length;\r\n // On its own line, indented one step in from <body>; what followed <body> keeps its own line.\r\n const bodyIndent = /[ \\t]*$/.exec(text.slice(0, body.index))![0];\r\n const inner = `${bodyIndent} `;\r\n const rest = text.slice(at);\r\n const after = /^\\s*\\n/.test(rest) ? rest : `\\n${inner}${rest.replace(/^[ \\t]+/, '')}`;\r\n const withComponent = `${text.slice(0, at)}\\n${inner}<ZharpClient />${after}`;\r\n const imports = [...withComponent.matchAll(/^import .*$/gm)];\r\n const line = styled(text, `import { ZharpClient } from '${importPath}';`);\r\n if (!imports.length) return `${line}\\n${withComponent}`;\r\n const last = imports[imports.length - 1];\r\n const end = last.index! + last[0].length;\r\n return `${withComponent.slice(0, end)}\\n${line}${withComponent.slice(end)}`;\r\n}\r\n\r\nfunction nextjs(project: Project, c: Connected, api: string): Plan {\r\n const dir = project.dir;\r\n const ts = project.typescript;\r\n const plan: Plan = { install: ['@zharp/browser', '@zharp/node'], devInstall: ['@zharp/nextjs'], changes: [], manual: [], notes: [], env: { file: '.env.local', vars: {} } };\r\n const endpoint = endpointOf(api);\r\n\r\n // Server: instrumentation.ts, next to app/ (in src/ when the app lives there).\r\n const instrumentationPath = `${project.appDir?.startsWith('src/') ? 'src/' : ''}instrumentation.${ts ? 'ts' : 'js'}`;\r\n const instrumentation = [\r\n 'export async function register() {',\r\n \" if (process.env.NEXT_RUNTIME === 'nodejs') {\",\r\n \" const { Zharp } = await import('@zharp/node');\",\r\n ` Zharp.init({ service: '${c.application.serviceName}' });`,\r\n ' }',\r\n '}',\r\n '',\r\n '// Errors Next.js answers with an error page: reported with their route.',\r\n `export async function onRequestError(...args${ts ? \": Parameters<typeof import('@zharp/node').Zharp.onRequestError>\" : ''}) {`,\r\n \" if (process.env.NEXT_RUNTIME === 'nodejs') {\",\r\n \" const { Zharp } = await import('@zharp/node');\",\r\n ' Zharp.onRequestError(...args);',\r\n ' }',\r\n '}',\r\n '',\r\n ].join('\\n');\r\n const existingInstrumentation = first(dir, ['instrumentation.ts', 'instrumentation.js', 'src/instrumentation.ts', 'src/instrumentation.js']);\r\n if (!existingInstrumentation) plan.changes.push({ path: instrumentationPath, kind: 'create', content: instrumentation, note: 'starts Zharp on the server' });\r\n else if (!mentionsZharp(read(dir, existingInstrumentation))) plan.manual.push({ path: existingInstrumentation, why: 'it already exists — add Zharp to it', snippet: instrumentation });\r\n\r\n // Build: next.config wrapped with withZharp (source maps uploaded, @zharp/node kept external).\r\n const configPath = first(dir, ['next.config.ts', 'next.config.mjs', 'next.config.js', 'next.config.cjs']);\r\n if (!configPath) {\r\n plan.changes.push({ path: ts ? 'next.config.ts' : 'next.config.mjs', kind: 'create', content: `import { withZharp } from '@zharp/nextjs';\\n\\nexport default withZharp({}, { app: ${c.application.id} });\\n`, note: 'source maps uploaded on build' });\r\n } else {\r\n const text = read(dir, configPath) ?? '';\r\n const esm = /\\.(ts|mjs)$/.test(configPath) || /^\\s*(import|export)\\s/m.test(text);\r\n const wrapped = mentionsZharp(text) ? null : wrapNextConfig(text, c.application.id, esm);\r\n if (wrapped) plan.changes.push({ path: configPath, kind: 'edit', content: wrapped, note: 'wrapped with withZharp' });\r\n else if (!mentionsZharp(text)) plan.manual.push({ path: configPath, why: \"its export isn't a plain value — wrap it yourself\", snippet: `import { withZharp } from '@zharp/nextjs';\\n\\nexport default withZharp(nextConfig, { app: ${c.application.id} });` });\r\n }\r\n\r\n // Browser: a client component started from the root layout (app router).\r\n if (project.appDir) {\r\n const ext = ts ? 'tsx' : 'jsx';\r\n const clientPath = `${project.appDir}/zharp-client.${ext}`;\r\n const client = [\r\n \"'use client';\",\r\n \"import { Zharp } from '@zharp/browser';\",\r\n '',\r\n \"if (typeof window !== 'undefined' && !Zharp.isActive) {\",\r\n ` Zharp.init({ key: process.env.NEXT_PUBLIC_ZHARP_KEY${ts ? '!' : ''}${endpoint ? ', endpoint: process.env.NEXT_PUBLIC_ZHARP_ENDPOINT' : ''}, service: '${c.application.serviceName}' });`,\r\n '}',\r\n '',\r\n '/** Starts Zharp in the browser; rendered once, in the root layout. */',\r\n 'export function ZharpClient() {',\r\n ' return null;',\r\n '}',\r\n '',\r\n ].join('\\n');\r\n if (!existsSync(join(dir, clientPath))) plan.changes.push({ path: clientPath, kind: 'create', content: client, note: `starts Zharp in the browser` });\r\n const layoutPath = first(dir, [`${project.appDir}/layout.tsx`, `${project.appDir}/layout.jsx`, `${project.appDir}/layout.js`]);\r\n const layout = layoutPath ? read(dir, layoutPath) : null;\r\n const edited = layout ? addToLayout(layout, './zharp-client') : null;\r\n if (layoutPath && edited) plan.changes.push({ path: layoutPath, kind: 'edit', content: edited, note: 'renders <ZharpClient />' });\r\n else if (layoutPath && !/ZharpClient/.test(layout ?? '')) plan.manual.push({ path: layoutPath, why: 'add the component inside <body>', snippet: \"import { ZharpClient } from './zharp-client';\\n…\\n<body>\\n <ZharpClient />\" });\r\n } else {\r\n plan.manual.push({ path: 'pages/_app', why: 'pages router: start Zharp in your _app', snippet: \"import { Zharp } from '@zharp/browser';\\n\\nif (typeof window !== 'undefined') Zharp.init({ key: process.env.NEXT_PUBLIC_ZHARP_KEY });\" });\r\n }\r\n\r\n plan.env.vars = {\r\n NEXT_PUBLIC_ZHARP_KEY: c.application.ingestKey,\r\n ZHARP_KEY: c.application.ingestKey,\r\n ZHARP_AUTH_TOKEN: c.uploadKey,\r\n ...(endpoint ? { NEXT_PUBLIC_ZHARP_ENDPOINT: endpoint, ZHARP_ENDPOINT: endpoint, ZHARP_URL: api.replace(/\\/+$/, '') } : {}),\r\n };\r\n plan.notes.push('Add ZHARP_AUTH_TOKEN (and the keys) to your CI and hosting, so production builds upload their source maps.');\r\n return plan;\r\n}\r\n\r\n// ── React with Vite ──────────────────────────────────────────────────────────────\r\n\r\n/** `plugins: [react()]` → `plugins: [react(), zharp({ app: 42 })]`, the import added. */\r\nexport function addVitePlugin(text: string, appId: number): string | null {\r\n if (/@zharp\\/vite-plugin/.test(text)) return null;\r\n const plugins = /plugins\\s*:\\s*\\[/.exec(text);\r\n if (!plugins) return null;\r\n // The array's closing bracket: the first `]` at depth zero after the opening one.\r\n let depth = 0;\r\n let close = -1;\r\n for (let i = plugins.index + plugins[0].length; i < text.length; i++) {\r\n const ch = text[i];\r\n if (ch === '[' || ch === '(' || ch === '{') depth++;\r\n else if (ch === ']' || ch === ')' || ch === '}') {\r\n if (depth === 0 && ch === ']') {\r\n close = i;\r\n break;\r\n }\r\n depth--;\r\n }\r\n }\r\n if (close < 0) return null;\r\n const inside = text.slice(plugins.index + plugins[0].length, close).trimEnd();\r\n const sep = inside.length === 0 ? '' : inside.endsWith(',') ? ' ' : ', ';\r\n const withPlugin = `${text.slice(0, plugins.index + plugins[0].length)}${inside}${sep}zharp({ app: ${appId} })${text.slice(close)}`;\r\n const imports = [...withPlugin.matchAll(/^import .*$/gm)];\r\n const line = styled(text, \"import { zharp } from '@zharp/vite-plugin';\");\r\n if (!imports.length) return `${line}\\n${withPlugin}`;\r\n const last = imports[imports.length - 1];\r\n const end = last.index! + last[0].length;\r\n return `${withPlugin.slice(0, end)}\\n${line}${withPlugin.slice(end)}`;\r\n}\r\n\r\n/** Zharp started before React renders; createRoot given React 19's error handlers. */\r\nexport function addToViteMain(text: string, serviceName: string, withEndpoint: boolean): string | null {\r\n if (/@zharp\\/browser/.test(text)) return null;\r\n const call = /createRoot\\(([^()]*(?:\\([^()]*\\)[^()]*)*)\\)/.exec(text);\r\n let next = text;\r\n if (call && !call[1].includes(',')) {\r\n next = `${text.slice(0, call.index)}createRoot(${call[1]}, {\\n onUncaughtError: Zharp.reactErrorHandler(),\\n onCaughtError: Zharp.reactErrorHandler(),\\n})${text.slice(call.index + call[0].length)}`;\r\n }\r\n const imports = [...next.matchAll(/^import .*$/gm)];\r\n const start = styled(text, `Zharp.init({ key: import.meta.env.VITE_ZHARP_KEY${withEndpoint ? ', endpoint: import.meta.env.VITE_ZHARP_ENDPOINT' : ''}, service: '${serviceName}' });`);\r\n const init = `\\n${start}\\n`;\r\n const line = styled(text, \"import { Zharp } from '@zharp/browser';\");\r\n if (!imports.length) return `${line}\\n${init}\\n${next}`;\r\n const last = imports[imports.length - 1];\r\n const end = last.index! + last[0].length;\r\n return `${next.slice(0, end)}\\n${line}\\n${init}${next.slice(end).replace(/^\\n+/, '\\n')}`;\r\n}\r\n\r\nfunction viteReact(project: Project, c: Connected, api: string): Plan {\r\n const dir = project.dir;\r\n const endpoint = endpointOf(api);\r\n const plan: Plan = { install: ['@zharp/browser'], devInstall: ['@zharp/vite-plugin'], changes: [], manual: [], notes: [], env: { file: '.env.local', vars: {} } };\r\n const configPath = first(dir, ['vite.config.ts', 'vite.config.mts', 'vite.config.js', 'vite.config.mjs']);\r\n const config = configPath ? read(dir, configPath) : null;\r\n const editedConfig = config ? addVitePlugin(config, c.application.id) : null;\r\n if (configPath && editedConfig) plan.changes.push({ path: configPath, kind: 'edit', content: editedConfig, note: 'source maps uploaded on build' });\r\n else if (!mentionsZharp(config)) plan.manual.push({ path: configPath ?? 'vite.config.ts', why: 'add the plugin to plugins', snippet: `import { zharp } from '@zharp/vite-plugin';\\n…\\nplugins: [react(), zharp({ app: ${c.application.id} })]` });\r\n\r\n const mainPath = first(dir, ['src/main.tsx', 'src/main.jsx', 'src/main.ts', 'src/main.js', 'src/index.tsx', 'src/index.jsx']);\r\n const main = mainPath ? read(dir, mainPath) : null;\r\n const editedMain = main ? addToViteMain(main, c.application.serviceName, !!endpoint) : null;\r\n if (mainPath && editedMain) plan.changes.push({ path: mainPath, kind: 'edit', content: editedMain, note: 'starts Zharp; React errors with their component stack' });\r\n else if (!mentionsZharp(main)) plan.manual.push({ path: mainPath ?? 'src/main.tsx', why: 'start Zharp before React renders', snippet: \"import { Zharp } from '@zharp/browser';\\n\\nZharp.init({ key: import.meta.env.VITE_ZHARP_KEY });\\n\\ncreateRoot(el, { onUncaughtError: Zharp.reactErrorHandler(), onCaughtError: Zharp.reactErrorHandler() })\" });\r\n\r\n plan.env.vars = {\r\n VITE_ZHARP_KEY: c.application.ingestKey,\r\n ZHARP_AUTH_TOKEN: c.uploadKey,\r\n ...(endpoint ? { VITE_ZHARP_ENDPOINT: endpoint, ZHARP_URL: api.replace(/\\/+$/, '') } : {}),\r\n };\r\n plan.notes.push('Add ZHARP_AUTH_TOKEN and VITE_ZHARP_KEY to your CI, so production builds upload their source maps.');\r\n return plan;\r\n}\r\n\r\n// ── NestJS ───────────────────────────────────────────────────────────────────────\r\n\r\nfunction nestjs(project: Project, c: Connected, api: string): Plan {\r\n const dir = project.dir;\r\n const endpoint = endpointOf(api);\r\n const plan: Plan = { install: ['@zharp/node'], devInstall: [], changes: [], manual: [], notes: [], env: { file: '.env', vars: {} } };\r\n const ext = project.typescript ? 'ts' : 'js';\r\n const instrumentPath = `src/instrument.${ext}`;\r\n const instrument = [\r\n \"import { Zharp } from '@zharp/node';\",\r\n '',\r\n '// Before anything else: http, the database drivers and NestJS are instrumented as they load.',\r\n \"try { process.loadEnvFile?.('.env'); } catch { /* no .env: the environment has the keys */ }\",\r\n `Zharp.init({ service: '${c.application.serviceName}' });`,\r\n '',\r\n ].join('\\n');\r\n if (!existsSync(join(dir, instrumentPath))) plan.changes.push({ path: instrumentPath, kind: 'create', content: instrument, note: 'starts Zharp before the app loads' });\r\n\r\n const mainPath = first(dir, [`src/main.${ext}`]);\r\n const main = mainPath ? read(dir, mainPath) : null;\r\n const esm = project.packageJson?.type === 'module' || /from '\\.{1,2}\\/[^']+\\.js'/.test(main ?? '');\r\n if (esm) {\r\n // ES modules load every import before any code runs, so a first import is too late for\r\n // NestJS: Node preloads the file instead (--import), from the project's own start scripts.\r\n const pkgText = read(dir, 'package.json');\r\n const scripts = { ...(project.packageJson?.scripts ?? {}) } as Record<string, string>;\r\n const preload = '--import ./dist/instrument.js';\r\n let changed = false;\r\n for (const [name, command] of Object.entries(scripts)) {\r\n if (command.includes(preload)) continue;\r\n if (/^nest start\\b/.test(command) && !/--exec\\b/.test(command)) {\r\n scripts[name] = `${command} --exec \"node ${preload}\"`;\r\n changed = true;\r\n } else if (/^node (?:--[^\\s]+ )*dist\\/main(?:\\.js)?\\s*$/.test(command)) {\r\n scripts[name] = command.replace(/^node /, `node ${preload} `);\r\n changed = true;\r\n }\r\n }\r\n if (changed && pkgText) {\r\n // Only those lines change: the rest of package.json keeps its formatting.\r\n let text = pkgText;\r\n for (const [name, command] of Object.entries(scripts)) {\r\n const before = (project.packageJson?.scripts ?? {})[name];\r\n if (before === command) continue;\r\n const line = new RegExp(`(\"${name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\"\\\\s*:\\\\s*)${JSON.stringify(before).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}`);\r\n text = text.replace(line, (_, key: string) => `${key}${JSON.stringify(command)}`);\r\n }\r\n plan.changes.push({ path: 'package.json', kind: 'edit', content: text, note: 'start scripts preload Zharp (--import)' });\r\n }\r\n plan.manual.push({ path: 'your start command', why: 'ES modules: wherever the app is started outside these scripts (a Dockerfile, a process manager), preload Zharp', snippet: `node ${preload} dist/main.js` });\r\n } else if (mainPath && main && !main.includes('./instrument')) {\r\n plan.changes.push({ path: mainPath, kind: 'edit', content: `${styled(main, \"import './instrument';\")}\\n${main}`, note: 'loads it first' });\r\n } else if (!mainPath) {\r\n plan.manual.push({ path: 'src/main.ts', why: 'import it first in your entry file', snippet: \"import './instrument';\" });\r\n }\r\n plan.env.vars = { ZHARP_KEY: c.application.ingestKey, ...(endpoint ? { ZHARP_ENDPOINT: endpoint } : {}) };\r\n plan.notes.push('Set ZHARP_KEY where the app runs in production.');\r\n return plan;\r\n}\r\n\r\nexport function planFor(project: Project, c: Connected, api: string): Plan | null {\r\n const plan = basePlanFor(project, c, api);\r\n // Edited files keep their own line endings: \\r\\n where they had them (Windows, django-admin).\r\n for (const ch of plan?.changes ?? []) {\r\n if (ch.kind !== 'edit') continue;\r\n try {\r\n if (readFileSync(join(project.dir, ch.path), 'utf8').includes('\\r\\n')) ch.content = ch.content.replace(/\\r?\\n/g, '\\r\\n');\r\n } catch {\r\n // A file that went away: written as it is.\r\n }\r\n }\r\n return plan;\r\n}\r\n\r\nfunction basePlanFor(project: Project, c: Connected, api: string): Plan | null {\r\n switch (project.framework) {\r\n case 'nextjs':\r\n return nextjs(project, c, api);\r\n case 'vite-react':\r\n return viteReact(project, c, api);\r\n case 'nestjs':\r\n return nestjs(project, c, api);\r\n default:\r\n return reactNativePlanFor(project, c, api) ?? morePlanFor(project, c, api);\r\n }\r\n}\r\n\r\n/** Frameworks without a recipe yet: where to read how. */\r\nexport const GUIDES: Record<string, string> = {\r\n express: 'https://zharp.io/docs/sdks/node',\r\n node: 'https://zharp.io/docs/sdks/node',\r\n django: 'https://zharp.io/docs/sdks/python',\r\n fastapi: 'https://zharp.io/docs/sdks/python',\r\n flask: 'https://zharp.io/docs/sdks/python',\r\n laravel: 'https://zharp.io/docs/sdks/php',\r\n go: 'https://zharp.io/docs/sdks/go',\r\n};\r\n","/**\r\n * `zharp init` for the frameworks outside the JavaScript build tools: Express, Django, FastAPI,\r\n * Flask, Laravel and Go. The same rules as the others — standard files only, edited only where\r\n * their shape is the common one, everything else a snippet to paste.\r\n *\r\n * Python and Go get the app's key in code. It is the same key a web page ships: it can only send\r\n * data to this one app, so it is safe in a repository, and it avoids depending on how a project\r\n * loads its environment. Laravel reads .env itself, so its key goes there.\r\n */\r\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\r\nimport { join, relative } from 'node:path';\r\nimport type { Project } from './detect';\r\nimport type { Connected } from './connect';\r\nimport type { Plan } from './recipes';\r\n\r\nexport interface Command {\r\n /** What it does, for the plan: \"install zharp into .venv\". */\r\n label: string;\r\n argv: string[];\r\n}\r\n\r\nconst read = (dir: string, path: string): string | null => {\r\n try {\r\n // Worked on with \\n line endings; a file that had \\r\\n gets them back (see planFor).\r\n return readFileSync(join(dir, path), 'utf8').replace(/\\r\\n/g, '\\n');\r\n } catch {\r\n return null;\r\n }\r\n};\r\nconst first = (dir: string, paths: string[]) => paths.find((p) => existsSync(join(dir, p))) ?? null;\r\n\r\nfunction emptyPlan(envFile: string | null): Plan {\r\n return { install: [], devInstall: [], changes: [], manual: [], notes: [], env: { file: envFile ?? '', vars: {} }, commands: [] };\r\n}\r\n\r\nconst DEFAULT_API = 'https://api.zharp.io';\r\nconst otlpOf = (api: string) => {\r\n const clean = api.replace(/\\/+$/, '');\r\n return clean === DEFAULT_API ? null : `${clean}/api/v1/otlp`;\r\n};\r\n\r\n/** Files under `dir` (a few levels, skipping dependencies and virtualenvs) whose name ends with `suffix`. */\r\nexport function findFiles(dir: string, suffix: string, depth = 3): string[] {\r\n const skip = /^(node_modules|vendor|\\.git|\\.venv|venv|env|__pycache__|dist|build|target|\\.next|site-packages)$/;\r\n const out: string[] = [];\r\n const walk = (at: string, level: number) => {\r\n let entries;\r\n try {\r\n entries = readdirSync(at, { withFileTypes: true });\r\n } catch {\r\n return;\r\n }\r\n for (const e of entries) {\r\n if (e.isDirectory()) {\r\n if (level < depth && !skip.test(e.name) && !e.name.startsWith('.')) walk(join(at, e.name), level + 1);\r\n } else if (e.name.endsWith(suffix)) {\r\n out.push(relative(dir, join(at, e.name)).replace(/\\\\/g, '/'));\r\n }\r\n }\r\n };\r\n walk(dir, 0);\r\n return out.sort((a, b) => a.split('/').length - b.split('/').length || a.localeCompare(b));\r\n}\r\n\r\n// ── Express (and plain Node servers) ─────────────────────────────────────────────\r\n\r\n/** The file a Node app starts from: its start script's, else package.json's main, else the usual names. */\r\nexport function nodeEntry(project: Project): string | null {\r\n const scripts: Record<string, string> = project.packageJson?.scripts ?? {};\r\n for (const name of ['start', 'dev', 'serve']) {\r\n const m = /(?:^|\\s)(?:node|nodemon|tsx|ts-node)(?:\\s+--?[\\w-]+(?:[= ][^\\s]+)?)*\\s+([\\w./-]+\\.(?:c|m)?[jt]s)\\b/.exec(scripts[name] ?? '');\r\n if (m && existsSync(join(project.dir, m[1]))) return m[1].replace(/^\\.\\//, '');\r\n }\r\n const main = project.packageJson?.main;\r\n if (typeof main === 'string' && existsSync(join(project.dir, main))) return main.replace(/^\\.\\//, '');\r\n return first(project.dir, ['server.js', 'app.js', 'index.js', 'src/server.js', 'src/app.js', 'src/index.js', 'src/server.ts', 'src/app.ts', 'src/index.ts', 'server.ts', 'index.ts']);\r\n}\r\n\r\nfunction express(project: Project, c: Connected, api: string): Plan {\r\n const plan = emptyPlan('.env');\r\n plan.install = ['@zharp/node'];\r\n const entry = nodeEntry(project);\r\n const endpoint = otlpOf(api);\r\n plan.env.vars = { ZHARP_KEY: c.application.ingestKey, ...(endpoint ? { ZHARP_ENDPOINT: endpoint } : {}) };\r\n plan.notes.push('Set ZHARP_KEY where the app runs in production.');\r\n if (!entry) {\r\n plan.manual.push({ path: 'your entry file', why: 'start Zharp before anything else loads', snippet: \"require('./instrument'); // or: node --import ./instrument.mjs server.js\" });\r\n return plan;\r\n }\r\n const main = read(project.dir, entry) ?? '';\r\n const ts = entry.endsWith('.ts');\r\n const esm = project.packageJson?.type === 'module' || /\\.mjs$/.test(entry) || (!ts && /^\\s*import\\s/m.test(main));\r\n const dirOf = entry.includes('/') ? entry.slice(0, entry.lastIndexOf('/') + 1) : '';\r\n const instrumentName = ts ? 'instrument.ts' : esm ? (entry.endsWith('.mjs') ? 'instrument.mjs' : 'instrument.js') : (entry.endsWith('.cjs') ? 'instrument.cjs' : 'instrument.js');\r\n const instrumentPath = `${dirOf}${instrumentName}`;\r\n const body = [\r\n '// Before anything else: http, express and the database drivers are instrumented as they load.',\r\n \"try { process.loadEnvFile?.('.env'); } catch { /* no .env: the environment has the key */ }\",\r\n `Zharp.init({ service: '${c.application.serviceName}' });`,\r\n '',\r\n ];\r\n const content = esm || ts ? [\"import { Zharp } from '@zharp/node';\", '', ...body].join('\\n') : [\"const { Zharp } = require('@zharp/node');\", '', ...body].join('\\n');\r\n if (!existsSync(join(project.dir, instrumentPath))) plan.changes.push({ path: instrumentPath, kind: 'create', content, note: 'starts Zharp before the app loads' });\r\n if (main.includes('instrument')) return plan;\r\n\r\n if (esm && !ts) {\r\n // ES modules load every import before any code runs: Node preloads the file instead.\r\n const pkgText = read(project.dir, 'package.json');\r\n let text = pkgText ?? '';\r\n const preload = `--import ./${instrumentPath}`;\r\n let changed = false;\r\n for (const [name, command] of Object.entries((project.packageJson?.scripts ?? {}) as Record<string, string>)) {\r\n if (command.includes(preload)) continue;\r\n const m = /^(node|nodemon)\\s+/.exec(command);\r\n if (!m || !command.includes(entry.replace(/^\\.\\//, ''))) continue;\r\n const next = command.replace(/^(node|nodemon)\\s+/, `$1 ${preload} `);\r\n text = text.replace(`\"${name}\": ${JSON.stringify(command)}`, `\"${name}\": ${JSON.stringify(next)}`);\r\n changed = true;\r\n }\r\n if (changed) plan.changes.push({ path: 'package.json', kind: 'edit', content: text, note: 'start scripts preload Zharp (--import)' });\r\n plan.manual.push({ path: 'your start command', why: 'ES modules: wherever the app starts outside these scripts, preload Zharp', snippet: `node ${preload} ${entry}` });\r\n return plan;\r\n }\r\n const line = ts ? \"import './instrument';\" : \"require('./instrument');\";\r\n plan.changes.push({ path: entry, kind: 'edit', content: `${line}\\n${main}`, note: 'loads it first' });\r\n return plan;\r\n}\r\n\r\n// ── Python: Django, FastAPI, Flask ───────────────────────────────────────────────\r\n\r\n/** The block that starts Zharp, for Python. */\r\nfunction pythonInit(c: Connected, api: string): string {\r\n const endpoint = otlpOf(api);\r\n return [\r\n 'import zharp',\r\n '',\r\n \"# The app's key can only send data to this app, so it is safe in code.\",\r\n `zharp.init(key=\"${c.application.ingestKey}\", service=\"${c.application.serviceName}\"${endpoint ? `, endpoint=\"${api.replace(/\\/+$/, '')}/api/v1/otlp\"` : ''})`,\r\n ].join('\\n');\r\n}\r\n\r\n/** `block` placed after a module's docstring and its leading imports — before any other code. */\r\nexport function afterPythonImports(text: string, block: string): string | null {\r\n if (/^\\s*import zharp\\b/m.test(text)) return null;\r\n const lines = text.split('\\n');\r\n let i = 0;\r\n // A shebang, an encoding line, comments, blank lines.\r\n while (i < lines.length && (/^\\s*(#.*)?$/.test(lines[i]))) i++;\r\n // The module docstring.\r\n if (i < lines.length && /^\\s*[rubRUB]*(\"\"\"|''')/.test(lines[i])) {\r\n const quote = /(\"\"\"|''')/.exec(lines[i])![1];\r\n const rest = lines[i].slice(lines[i].indexOf(quote) + 3);\r\n if (!rest.includes(quote)) {\r\n i++;\r\n while (i < lines.length && !lines[i].includes(quote)) i++;\r\n }\r\n i++;\r\n }\r\n // Leading imports (and `from __future__`), blank lines and comments between them.\r\n let last = -1;\r\n for (let j = i; j < lines.length; j++) {\r\n if (/^(import |from \\S+ import )/.test(lines[j])) {\r\n last = j;\r\n // A parenthesised import runs on until its closing bracket.\r\n if (/\\($/.test(lines[j].trim())) while (j < lines.length && !lines[j].includes(')')) last = ++j;\r\n } else if (!/^\\s*(#.*)?$/.test(lines[j])) break;\r\n }\r\n const at = last >= 0 ? last + 1 : i;\r\n return [...lines.slice(0, at), '', block, '', ...lines.slice(at)].join('\\n').replace(/\\n{4,}/g, '\\n\\n\\n');\r\n}\r\n\r\nfunction pythonInstall(project: Project): { changes: Plan['changes']; commands: Command[]; manual: Plan['manual'] } {\r\n const dir = project.dir;\r\n const changes: Plan['changes'] = [];\r\n const commands: Command[] = [];\r\n const manual: Plan['manual'] = [];\r\n const requirements = read(dir, 'requirements.txt');\r\n const pyproject = read(dir, 'pyproject.toml') ?? '';\r\n if (requirements !== null) {\r\n if (!/^zharp\\b/im.test(requirements)) changes.push({ path: 'requirements.txt', kind: 'edit', content: `${requirements.replace(/\\s*$/, '\\n')}zharp\\n`, note: 'adds zharp' });\r\n }\r\n const venvPython = first(dir, ['.venv/Scripts/python.exe', '.venv/bin/python', 'venv/Scripts/python.exe', 'venv/bin/python']);\r\n if (existsSync(join(dir, 'uv.lock'))) commands.push({ label: 'uv add zharp', argv: ['uv', 'add', 'zharp'] });\r\n else if (/\\[tool\\.poetry\\]/.test(pyproject)) commands.push({ label: 'poetry add zharp', argv: ['poetry', 'add', 'zharp'] });\r\n else if (venvPython) commands.push({ label: `install zharp into ${venvPython.split('/')[0]}`, argv: [join(dir, venvPython), '-m', 'pip', 'install', 'zharp'] });\r\n else manual.push({ path: 'your Python environment', why: 'install the package where the app runs', snippet: 'pip install zharp' });\r\n return { changes, commands, manual };\r\n}\r\n\r\nfunction python(project: Project, c: Connected, api: string): Plan {\r\n const plan = emptyPlan(null);\r\n const installed = pythonInstall(project);\r\n plan.changes.push(...installed.changes);\r\n plan.commands = installed.commands;\r\n plan.manual.push(...installed.manual);\r\n const block = pythonInit(c, api);\r\n\r\n let targets: string[] = [];\r\n if (project.framework === 'django') {\r\n // runserver and the management commands start at manage.py; production at wsgi.py / asgi.py.\r\n targets = [first(project.dir, ['manage.py']), ...findFiles(project.dir, 'wsgi.py'), ...findFiles(project.dir, 'asgi.py')].filter((p): p is string => !!p);\r\n } else {\r\n const marker = project.framework === 'fastapi' ? /\\bFastAPI\\(/ : /\\bFlask\\(\\s*__name__/;\r\n const files = findFiles(project.dir, '.py').filter((f) => marker.test(read(project.dir, f) ?? ''));\r\n const preferred = files.find((f) => /(^|\\/)(main|app|server|wsgi|__init__)\\.py$/.test(f)) ?? files[0];\r\n if (preferred) targets = [preferred];\r\n }\r\n for (const path of targets) {\r\n const text = read(project.dir, path);\r\n const edited = text !== null ? afterPythonImports(text, block) : null;\r\n if (edited) plan.changes.push({ path, kind: 'edit', content: edited, note: 'starts Zharp' });\r\n }\r\n if (!targets.length) {\r\n const where = project.framework === 'django' ? 'manage.py, wsgi.py and asgi.py' : project.framework === 'fastapi' ? 'the file that creates FastAPI()' : 'the file that creates Flask(__name__)';\r\n plan.manual.push({ path: where, why: 'start Zharp at the top, after the imports', snippet: block });\r\n }\r\n return plan;\r\n}\r\n\r\n// ── Laravel ──────────────────────────────────────────────────────────────────────\r\n\r\nfunction laravel(project: Project, c: Connected, api: string): Plan {\r\n const plan = emptyPlan('.env');\r\n plan.commands = [{ label: 'composer require zharp/zharp', argv: ['composer', 'require', 'zharp/zharp'] }];\r\n const endpoint = otlpOf(api);\r\n plan.env.vars = { ZHARP_KEY: c.application.ingestKey, ZHARP_SERVICE: c.application.serviceName, ...(endpoint ? { ZHARP_ENDPOINT: endpoint } : {}) };\r\n plan.notes.push('Laravel finds Zharp by itself (package discovery). Set ZHARP_KEY in production too.');\r\n void project;\r\n return plan;\r\n}\r\n\r\n// ── Go ───────────────────────────────────────────────────────────────────────────\r\n\r\nconst GO_MODULE = 'github.com/zharp-io/zharp-go-lib';\r\n\r\n/** main.go with Zharp started first in main(), and the router wrapped where its shape is known. */\r\nexport function editGoMain(text: string, c: Connected, api: string, routers: { gin: boolean; echo: boolean }): string | null {\r\n if (text.includes(GO_MODULE)) return null;\r\n const block = /^import \\(\\n([\\s\\S]*?)^\\)/m.exec(text);\r\n const mainFn = /^func main\\(\\) \\{\\n/m.exec(text);\r\n if (!block || !mainFn) return null;\r\n const imports = block[1];\r\n const stdlib: string[] = [];\r\n if (!/^\\s*\"context\"$/m.test(imports)) stdlib.push('\\t\"context\"');\r\n const add: string[] = [`\\tzharp \"${GO_MODULE}\"`];\r\n let routerLine = '';\r\n let next = text;\r\n const gin = routers.gin ? /^(\\s*)(\\w+) := gin\\.(?:Default|New)\\(\\)\\n/m.exec(next) : null;\r\n const echo = routers.echo ? /^(\\s*)(\\w+) := echo\\.New\\(\\)\\n/m.exec(next) : null;\r\n if (gin) {\r\n add.push(`\\t\"${GO_MODULE}/zharpgin\"`);\r\n routerLine = `${gin[1]}${gin[2]}.Use(zharpgin.Middleware())\\n`;\r\n next = next.replace(gin[0], gin[0] + routerLine);\r\n } else if (echo) {\r\n add.push(`\\t\"${GO_MODULE}/zharpecho\"`);\r\n routerLine = `${echo[1]}${echo[2]}.Use(zharpecho.Middleware())\\n`;\r\n next = next.replace(echo[0], echo[0] + routerLine);\r\n } else {\r\n // net/http: the handler given to ListenAndServe, traced.\r\n next = next.replace(/http\\.ListenAndServe\\(([^,]+),\\s*(nil|[\\w.]+)\\)/, (_, addr: string, handler: string) =>\r\n `http.ListenAndServe(${addr}, zharp.Handler(${handler === 'nil' ? 'http.DefaultServeMux' : handler}))`);\r\n }\r\n const endpoint = otlpOf(api);\r\n const start = [\r\n \"\\t// The app's key can only send data to this app, so it is safe in code.\",\r\n `\\tshutdown := zharp.Init(zharp.Config{Key: \"${c.application.ingestKey}\", Service: \"${c.application.serviceName}\"${endpoint ? `, Endpoint: \"${api.replace(/\\/+$/, '')}/api/v1/otlp\"` : ''}})`,\r\n '\\tdefer shutdown(context.Background())',\r\n '',\r\n ].join('\\n');\r\n next = next.replace(block[0], `import (\\n${groupedImports(imports, stdlib, add)})`);\r\n next = next.replace(/^func main\\(\\) \\{\\n/m, `func main() {\\n${start}`);\r\n return next;\r\n}\r\n\r\n/**\r\n * The import block's lines with ours added the way goimports keeps them: \"context\" with the\r\n * standard library, the Zharp modules with the other modules (gofmt sorts inside each group).\r\n */\r\nfunction groupedImports(body: string, stdlib: string[], modules: string[]): string {\r\n const groups = body.replace(/\\n+$/, '').split(/\\n[ \\t]*\\n/).map((g) => g.split('\\n'));\r\n // A module path has a dot in its first element (\"github.com/…\"); the standard library's don't.\r\n const isModule = (line: string) => /\"[^\"/]*\\.[^\"/]*\\//.test(line) || /\"[^\"/]*\\.[^\"/]*\"/.test(line);\r\n const std = groups.find((g) => g.some((l) => /\"/.test(l)) && !g.some(isModule));\r\n const mods = groups.find((g) => g.some(isModule));\r\n if (stdlib.length) std ? std.push(...stdlib) : groups.unshift(stdlib);\r\n mods ? mods.push(...modules) : groups.push(modules);\r\n return `${groups.map((g) => g.join('\\n')).join('\\n\\n')}\\n`;\r\n}\r\n\r\nfunction go(project: Project, c: Connected, api: string): Plan {\r\n const plan = emptyPlan(null);\r\n const goMod = read(project.dir, 'go.mod') ?? '';\r\n const routers = { gin: /github\\.com\\/gin-gonic\\/gin/.test(goMod), echo: /github\\.com\\/labstack\\/echo/.test(goMod) };\r\n plan.commands = [{ label: `go get ${GO_MODULE}`, argv: ['go', 'get', `${GO_MODULE}@latest`] }];\r\n if (routers.gin) plan.commands.push({ label: 'go get …/zharpgin', argv: ['go', 'get', `${GO_MODULE}/zharpgin@latest`] });\r\n else if (routers.echo) plan.commands.push({ label: 'go get …/zharpecho', argv: ['go', 'get', `${GO_MODULE}/zharpecho@latest`] });\r\n const mainPath = first(project.dir, ['main.go', 'cmd/server/main.go', 'cmd/api/main.go', 'cmd/main.go']) ?? findFiles(project.dir, 'main.go').find((f) => /func main\\(\\)/.test(read(project.dir, f) ?? '')) ?? null;\r\n const text = mainPath ? read(project.dir, mainPath) : null;\r\n const edited = text ? editGoMain(text, c, api, routers) : null;\r\n if (mainPath && edited) {\r\n plan.changes.push({ path: mainPath, kind: 'edit', content: edited, note: `starts Zharp${routers.gin ? '; traces Gin' : routers.echo ? '; traces Echo' : ''}` });\r\n plan.commands.push({ label: 'go mod tidy', argv: ['go', 'mod', 'tidy'] });\r\n plan.commands.push({ label: `gofmt -w ${mainPath}`, argv: ['gofmt', '-w', mainPath] });\r\n } else if (!text?.includes(GO_MODULE)) {\r\n plan.manual.push({ path: mainPath ?? 'main.go', why: 'start Zharp first in main()', snippet: `shutdown := zharp.Init(zharp.Config{Key: \"${c.application.ingestKey}\"})\\ndefer shutdown(context.Background())` });\r\n }\r\n return plan;\r\n}\r\n\r\nexport function morePlanFor(project: Project, c: Connected, api: string): Plan | null {\r\n switch (project.framework) {\r\n case 'express':\r\n return express(project, c, api);\r\n case 'django':\r\n case 'fastapi':\r\n case 'flask':\r\n return python(project, c, api);\r\n case 'laravel':\r\n return laravel(project, c, api);\r\n case 'go':\r\n return go(project, c, api);\r\n default:\r\n return null;\r\n }\r\n}\r\n","/**\r\n * `zharp init` for React Native and Expo: @zharp/react-native installed and started, release\r\n * builds made readable (the Metro serializer, then the source map uploaded by the Android and\r\n * iOS builds), and the upload key kept where git ignores it.\r\n *\r\n * - Expo: metro.config.js (Expo's default + withZharpConfig), the config plugin in app.json, Zharp\r\n * started in the root layout (Expo Router, with screens) or the entry file; the upload key in\r\n * .env.local for local builds, and EAS secrets for EAS Build.\r\n * - React Native: metro.config.js wrapped, Zharp started first in index.js, android/app/build.gradle\r\n * and the Xcode bundle phase wired as the config plugin wires Expo's; the upload key in\r\n * android/local.properties and ios/.xcode.env.local.\r\n */\r\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\r\nimport { join } from 'node:path';\r\nimport type { Connected } from './connect';\r\nimport type { Project } from './detect';\r\nimport type { Plan } from './recipes';\r\n\r\nconst read = (dir: string, path: string): string | null => {\r\n try {\r\n return readFileSync(join(dir, path), 'utf8').replace(/\\r\\n/g, '\\n');\r\n } catch {\r\n return null;\r\n }\r\n};\r\nconst first = (dir: string, paths: string[]) => paths.find((p) => existsSync(join(dir, p))) ?? null;\r\n\r\nfunction emptyPlan(): Plan {\r\n return { install: [], devInstall: [], changes: [], manual: [], notes: [], env: { file: '', vars: {} }, commands: [] };\r\n}\r\n\r\n/** The ingest endpoint, when it isn't Zharp's own. */\r\nfunction endpointOf(api: string): string | null {\r\n const clean = api.replace(/\\/+$/, '');\r\n return /^https:\\/\\/api\\.zharp\\.io$/.test(clean) ? null : `${clean}/api/v1/otlp`;\r\n}\r\n\r\n// ── shared with app.plugin.js (keep the two in step) ─────────────────────────\r\n\r\nexport const GRADLE_LINE =\r\n `apply from: new File([\"node\", \"--print\", \"require.resolve('@zharp/react-native/package.json')\"].execute(null, rootDir).text.trim(), \"../zharp.gradle\")`;\r\n\r\n/** app/build.gradle with zharp.gradle applied after React Native's plugin (once). */\r\nexport function addGradleLine(text: string): string {\r\n if (text.includes('zharp.gradle')) return text;\r\n const anchor = /^apply plugin: [\"']com\\.facebook\\.react[\"'][^\\n]*$/m;\r\n if (anchor.test(text)) return text.replace(anchor, (line) => `${line}\\n${GRADLE_LINE}`);\r\n return `${text.replace(/\\s*$/, '')}\\n\\n${GRADLE_LINE}\\n`;\r\n}\r\n\r\n/** The bundle phase's script with a source map written first and uploaded after the bundle (once). */\r\nexport function wireBundlePhase(script: string): string {\r\n if (script.includes('zharp-upload.sh')) return script;\r\n const sourceMap = 'export SOURCEMAP_FILE=\"${SOURCEMAP_FILE:-$DERIVED_FILE_DIR/main.jsbundle.map}\"';\r\n const lines = script.split('\\n');\r\n lines.splice(lines[0].trim() === 'set -e' ? 1 : 0, 0, sourceMap);\r\n const upload = '/bin/bash \"$PODS_ROOT/../../node_modules/@zharp/react-native/ios/zharp-upload.sh\"';\r\n return `${lines.join('\\n').replace(/\\s*$/, '')}\\n${upload}\\n`;\r\n}\r\n\r\n/**\r\n * project.pbxproj with the \"Bundle React Native code and images\" phase wired, or null when the\r\n * phase isn't there (or is already wired). The script is one quoted string in the file.\r\n */\r\nexport function wireXcodeProject(pbxproj: string): string | null {\r\n const phase = /(name = \"Bundle React Native code and images\";[\\s\\S]*?shellScript = )(\"(?:[^\"\\\\]|\\\\.)*\")(;)/.exec(pbxproj);\r\n if (!phase) return null;\r\n let script: string;\r\n try {\r\n script = JSON.parse(phase[2]);\r\n } catch {\r\n return null;\r\n }\r\n const wired = wireBundlePhase(script);\r\n if (wired === script) return null;\r\n return pbxproj.replace(phase[0], `${phase[1]}${JSON.stringify(wired)}${phase[3]}`);\r\n}\r\n\r\n// ── edits ────────────────────────────────────────────────────────────────────\r\n\r\n/** metro.config.js with withZharpConfig around what it exports, or null when its shape is unknown. */\r\nexport function wrapMetroConfig(text: string): string | null {\r\n if (text.includes('withZharpConfig')) return null;\r\n const exportLine = /^module\\.exports\\s*=\\s*([\\s\\S]+?);?\\s*$/m;\r\n const m = exportLine.exec(text);\r\n if (!m) return null;\r\n const require = \"const { withZharpConfig } = require('@zharp/react-native/metro');\";\r\n const lines = text.split('\\n');\r\n let lastRequire = -1;\r\n lines.forEach((line, i) => {\r\n if (/^\\s*const .*=\\s*require\\(/.test(line)) lastRequire = i;\r\n });\r\n lines.splice(lastRequire + 1, 0, require);\r\n return lines.join('\\n').replace(exportLine, (_, value: string) => `module.exports = withZharpConfig(${value.trim().replace(/;$/, '')});`);\r\n}\r\n\r\n/** The Zharp.init call, with the app's key (it can only send, so it is safe in the app). */\r\nfunction initBlock(c: Connected, api: string, typescript: boolean): string {\r\n void typescript;\r\n const endpoint = endpointOf(api);\r\n return [\r\n \"// The app's key can only send data to this app, so it is safe in the app.\",\r\n 'Zharp.init({',\r\n ` key: '${c.application.ingestKey}',`,\r\n ` service: '${c.application.serviceName}',`,\r\n ...(endpoint ? [` endpoint: '${endpoint}',`] : []),\r\n '});',\r\n ].join('\\n');\r\n}\r\n\r\n/** `block` (and an import) after a file's leading imports. */\r\nfunction afterImports(text: string, imports: string[], block: string): string {\r\n const lines = text.split('\\n');\r\n let last = -1;\r\n for (let i = 0; i < lines.length; i++) {\r\n const line = lines[i].trim();\r\n if (/^import\\b/.test(line)) {\r\n last = i;\r\n // A multi-line import runs on to its \"from '…';\".\r\n while (last < lines.length - 1 && !/from\\s+['\"][^'\"]+['\"];?\\s*$|^import\\s+['\"][^'\"]+['\"];?\\s*$/.test(lines[last].trim())) last++;\r\n i = last;\r\n } else if (line && !line.startsWith('//') && !line.startsWith('/*') && !line.startsWith('*') && !line.startsWith(\"'use\") && !line.startsWith('\"use')) break;\r\n }\r\n const missing = imports.filter((i) => !text.includes(i));\r\n lines.splice(last + 1, 0, ...missing, ...(block ? ['', block] : []));\r\n return lines.join('\\n');\r\n}\r\n\r\n/** Expo Router's root layout with Zharp started and its screens followed. */\r\nfunction editRootLayout(text: string, c: Connected, api: string, typescript: boolean): string | null {\r\n if (text.includes('@zharp/react-native')) return null;\r\n const fn = /export default function (\\w+)\\s*\\([^)]*\\)\\s*(?::\\s*[^{]+)?\\{\\n/.exec(text);\r\n if (!fn) return null;\r\n let out = afterImports(text, [\"import { Zharp, useZharpNavigation } from '@zharp/react-native';\"], initBlock(c, api, typescript));\r\n if (!/import\\s*\\{[^}]*\\buseNavigationContainerRef\\b[^}]*\\}\\s*from\\s*['\"]expo-router['\"]/.test(out)) {\r\n // Into the file's own `import { … } from 'expo-router'` when it has one.\r\n const existing = /import\\s*\\{([^}]*)\\}\\s*from\\s*(['\"])expo-router\\2;?/.exec(out);\r\n out = existing\r\n ? out.replace(existing[0], existing[0].replace(`{${existing[1]}}`, `{${existing[1].replace(/\\s*$/, '')}, useNavigationContainerRef }`))\r\n : afterImports(out, [\"import { useNavigationContainerRef } from 'expo-router';\"], '');\r\n }\r\n const again = /export default function (\\w+)\\s*\\([^)]*\\)\\s*(?::\\s*[^{]+)?\\{\\n/.exec(out)!;\r\n return out.replace(again[0], `${again[0]} // Each screen the app shows, with the requests it made.\\n useZharpNavigation(useNavigationContainerRef());\\n`);\r\n}\r\n\r\nfunction gitIgnores(dir: string, file: string): boolean {\r\n const ignore = read(dir, '.gitignore') ?? '';\r\n const lines = ignore.split('\\n').map((l) => l.trim());\r\n const name = file.split('/').pop()!;\r\n return lines.some((l) => l === file || l === `/${file}` || l === name || l === `*.${name.split('.').pop()}` || (l === '.env*.local' && /^\\.env.*\\.local$/.test(name)) || (l === '.xcode.env.local' && name === '.xcode.env.local'));\r\n}\r\n\r\n// ── the recipes ──────────────────────────────────────────────────────────────\r\n\r\nfunction metroChange(project: Project, plan: Plan, expo: boolean): void {\r\n const dir = project.dir;\r\n const path = first(dir, ['metro.config.js', 'metro.config.cjs']);\r\n if (!path) {\r\n if (expo) {\r\n plan.changes.push({\r\n path: 'metro.config.js', kind: 'create', note: 'Expo’s config, with release bundles stamped for readable errors',\r\n content: [\r\n \"const { getDefaultConfig } = require('expo/metro-config');\",\r\n \"const { withZharpConfig } = require('@zharp/react-native/metro');\",\r\n '',\r\n 'module.exports = withZharpConfig(getDefaultConfig(__dirname));',\r\n '',\r\n ].join('\\n'),\r\n });\r\n } else {\r\n plan.manual.push({ path: 'metro.config.js', why: 'wrap its config so release errors are readable', snippet: \"const { withZharpConfig } = require('@zharp/react-native/metro');\\nmodule.exports = withZharpConfig(config);\" });\r\n }\r\n return;\r\n }\r\n const text = read(dir, path)!;\r\n const wrapped = wrapMetroConfig(text);\r\n if (wrapped) plan.changes.push({ path, kind: 'edit', content: wrapped, note: 'release bundles stamped for readable errors' });\r\n else if (!text.includes('withZharpConfig')) plan.manual.push({ path, why: 'wrap what it exports so release errors are readable', snippet: \"const { withZharpConfig } = require('@zharp/react-native/metro');\\nmodule.exports = withZharpConfig(/* your config */);\" });\r\n}\r\n\r\nfunction expo(project: Project, c: Connected, api: string): Plan {\r\n const plan = emptyPlan();\r\n const dir = project.dir;\r\n plan.install = ['@zharp/react-native'];\r\n metroChange(project, plan, true);\r\n\r\n // The config plugin, in app.json (an app.config.js/ts is code: shown, not edited).\r\n const appJson = read(dir, 'app.json');\r\n if (appJson && !first(dir, ['app.config.js', 'app.config.ts'])) {\r\n try {\r\n const config = JSON.parse(appJson);\r\n const root = config.expo ?? config;\r\n const plugins: unknown[] = Array.isArray(root.plugins) ? root.plugins : [];\r\n if (!plugins.some((p) => (Array.isArray(p) ? p[0] : p) === '@zharp/react-native')) {\r\n root.plugins = [...plugins, '@zharp/react-native'];\r\n plan.changes.push({ path: 'app.json', kind: 'edit', content: `${JSON.stringify(config, null, 2)}\\n`, note: 'the config plugin: builds upload their source maps' });\r\n }\r\n } catch {\r\n plan.manual.push({ path: 'app.json', why: 'add the config plugin', snippet: '\"plugins\": [\"@zharp/react-native\"]' });\r\n }\r\n } else {\r\n plan.manual.push({ path: 'app.config', why: 'add the config plugin', snippet: \"plugins: ['@zharp/react-native']\" });\r\n }\r\n\r\n // Started first: the root layout (Expo Router, with its screens), else the entry file.\r\n const layout = first(dir, ['app/_layout.tsx', 'app/_layout.jsx', 'app/_layout.js', 'src/app/_layout.tsx', 'src/app/_layout.jsx']);\r\n const entry = (() => {\r\n const main = project.packageJson?.main;\r\n if (typeof main === 'string' && !main.includes('expo-router') && existsSync(join(dir, main))) return main;\r\n return first(dir, ['index.ts', 'index.tsx', 'index.js', 'App.tsx', 'App.js']);\r\n })();\r\n if (layout) {\r\n const edited = editRootLayout(read(dir, layout)!, c, api, project.typescript);\r\n if (edited) plan.changes.push({ path: layout, kind: 'edit', content: edited, note: 'starts Zharp; screens from Expo Router' });\r\n } else if (entry) {\r\n const text = read(dir, entry)!;\r\n if (!text.includes('@zharp/react-native')) {\r\n plan.changes.push({ path: entry, kind: 'edit', content: afterImports(text, [\"import { Zharp } from '@zharp/react-native';\"], initBlock(c, api, project.typescript)), note: 'starts Zharp' });\r\n }\r\n } else {\r\n plan.manual.push({ path: 'your entry file', why: 'start Zharp before the app renders', snippet: `import { Zharp } from '@zharp/react-native';\\n\\n${initBlock(c, api, project.typescript)}` });\r\n }\r\n\r\n // The upload key: .env.local for local builds (expo run), EAS secrets for EAS Build.\r\n plan.env = { file: '.env.local', vars: { ZHARP_AUTH_TOKEN: c.uploadKey, ZHARP_APP: String(c.application.id), ...(endpointOf(api) ? { ZHARP_URL: api.replace(/\\/+$/, '') } : {}) } };\r\n plan.notes.push(`EAS Build: add the upload key as secrets — eas env:create --name ZHARP_AUTH_TOKEN --value <the key in .env.local> --visibility secret, and ZHARP_APP=${c.application.id}.`);\r\n plan.notes.push('EAS Update: after eas update (or npx expo export --source-maps), upload with npx zharp react-native upload --dir dist.');\r\n return plan;\r\n}\r\n\r\nfunction reactNative(project: Project, c: Connected, api: string): Plan {\r\n const plan = emptyPlan();\r\n const dir = project.dir;\r\n plan.install = ['@zharp/react-native'];\r\n metroChange(project, plan, false);\r\n\r\n const entry = first(dir, ['index.js', 'index.ts', 'index.tsx']);\r\n if (entry) {\r\n const text = read(dir, entry)!;\r\n if (!text.includes('@zharp/react-native')) {\r\n plan.changes.push({ path: entry, kind: 'edit', content: afterImports(text, [\"import { Zharp } from '@zharp/react-native';\"], initBlock(c, api, project.typescript)), note: 'starts Zharp, before the app registers' });\r\n }\r\n }\r\n plan.notes.push('Screens: useZharpNavigation(navigationRef) next to your NavigationContainer (React Navigation).');\r\n\r\n // Android: zharp.gradle after React Native's plugin; the upload key in local.properties.\r\n const gradle = read(dir, 'android/app/build.gradle');\r\n if (gradle !== null) {\r\n const edited = addGradleLine(gradle);\r\n if (edited !== gradle) plan.changes.push({ path: 'android/app/build.gradle', kind: 'edit', content: edited, note: 'release builds upload their source map' });\r\n const local = read(dir, 'android/local.properties') ?? '';\r\n if (!/^zharp\\.authToken=/m.test(local)) {\r\n const lines = [`zharp.authToken=${c.uploadKey}`, `zharp.appId=${c.application.id}`];\r\n plan.changes.push({ path: 'android/local.properties', kind: local ? 'edit' : 'create', content: `${local.replace(/\\s*$/, local ? '\\n' : '')}${lines.join('\\n')}\\n`, note: 'the upload key (git ignores this file)' });\r\n if (!gitIgnores(dir, 'android/local.properties') && !gitIgnores(join(dir, 'android'), 'local.properties')) plan.notes.push('android/local.properties holds the upload key: make sure git ignores it.');\r\n }\r\n }\r\n\r\n // iOS: the bundle phase wired; the upload key in ios/.xcode.env.local.\r\n const ios = existsSync(join(dir, 'ios')) ? readdirSync(join(dir, 'ios')).find((name) => name.endsWith('.xcodeproj')) : undefined;\r\n if (ios) {\r\n const path = `ios/${ios}/project.pbxproj`;\r\n const text = read(dir, path);\r\n const wired = text ? wireXcodeProject(text) : null;\r\n if (wired) plan.changes.push({ path, kind: 'edit', content: wired, note: 'the bundle phase writes and uploads its source map' });\r\n const envLocal = read(dir, 'ios/.xcode.env.local') ?? '';\r\n if (!/ZHARP_AUTH_TOKEN=/.test(envLocal)) {\r\n const lines = [`export ZHARP_AUTH_TOKEN=${c.uploadKey}`, `export ZHARP_APP=${c.application.id}`, ...(endpointOf(api) ? [`export ZHARP_URL=${api.replace(/\\/+$/, '')}`] : [])];\r\n plan.changes.push({ path: 'ios/.xcode.env.local', kind: envLocal ? 'edit' : 'create', content: `${envLocal.replace(/\\s*$/, envLocal ? '\\n' : '')}${lines.join('\\n')}\\n`, note: 'the upload key (git ignores this file)' });\r\n }\r\n }\r\n if (endpointOf(api) && gradle !== null) plan.notes.push(`Android builds upload to ${api}: set ZHARP_URL=${api.replace(/\\/+$/, '')} when building.`);\r\n plan.notes.push('CI: set ZHARP_AUTH_TOKEN (the upload key) and ZHARP_APP for release builds.');\r\n return plan;\r\n}\r\n\r\nexport function reactNativePlanFor(project: Project, c: Connected, api: string): Plan | null {\r\n if (project.framework === 'expo') return expo(project, c, api);\r\n if (project.framework === 'react-native') return reactNative(project, c, api);\r\n return null;\r\n}\r\n"],"mappings":";;;;AAIA,u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M,UAAU,OAAO,YAAY,IAAI,QAAQ,OAAO;AACtD,YAAM,YAAY,WAAW,oCAAoC,GAAGC,SAAQ,GAAG,EAAE,SAAAD,UAAS,QAAQ,QAAQ,QAAQ,CAAC;AACnH;AAAA,IACF;AAAA,IACA;AACE,WAAK,oBAAoB,YAAY,KAAK,GAAG,CAAC,0BAA0B;AAAA,EAC5E;AACF;AAIA,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,UAAU;AAC3C,UAAQ,MAAM,kBAAkB,iBAAiB,cAAc,iBAAiB,eAAe,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACvJ,UAAQ,WAAW;AACrB,CAAC;","names":["import_node_fs","resolve","import_node_fs","import_node_path","hex","import_node_fs","read","import_node_fs","import_node_path","release","import_node_fs","import_node_path","withSources","import_node_fs","import_node_path","import_node_fs","import_node_path","hex","out","lines","import_node_child_process","import_node_fs","import_node_path","import_node_child_process","sleep","osPlatform","import_node_fs","import_node_path","import_node_fs","import_node_path","import_node_fs","import_node_path","read","walk","main","installed","import_node_fs","import_node_path","read","first","emptyPlan","require","expo","main","DEFAULT_API","read","first","endpointOf","sep","main","DEFAULT_API","release","connect"]}
|