@zharp/cli 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +94 -3
- package/dist/cli.js +1437 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.mts +292 -0
- package/dist/index.d.ts +292 -0
- package/dist/index.js +850 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +791 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +60 -3
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1437 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// src/cli.ts
|
|
5
|
+
var import_node_util = require("util");
|
|
6
|
+
var import_node_fs8 = require("fs");
|
|
7
|
+
|
|
8
|
+
// src/api.ts
|
|
9
|
+
var import_node_zlib = require("zlib");
|
|
10
|
+
var DEFAULT_URL = "https://api.zharp.io";
|
|
11
|
+
var UploadError = class extends Error {
|
|
12
|
+
constructor(message, status, permanent = false) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.status = status;
|
|
15
|
+
this.permanent = permanent;
|
|
16
|
+
this.name = "UploadError";
|
|
17
|
+
}
|
|
18
|
+
status;
|
|
19
|
+
permanent;
|
|
20
|
+
};
|
|
21
|
+
function resolveConnection(options) {
|
|
22
|
+
const authToken = options.authToken || process.env.ZHARP_AUTH_TOKEN;
|
|
23
|
+
const app = options.app ?? process.env.ZHARP_APP;
|
|
24
|
+
const missing = [];
|
|
25
|
+
if (!authToken) missing.push('an auth token (ZHARP_AUTH_TOKEN, or the authToken option): a workspace API key with the "artifacts:write" scope');
|
|
26
|
+
if (app === void 0 || app === "") missing.push("the application ID (--app, the app option, or ZHARP_APP)");
|
|
27
|
+
if (missing.length) throw new UploadError(`Cannot upload without ${missing.join(" and ")}.`, void 0, true);
|
|
28
|
+
return { url: (options.url || process.env.ZHARP_URL || DEFAULT_URL).replace(/\/+$/, ""), authToken, app };
|
|
29
|
+
}
|
|
30
|
+
function artifactsUrl(connection) {
|
|
31
|
+
return `${connection.url}/api/v1/applications/${encodeURIComponent(String(connection.app))}/artifacts`;
|
|
32
|
+
}
|
|
33
|
+
var sleep = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
|
|
34
|
+
async function uploadArtifact(connection, artifact, options = {}) {
|
|
35
|
+
const doFetch = options.fetch ?? fetch;
|
|
36
|
+
const retries = options.retries ?? 3;
|
|
37
|
+
const backoff = options.backoffMs ?? 1e3;
|
|
38
|
+
const fileName = (artifact.name.split("/").pop() || "artifact") + (artifact.gzip ? ".gz" : "");
|
|
39
|
+
const payload = artifact.gzip ? (0, import_node_zlib.gzipSync)(artifact.data) : artifact.data;
|
|
40
|
+
for (let attempt = 0; ; attempt++) {
|
|
41
|
+
const form = new FormData();
|
|
42
|
+
form.set("kind", artifact.kind);
|
|
43
|
+
form.set("debugId", artifact.debugId);
|
|
44
|
+
form.set("name", artifact.name);
|
|
45
|
+
if (artifact.release) form.set("release", artifact.release);
|
|
46
|
+
if (artifact.arch) form.set("arch", artifact.arch);
|
|
47
|
+
const type = artifact.gzip ? "application/gzip" : artifact.kind === "sourcemap" ? "application/json" : "application/octet-stream";
|
|
48
|
+
form.set("file", new Blob([payload], { type }), fileName);
|
|
49
|
+
let retryAfter = 0;
|
|
50
|
+
let error;
|
|
51
|
+
try {
|
|
52
|
+
const response = await doFetch(artifactsUrl(connection), {
|
|
53
|
+
method: "POST",
|
|
54
|
+
headers: { Authorization: `Bearer ${connection.authToken}`, "User-Agent": "zharp-cli" },
|
|
55
|
+
body: form
|
|
56
|
+
});
|
|
57
|
+
const text = await response.text().catch(() => "");
|
|
58
|
+
if (response.ok) {
|
|
59
|
+
try {
|
|
60
|
+
return text ? JSON.parse(text) : null;
|
|
61
|
+
} catch {
|
|
62
|
+
return text;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
error = describeFailure(response.status, text, connection);
|
|
66
|
+
retryAfter = Number(response.headers.get("retry-after")) * 1e3 || 0;
|
|
67
|
+
} catch (cause) {
|
|
68
|
+
error = new UploadError(`Could not reach ${connection.url}: ${cause?.message ?? cause}`);
|
|
69
|
+
}
|
|
70
|
+
if (error.permanent || attempt >= retries) throw error;
|
|
71
|
+
await sleep(Math.max(retryAfter, backoff * 2 ** attempt));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function serverMessage(text) {
|
|
75
|
+
try {
|
|
76
|
+
const body = JSON.parse(text);
|
|
77
|
+
const message = body?.message ?? body?.error;
|
|
78
|
+
if (typeof message === "string") return message;
|
|
79
|
+
if (Array.isArray(message)) return message.join("; ");
|
|
80
|
+
} catch {
|
|
81
|
+
}
|
|
82
|
+
return text.slice(0, 300);
|
|
83
|
+
}
|
|
84
|
+
function describeFailure(status, text, connection) {
|
|
85
|
+
const detail = serverMessage(text);
|
|
86
|
+
const retryable = status === 408 || status === 429 || status >= 500;
|
|
87
|
+
const explain = {
|
|
88
|
+
401: "The auth token was rejected \u2014 check ZHARP_AUTH_TOKEN (a workspace API key, not the app key).",
|
|
89
|
+
403: 'The API key cannot upload here \u2014 it needs the "artifacts:write" scope, in the workspace that owns the app.',
|
|
90
|
+
404: `Application ${connection.app} was not found \u2014 check --app (the ID in the app's dashboard URL) and ZHARP_URL.`,
|
|
91
|
+
413: "The file is larger than the server accepts."
|
|
92
|
+
};
|
|
93
|
+
const message = `${explain[status] ?? `Upload failed with HTTP ${status}.`}${detail ? ` Server said: ${detail}` : ""}`;
|
|
94
|
+
return new UploadError(message, status, !retryable);
|
|
95
|
+
}
|
|
96
|
+
async function eachLimit(items, limit, fn) {
|
|
97
|
+
let next = 0;
|
|
98
|
+
let failed;
|
|
99
|
+
const worker = async () => {
|
|
100
|
+
while (failed === void 0 && next < items.length) {
|
|
101
|
+
const index = next++;
|
|
102
|
+
try {
|
|
103
|
+
await fn(items[index], index);
|
|
104
|
+
} catch (error) {
|
|
105
|
+
failed ??= error;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
110
|
+
if (failed !== void 0) throw failed;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// src/log.ts
|
|
114
|
+
var consoleLogger = (prefix = "[zharp]") => ({
|
|
115
|
+
info: (message) => console.log(`${prefix} ${message}`),
|
|
116
|
+
warn: (message) => console.warn(`${prefix} ${message}`)
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
// src/native.ts
|
|
120
|
+
var import_node_fs2 = require("fs");
|
|
121
|
+
var import_node_path2 = require("path");
|
|
122
|
+
|
|
123
|
+
// src/elf.ts
|
|
124
|
+
var NT_GNU_BUILD_ID = 3;
|
|
125
|
+
var SHT_NOTE = 7;
|
|
126
|
+
var PT_NOTE = 4;
|
|
127
|
+
var MACHINES = { 3: "x86", 40: "arm", 62: "x86_64", 183: "arm64", 243: "riscv64" };
|
|
128
|
+
function isElf(data) {
|
|
129
|
+
return data.length >= 16 && data[0] === 127 && data[1] === 69 && data[2] === 76 && data[3] === 70;
|
|
130
|
+
}
|
|
131
|
+
function readElf(data) {
|
|
132
|
+
if (!isElf(data)) throw new Error("not an ELF file");
|
|
133
|
+
const bits = data[4] === 2 ? 64 : 32;
|
|
134
|
+
const littleEndian = data[5] !== 2;
|
|
135
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
136
|
+
const u16 = (o) => view.getUint16(o, littleEndian);
|
|
137
|
+
const u32 = (o) => view.getUint32(o, littleEndian);
|
|
138
|
+
const addr = (o) => bits === 64 ? Number(view.getBigUint64(o, littleEndian)) : u32(o);
|
|
139
|
+
const info = { bits, littleEndian, arch: MACHINES[u16(18)] };
|
|
140
|
+
const notes = (offset, size) => {
|
|
141
|
+
let p = offset;
|
|
142
|
+
const end = Math.min(offset + size, data.length);
|
|
143
|
+
while (p + 12 <= end) {
|
|
144
|
+
const nameSize = u32(p);
|
|
145
|
+
const descSize = u32(p + 4);
|
|
146
|
+
const type = u32(p + 8);
|
|
147
|
+
const nameStart = p + 12;
|
|
148
|
+
const descStart = nameStart + align4(nameSize);
|
|
149
|
+
if (descStart + descSize > end) break;
|
|
150
|
+
const name = String.fromCharCode(...data.subarray(nameStart, nameStart + Math.max(0, nameSize - 1)));
|
|
151
|
+
if (name === "GNU" && type === NT_GNU_BUILD_ID) return hex(data.subarray(descStart, descStart + descSize));
|
|
152
|
+
p = descStart + align4(descSize);
|
|
153
|
+
}
|
|
154
|
+
return void 0;
|
|
155
|
+
};
|
|
156
|
+
const shoff = addr(bits === 64 ? 40 : 32);
|
|
157
|
+
const shentsize = u16(bits === 64 ? 58 : 46);
|
|
158
|
+
const shnum = u16(bits === 64 ? 60 : 48);
|
|
159
|
+
for (let i = 0; i < shnum && shoff > 0; i++) {
|
|
160
|
+
const h = shoff + i * shentsize;
|
|
161
|
+
if (h + shentsize > data.length) break;
|
|
162
|
+
if (u32(h + 4) !== SHT_NOTE) continue;
|
|
163
|
+
const offset = addr(bits === 64 ? h + 24 : h + 16);
|
|
164
|
+
const size = addr(bits === 64 ? h + 32 : h + 20);
|
|
165
|
+
const id = notes(offset, size);
|
|
166
|
+
if (id) return { ...info, buildId: id };
|
|
167
|
+
}
|
|
168
|
+
const phoff = addr(bits === 64 ? 32 : 28);
|
|
169
|
+
const phentsize = u16(bits === 64 ? 54 : 42);
|
|
170
|
+
const phnum = u16(bits === 64 ? 56 : 44);
|
|
171
|
+
for (let i = 0; i < phnum && phoff > 0; i++) {
|
|
172
|
+
const h = phoff + i * phentsize;
|
|
173
|
+
if (h + phentsize > data.length) break;
|
|
174
|
+
if (u32(h) !== PT_NOTE) continue;
|
|
175
|
+
const offset = addr(bits === 64 ? h + 8 : h + 4);
|
|
176
|
+
const size = addr(bits === 64 ? h + 32 : h + 16);
|
|
177
|
+
const id = notes(offset, size);
|
|
178
|
+
if (id) return { ...info, buildId: id };
|
|
179
|
+
}
|
|
180
|
+
return info;
|
|
181
|
+
}
|
|
182
|
+
var align4 = (n) => n + 3 & ~3;
|
|
183
|
+
function hex(bytes) {
|
|
184
|
+
let out = "";
|
|
185
|
+
for (const b of bytes) out += b.toString(16).padStart(2, "0");
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// src/files.ts
|
|
190
|
+
var import_node_fs = require("fs");
|
|
191
|
+
var import_node_path = require("path");
|
|
192
|
+
function walk(dir) {
|
|
193
|
+
const out = [];
|
|
194
|
+
const visit = (current) => {
|
|
195
|
+
for (const entry of (0, import_node_fs.readdirSync)(current, { withFileTypes: true })) {
|
|
196
|
+
const full = (0, import_node_path.join)(current, entry.name);
|
|
197
|
+
if (entry.isDirectory()) {
|
|
198
|
+
if (entry.name !== "node_modules") visit(full);
|
|
199
|
+
} else if (entry.isFile()) out.push(full);
|
|
200
|
+
else if (entry.isSymbolicLink()) {
|
|
201
|
+
try {
|
|
202
|
+
if ((0, import_node_fs.statSync)(full).isFile()) out.push(full);
|
|
203
|
+
} catch {
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
visit(dir);
|
|
209
|
+
return out.sort();
|
|
210
|
+
}
|
|
211
|
+
function relativePath(dir, path) {
|
|
212
|
+
return (0, import_node_path.relative)(dir, path).split(import_node_path.sep).join("/");
|
|
213
|
+
}
|
|
214
|
+
function globToRegExp(glob) {
|
|
215
|
+
let out = "";
|
|
216
|
+
for (let i = 0; i < glob.length; i++) {
|
|
217
|
+
const c = glob[i];
|
|
218
|
+
if (c === "*") {
|
|
219
|
+
if (glob[i + 1] === "*") {
|
|
220
|
+
const slash = glob[i + 2] === "/";
|
|
221
|
+
out += slash ? "(?:.*/)?" : ".*";
|
|
222
|
+
i += slash ? 2 : 1;
|
|
223
|
+
} else out += "[^/]*";
|
|
224
|
+
} else if (c === "?") out += "[^/]";
|
|
225
|
+
else out += /[.+^${}()|[\]\\]/.test(c) ? `\\${c}` : c;
|
|
226
|
+
}
|
|
227
|
+
return new RegExp(glob.includes("/") ? `^${out}$` : `(?:^|/)${out}$`);
|
|
228
|
+
}
|
|
229
|
+
function toList(pattern) {
|
|
230
|
+
if (pattern === void 0) return [];
|
|
231
|
+
return (Array.isArray(pattern) ? pattern : [pattern]).map((p) => typeof p === "string" ? globToRegExp(p) : p);
|
|
232
|
+
}
|
|
233
|
+
function pathFilter(include, exclude) {
|
|
234
|
+
const inc = toList(include);
|
|
235
|
+
const exc = toList(exclude);
|
|
236
|
+
return (path) => (inc.length === 0 || inc.some((r) => r.test(path))) && !exc.some((r) => r.test(path));
|
|
237
|
+
}
|
|
238
|
+
function formatBytes(bytes) {
|
|
239
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
240
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
|
|
241
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// src/macho.ts
|
|
245
|
+
var LC_UUID = 27;
|
|
246
|
+
var MH_MAGIC = 4277009102;
|
|
247
|
+
var MH_MAGIC_64 = 4277009103;
|
|
248
|
+
var FAT_MAGIC = 3405691582;
|
|
249
|
+
var FAT_MAGIC_64 = 3405691583;
|
|
250
|
+
function isMachO(data) {
|
|
251
|
+
if (data.length < 8) return false;
|
|
252
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
253
|
+
const be = view.getUint32(0, false);
|
|
254
|
+
const le = view.getUint32(0, true);
|
|
255
|
+
return be === FAT_MAGIC || be === FAT_MAGIC_64 || [MH_MAGIC, MH_MAGIC_64].includes(le) || [MH_MAGIC, MH_MAGIC_64].includes(be);
|
|
256
|
+
}
|
|
257
|
+
function archName(cpuType, cpuSubtype) {
|
|
258
|
+
const sub = cpuSubtype & 16777215;
|
|
259
|
+
switch (cpuType) {
|
|
260
|
+
case 16777228:
|
|
261
|
+
return sub === 2 ? "arm64e" : "arm64";
|
|
262
|
+
case 33554444:
|
|
263
|
+
return "arm64_32";
|
|
264
|
+
case 12:
|
|
265
|
+
return sub === 9 ? "armv7" : sub === 11 ? "armv7s" : sub === 12 ? "armv7k" : "arm";
|
|
266
|
+
case 16777223:
|
|
267
|
+
return sub === 8 ? "x86_64h" : "x86_64";
|
|
268
|
+
case 7:
|
|
269
|
+
return "i386";
|
|
270
|
+
default:
|
|
271
|
+
return `cpu${cpuType}`;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
function readMachO(data) {
|
|
275
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
276
|
+
const magic = view.getUint32(0, false);
|
|
277
|
+
if (magic === FAT_MAGIC || magic === FAT_MAGIC_64) {
|
|
278
|
+
const wide = magic === FAT_MAGIC_64;
|
|
279
|
+
const count = view.getUint32(4, false);
|
|
280
|
+
const images = [];
|
|
281
|
+
for (let i = 0; i < count; i++) {
|
|
282
|
+
const h = 8 + i * (wide ? 32 : 20);
|
|
283
|
+
const offset = wide ? Number(view.getBigUint64(h + 8, false)) : view.getUint32(h + 8, false);
|
|
284
|
+
const size = wide ? Number(view.getBigUint64(h + 16, false)) : view.getUint32(h + 12, false);
|
|
285
|
+
images.push(...readThin(data.subarray(offset, offset + size)).map((image) => ({ ...image, offset })));
|
|
286
|
+
}
|
|
287
|
+
return images;
|
|
288
|
+
}
|
|
289
|
+
return readThin(data);
|
|
290
|
+
}
|
|
291
|
+
function readThin(data) {
|
|
292
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
293
|
+
let little;
|
|
294
|
+
if ([MH_MAGIC, MH_MAGIC_64].includes(view.getUint32(0, true))) little = true;
|
|
295
|
+
else if ([MH_MAGIC, MH_MAGIC_64].includes(view.getUint32(0, false))) little = false;
|
|
296
|
+
else throw new Error("not a Mach-O file");
|
|
297
|
+
const wide = view.getUint32(0, little) === MH_MAGIC_64;
|
|
298
|
+
const cpuType = view.getUint32(4, little);
|
|
299
|
+
const cpuSubtype = view.getUint32(8, little);
|
|
300
|
+
const ncmds = view.getUint32(16, little);
|
|
301
|
+
let p = wide ? 32 : 28;
|
|
302
|
+
for (let i = 0; i < ncmds && p + 8 <= data.length; i++) {
|
|
303
|
+
const cmd = view.getUint32(p, little);
|
|
304
|
+
const size = view.getUint32(p + 4, little);
|
|
305
|
+
if (cmd === LC_UUID && p + 24 <= data.length) {
|
|
306
|
+
return [{ uuid: formatUuid(data.subarray(p + 8, p + 24)), arch: archName(cpuType, cpuSubtype), offset: 0, size: data.length }];
|
|
307
|
+
}
|
|
308
|
+
if (size < 8) break;
|
|
309
|
+
p += size;
|
|
310
|
+
}
|
|
311
|
+
return [];
|
|
312
|
+
}
|
|
313
|
+
function formatUuid(bytes) {
|
|
314
|
+
let hex2 = "";
|
|
315
|
+
for (const b of bytes) hex2 += b.toString(16).padStart(2, "0");
|
|
316
|
+
hex2 = hex2.toUpperCase();
|
|
317
|
+
return `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20)}`;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// src/native.ts
|
|
321
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
322
|
+
async function send(connection, artifacts, options) {
|
|
323
|
+
const logger = options.logger ?? consoleLogger();
|
|
324
|
+
let done = 0;
|
|
325
|
+
await eachLimit(artifacts, 2, async (artifact) => {
|
|
326
|
+
if (!options.dryRun) {
|
|
327
|
+
if (!connection) throw new Error("No connection to upload to.");
|
|
328
|
+
await uploadArtifact(connection, artifact, { fetch: options.fetch, retries: options.retries });
|
|
329
|
+
}
|
|
330
|
+
done += 1;
|
|
331
|
+
const extra = artifact.arch ? ` ${artifact.arch}` : "";
|
|
332
|
+
logger.info(` [${done}/${artifacts.length}] ${options.dryRun ? "would upload" : "uploaded"} ${artifact.kind} ${artifact.name}${extra} (${formatBytes(artifact.data.length)}) ${artifact.debugId}`);
|
|
333
|
+
});
|
|
334
|
+
return artifacts;
|
|
335
|
+
}
|
|
336
|
+
async function uploadProguard(mappingFile, uuid, connection, options = {}) {
|
|
337
|
+
if (!UUID.test(uuid)) throw new Error(`--uuid must be a UUID, got "${uuid}".`);
|
|
338
|
+
const data = (0, import_node_fs2.readFileSync)(mappingFile);
|
|
339
|
+
return send(connection, [{ kind: "proguard", debugId: uuid.toLowerCase(), name: (0, import_node_path2.basename)(mappingFile), release: options.release, data, gzip: true }], options);
|
|
340
|
+
}
|
|
341
|
+
var DART_ARCH = { x86_64: "x64", x86: "ia32" };
|
|
342
|
+
function findDartSymbols(path, logger = consoleLogger()) {
|
|
343
|
+
const files = (0, import_node_fs2.statSync)(path).isDirectory() ? walk((0, import_node_path2.resolve)(path)) : [(0, import_node_path2.resolve)(path)];
|
|
344
|
+
const out = [];
|
|
345
|
+
for (const file of files) {
|
|
346
|
+
const named = /\.symbols$/.test(file);
|
|
347
|
+
const data = (0, import_node_fs2.readFileSync)(file);
|
|
348
|
+
if (!isElf(data)) {
|
|
349
|
+
if (named) logger.warn(`Skipped ${(0, import_node_path2.basename)(file)}: not an ELF file.`);
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
const elf = readElf(data);
|
|
353
|
+
if (!elf.buildId) {
|
|
354
|
+
logger.warn(`Skipped ${(0, import_node_path2.basename)(file)}: it has no GNU build ID.`);
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
const match = /\.([a-z]+)-([a-z0-9_]+)\.symbols$/.exec((0, import_node_path2.basename)(file));
|
|
358
|
+
out.push({ path: file, buildId: elf.buildId, os: match?.[1], arch: match?.[2] ?? (elf.arch && (DART_ARCH[elf.arch] ?? elf.arch)) });
|
|
359
|
+
}
|
|
360
|
+
return out;
|
|
361
|
+
}
|
|
362
|
+
function findObfuscationMap(symbolsPath) {
|
|
363
|
+
const dir = (0, import_node_fs2.statSync)(symbolsPath).isDirectory() ? (0, import_node_path2.resolve)(symbolsPath) : (0, import_node_path2.dirname)((0, import_node_path2.resolve)(symbolsPath));
|
|
364
|
+
for (const where of [dir, (0, import_node_path2.dirname)(dir)]) {
|
|
365
|
+
let names;
|
|
366
|
+
try {
|
|
367
|
+
names = (0, import_node_fs2.readdirSync)(where).sort();
|
|
368
|
+
} catch {
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
const found = names.find((n) => n === "obfuscation.json") ?? names.find((n) => n.endsWith(".obfuscation.json"));
|
|
372
|
+
if (found && (0, import_node_fs2.statSync)((0, import_node_path2.join)(where, found)).isFile()) return (0, import_node_path2.join)(where, found);
|
|
373
|
+
}
|
|
374
|
+
return void 0;
|
|
375
|
+
}
|
|
376
|
+
function readObfuscationMap(file) {
|
|
377
|
+
const data = (0, import_node_fs2.readFileSync)(file);
|
|
378
|
+
let parsed;
|
|
379
|
+
try {
|
|
380
|
+
parsed = JSON.parse(data.toString("utf8"));
|
|
381
|
+
} catch (error) {
|
|
382
|
+
throw new Error(`${file} is not valid JSON (${error.message}).`);
|
|
383
|
+
}
|
|
384
|
+
if (!Array.isArray(parsed)) throw new Error(`${file} is not a Dart obfuscation map: expected a JSON array of [obfuscated, original] names.`);
|
|
385
|
+
return data;
|
|
386
|
+
}
|
|
387
|
+
async function uploadDartSymbols(path, connection, options = {}) {
|
|
388
|
+
const logger = options.logger ?? consoleLogger();
|
|
389
|
+
const files = findDartSymbols(path, logger);
|
|
390
|
+
if (files.length === 0) throw new Error(`No Dart symbol files in ${path} \u2014 build with \`flutter build \u2026 --obfuscate --split-debug-info=<dir>\` and pass that directory.`);
|
|
391
|
+
logger.info(`${options.dryRun ? "Would upload" : "Uploading"} ${files.length} Dart symbol file(s)`);
|
|
392
|
+
const artifacts = files.map((f) => ({
|
|
393
|
+
kind: "dart-symbols",
|
|
394
|
+
debugId: f.buildId,
|
|
395
|
+
name: (0, import_node_path2.basename)(f.path),
|
|
396
|
+
arch: f.arch,
|
|
397
|
+
release: options.release,
|
|
398
|
+
data: (0, import_node_fs2.readFileSync)(f.path),
|
|
399
|
+
gzip: true
|
|
400
|
+
}));
|
|
401
|
+
if (options.obfuscationMap && !(0, import_node_fs2.existsSync)(options.obfuscationMap)) throw new Error(`${options.obfuscationMap} does not exist.`);
|
|
402
|
+
const mapFile = options.obfuscationMap ?? findObfuscationMap(path);
|
|
403
|
+
if (mapFile) {
|
|
404
|
+
const data = readObfuscationMap(mapFile);
|
|
405
|
+
const buildIds = [...new Set(files.map((f) => f.buildId))];
|
|
406
|
+
logger.info(`With obfuscation map ${(0, import_node_path2.basename)(mapFile)} for ${buildIds.length} build ID(s)`);
|
|
407
|
+
for (const debugId of buildIds) {
|
|
408
|
+
artifacts.push({ kind: "dart-obfuscation-map", debugId, name: (0, import_node_path2.basename)(mapFile), release: options.release, data, gzip: true });
|
|
409
|
+
}
|
|
410
|
+
} else {
|
|
411
|
+
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.");
|
|
412
|
+
}
|
|
413
|
+
return send(connection, artifacts, options);
|
|
414
|
+
}
|
|
415
|
+
function findDsymImages(path) {
|
|
416
|
+
const root = (0, import_node_path2.resolve)(path);
|
|
417
|
+
const candidates = (0, import_node_fs2.statSync)(root).isDirectory() ? walk(root).filter((f) => /[\\/]Contents[\\/]Resources[\\/]DWARF[\\/][^\\/]+$/.test(f)) : [root];
|
|
418
|
+
const out = [];
|
|
419
|
+
for (const file of candidates) {
|
|
420
|
+
const data = (0, import_node_fs2.readFileSync)(file);
|
|
421
|
+
if (!isMachO(data)) continue;
|
|
422
|
+
for (const image of readMachO(data)) out.push({ path: file, ...image });
|
|
423
|
+
}
|
|
424
|
+
return out;
|
|
425
|
+
}
|
|
426
|
+
async function uploadDsyms(path, connection, options = {}) {
|
|
427
|
+
const logger = options.logger ?? consoleLogger();
|
|
428
|
+
const images = findDsymImages(path);
|
|
429
|
+
if (images.length === 0) throw new Error(`No dSYM DWARF files in ${path} \u2014 pass a .dSYM bundle or the folder that holds them ($DWARF_DSYM_FOLDER_PATH).`);
|
|
430
|
+
logger.info(`${options.dryRun ? "Would upload" : "Uploading"} ${images.length} dSYM image(s)`);
|
|
431
|
+
const cache = /* @__PURE__ */ new Map();
|
|
432
|
+
const artifacts = images.map((image) => {
|
|
433
|
+
let data = cache.get(image.path);
|
|
434
|
+
if (!data) cache.set(image.path, data = (0, import_node_fs2.readFileSync)(image.path));
|
|
435
|
+
return {
|
|
436
|
+
kind: "dsym",
|
|
437
|
+
debugId: image.uuid,
|
|
438
|
+
name: (0, import_node_path2.basename)(image.path),
|
|
439
|
+
arch: image.arch,
|
|
440
|
+
release: options.release,
|
|
441
|
+
// One architecture's slice of a universal file is a complete Mach-O file on its own.
|
|
442
|
+
data: data.subarray(image.offset, image.offset + image.size),
|
|
443
|
+
gzip: true
|
|
444
|
+
};
|
|
445
|
+
});
|
|
446
|
+
return send(connection, artifacts, options);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// src/sourcemaps.ts
|
|
450
|
+
var import_node_fs4 = require("fs");
|
|
451
|
+
var import_node_path4 = require("path");
|
|
452
|
+
|
|
453
|
+
// src/debug-id.ts
|
|
454
|
+
var import_node_crypto = require("crypto");
|
|
455
|
+
var import_node_fs3 = require("fs");
|
|
456
|
+
var import_node_path3 = require("path");
|
|
457
|
+
var import_node_url = require("url");
|
|
458
|
+
var DEBUG_ID_COMMENT = "//# debugId=";
|
|
459
|
+
var DEBUG_ID_PATTERN = /^\/\/# debugId=([0-9a-fA-F-]{36})\s*$/m;
|
|
460
|
+
var SOURCE_MAPPING_URL = /^\/\/[#@] sourceMappingURL=(.*?)\s*$/;
|
|
461
|
+
function debugIdFromContent(content) {
|
|
462
|
+
const bytes = (0, import_node_crypto.createHash)("sha256").update(content).digest().subarray(0, 16);
|
|
463
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
464
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
465
|
+
const hex2 = bytes.toString("hex");
|
|
466
|
+
return `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20)}`;
|
|
467
|
+
}
|
|
468
|
+
function registrationSnippet(debugId) {
|
|
469
|
+
return `;!function(){try{var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},s=(new Error).stack;s&&((g.__zharpDebugIds=g.__zharpDebugIds||{})[s]="${debugId}")}catch(e){}}();`;
|
|
470
|
+
}
|
|
471
|
+
function existingDebugId(code) {
|
|
472
|
+
const lines = code.trimEnd().split("\n");
|
|
473
|
+
for (let i = lines.length - 1; i >= 0 && i >= lines.length - 4; i--) {
|
|
474
|
+
const match = DEBUG_ID_PATTERN.exec(lines[i].trim());
|
|
475
|
+
if (match) return match[1].toLowerCase();
|
|
476
|
+
}
|
|
477
|
+
return void 0;
|
|
478
|
+
}
|
|
479
|
+
function hasRegistration(code) {
|
|
480
|
+
return code.slice(-2e3).includes(".__zharpDebugIds=");
|
|
481
|
+
}
|
|
482
|
+
function sourceMappingUrl(code) {
|
|
483
|
+
const lines = code.trimEnd().split("\n");
|
|
484
|
+
for (let i = lines.length - 1; i >= 0 && i >= lines.length - 3; i--) {
|
|
485
|
+
const match = SOURCE_MAPPING_URL.exec(lines[i].trim());
|
|
486
|
+
if (match) return match[1];
|
|
487
|
+
}
|
|
488
|
+
return void 0;
|
|
489
|
+
}
|
|
490
|
+
function injectCode(code, options = {}) {
|
|
491
|
+
const existing = existingDebugId(code);
|
|
492
|
+
const eol = code.includes("\r\n") ? "\r\n" : "\n";
|
|
493
|
+
if (existing) {
|
|
494
|
+
let out2 = code;
|
|
495
|
+
if (!hasRegistration(code)) {
|
|
496
|
+
const lines2 = code.split(/\r?\n/);
|
|
497
|
+
let at = lines2.length - 1;
|
|
498
|
+
while (at > 0 && !lines2[at].trim().startsWith(DEBUG_ID_COMMENT)) at--;
|
|
499
|
+
lines2.splice(at, 0, registrationSnippet(existing));
|
|
500
|
+
out2 = lines2.join(eol);
|
|
501
|
+
}
|
|
502
|
+
if (options.stripSourceMappingUrl) out2 = withoutSourceMappingUrl(out2);
|
|
503
|
+
return { code: out2, debugId: existing, changed: out2 !== code };
|
|
504
|
+
}
|
|
505
|
+
const debugId = debugIdFromContent(code);
|
|
506
|
+
const lines = code.split(/\r?\n/);
|
|
507
|
+
let tail = [];
|
|
508
|
+
let end = lines.length;
|
|
509
|
+
while (end > 0 && lines[end - 1].trim() === "") end--;
|
|
510
|
+
if (end > 0 && SOURCE_MAPPING_URL.test(lines[end - 1].trim())) {
|
|
511
|
+
tail = options.stripSourceMappingUrl ? [] : [lines[end - 1]];
|
|
512
|
+
end--;
|
|
513
|
+
}
|
|
514
|
+
const body = lines.slice(0, end);
|
|
515
|
+
const out = [...body, registrationSnippet(debugId), `${DEBUG_ID_COMMENT}${debugId}`, ...tail].join(eol) + eol;
|
|
516
|
+
return { code: out, debugId, changed: true };
|
|
517
|
+
}
|
|
518
|
+
function withoutSourceMappingUrl(code) {
|
|
519
|
+
const lines = code.split(/\r?\n/);
|
|
520
|
+
const eol = code.includes("\r\n") ? "\r\n" : "\n";
|
|
521
|
+
let end = lines.length;
|
|
522
|
+
while (end > 0 && lines[end - 1].trim() === "") end--;
|
|
523
|
+
if (end > 0 && SOURCE_MAPPING_URL.test(lines[end - 1].trim())) return lines.slice(0, end - 1).join(eol) + eol;
|
|
524
|
+
return code;
|
|
525
|
+
}
|
|
526
|
+
function injectMap(mapText, debugId, mapPath) {
|
|
527
|
+
const map = JSON.parse(mapText);
|
|
528
|
+
if (!map || typeof map !== "object") throw new Error("not a source map");
|
|
529
|
+
const filled = mapPath ? fillSourcesContent(map, mapPath) : 0;
|
|
530
|
+
const hasSourcesContent = Array.isArray(map.sourcesContent) && map.sourcesContent.some((s) => typeof s === "string");
|
|
531
|
+
if (!filled && map.debugId === debugId && map.debug_id === debugId) return { text: mapText, changed: false, hasSourcesContent };
|
|
532
|
+
map.debugId = debugId;
|
|
533
|
+
map.debug_id = debugId;
|
|
534
|
+
return { text: JSON.stringify(map), changed: true, hasSourcesContent };
|
|
535
|
+
}
|
|
536
|
+
var MAX_SOURCE_BYTES = 1e6;
|
|
537
|
+
function sourcePathCandidates(source, mapPath, sourceRoot = "") {
|
|
538
|
+
const mapDir = (0, import_node_path3.dirname)(mapPath);
|
|
539
|
+
let stripped = source;
|
|
540
|
+
let projectRelative = false;
|
|
541
|
+
if (/^turbopack:\/\/\/\[project\]\//.test(source)) {
|
|
542
|
+
stripped = source.replace(/^turbopack:\/\/\/\[project\]\//, "");
|
|
543
|
+
projectRelative = true;
|
|
544
|
+
} else if (/^webpack:\/\//.test(source)) {
|
|
545
|
+
stripped = source.replace(/^webpack:\/\/[^/]*\//, "").replace(/^\.\//, "");
|
|
546
|
+
projectRelative = true;
|
|
547
|
+
} else if (/^file:\/\//.test(source)) {
|
|
548
|
+
try {
|
|
549
|
+
return [(0, import_node_url.fileURLToPath)(source)];
|
|
550
|
+
} catch {
|
|
551
|
+
return [];
|
|
552
|
+
}
|
|
553
|
+
} else if (/^[a-z][\w+.-]*:\/\//i.test(source)) {
|
|
554
|
+
return [];
|
|
555
|
+
}
|
|
556
|
+
if ((0, import_node_path3.isAbsolute)(stripped)) return [stripped];
|
|
557
|
+
const out = [(0, import_node_path3.resolve)(mapDir, sourceRoot, stripped)];
|
|
558
|
+
if (projectRelative) {
|
|
559
|
+
for (let dir = mapDir, i = 0; i < 12; i++) {
|
|
560
|
+
if ((0, import_node_fs3.existsSync)((0, import_node_path3.join)(dir, "package.json"))) {
|
|
561
|
+
out.unshift((0, import_node_path3.join)(dir, stripped));
|
|
562
|
+
break;
|
|
563
|
+
}
|
|
564
|
+
const up = (0, import_node_path3.dirname)(dir);
|
|
565
|
+
if (up === dir) break;
|
|
566
|
+
dir = up;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return out;
|
|
570
|
+
}
|
|
571
|
+
function fillSourcesContent(map, mapPath) {
|
|
572
|
+
if (!Array.isArray(map.sources)) return 0;
|
|
573
|
+
const contents = Array.isArray(map.sourcesContent) ? [...map.sourcesContent] : [];
|
|
574
|
+
let filled = 0;
|
|
575
|
+
map.sources.forEach((source, i) => {
|
|
576
|
+
if (typeof contents[i] === "string" || typeof source !== "string") return;
|
|
577
|
+
if (/node_modules|^\[externals\]|\(ignored\)|^webpack\/runtime/.test(source)) return;
|
|
578
|
+
for (const path of sourcePathCandidates(source, mapPath, typeof map.sourceRoot === "string" ? map.sourceRoot : "")) {
|
|
579
|
+
if (/[\\/]node_modules[\\/]/.test(path)) continue;
|
|
580
|
+
try {
|
|
581
|
+
const stat = (0, import_node_fs3.statSync)(path);
|
|
582
|
+
if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) continue;
|
|
583
|
+
contents[i] = (0, import_node_fs3.readFileSync)(path, "utf8");
|
|
584
|
+
filled++;
|
|
585
|
+
break;
|
|
586
|
+
} catch {
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
});
|
|
590
|
+
if (filled) {
|
|
591
|
+
while (contents.length < map.sources.length) contents.push(null);
|
|
592
|
+
map.sourcesContent = contents.map((c) => typeof c === "string" ? c : null);
|
|
593
|
+
}
|
|
594
|
+
return filled;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// src/sourcemaps.ts
|
|
598
|
+
var JS_FILE = /\.(?:js|mjs|cjs)$/;
|
|
599
|
+
function mapFor(file, code) {
|
|
600
|
+
const sibling = `${file}.map`;
|
|
601
|
+
if ((0, import_node_fs4.existsSync)(sibling)) return sibling;
|
|
602
|
+
const url = sourceMappingUrl(code ?? (0, import_node_fs4.readFileSync)(file, "utf8"));
|
|
603
|
+
if (!url || /^[a-z][a-z0-9+.-]*:/i.test(url)) return void 0;
|
|
604
|
+
let path;
|
|
605
|
+
try {
|
|
606
|
+
path = decodeURIComponent(url.split(/[?#]/)[0]);
|
|
607
|
+
} catch {
|
|
608
|
+
return void 0;
|
|
609
|
+
}
|
|
610
|
+
const full = (0, import_node_path4.isAbsolute)(path) ? path : (0, import_node_path4.resolve)((0, import_node_path4.dirname)(file), path);
|
|
611
|
+
return (0, import_node_fs4.existsSync)(full) ? full : void 0;
|
|
612
|
+
}
|
|
613
|
+
function findSourceFiles(dir, options = {}) {
|
|
614
|
+
const root = (0, import_node_path4.resolve)(dir);
|
|
615
|
+
const keep = pathFilter(options.include, options.exclude);
|
|
616
|
+
const candidates = options.files ? options.files.map((f) => (0, import_node_path4.resolve)(f)) : walk(root);
|
|
617
|
+
const out = [];
|
|
618
|
+
for (const file of candidates) {
|
|
619
|
+
if (!JS_FILE.test(file) || !(0, import_node_fs4.existsSync)(file)) continue;
|
|
620
|
+
const name = relativePath(root, file);
|
|
621
|
+
if (!keep(name)) continue;
|
|
622
|
+
const map = mapFor(file);
|
|
623
|
+
if (map) out.push({ file, map, name, mapName: relativePath(root, map) });
|
|
624
|
+
}
|
|
625
|
+
return out;
|
|
626
|
+
}
|
|
627
|
+
function injectDirectory(dir, options = {}) {
|
|
628
|
+
const logger = options.logger ?? consoleLogger();
|
|
629
|
+
const files = findSourceFiles(dir, options);
|
|
630
|
+
const out = [];
|
|
631
|
+
const noSourcesContent = [];
|
|
632
|
+
for (const source of files) {
|
|
633
|
+
const code = (0, import_node_fs4.readFileSync)(source.file, "utf8");
|
|
634
|
+
const injected = injectCode(code, { stripSourceMappingUrl: options.stripSourceMappingUrl });
|
|
635
|
+
let map;
|
|
636
|
+
try {
|
|
637
|
+
map = injectMap((0, import_node_fs4.readFileSync)(source.map, "utf8"), injected.debugId, source.map);
|
|
638
|
+
} catch (error) {
|
|
639
|
+
logger.warn(`Skipped ${source.name}: ${source.mapName} is not a readable source map (${error.message}).`);
|
|
640
|
+
continue;
|
|
641
|
+
}
|
|
642
|
+
if (!options.dryRun) {
|
|
643
|
+
if (injected.changed) (0, import_node_fs4.writeFileSync)(source.file, injected.code);
|
|
644
|
+
if (map.changed) (0, import_node_fs4.writeFileSync)(source.map, map.text);
|
|
645
|
+
}
|
|
646
|
+
if (!map.hasSourcesContent) noSourcesContent.push(source.mapName);
|
|
647
|
+
const changed = injected.changed || map.changed;
|
|
648
|
+
out.push({ ...source, debugId: injected.debugId, changed });
|
|
649
|
+
logger.info(`${changed ? options.dryRun ? "would inject" : "injected" : "already has"} ${injected.debugId} ${source.name}`);
|
|
650
|
+
}
|
|
651
|
+
if (noSourcesContent.length) {
|
|
652
|
+
logger.warn(
|
|
653
|
+
`${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 ? ", \u2026" : ""}`
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
if (out.length === 0) logger.warn(`No JavaScript files with source maps found in ${dir}.`);
|
|
657
|
+
return out;
|
|
658
|
+
}
|
|
659
|
+
async function uploadSourcemaps(dir, connection, options = {}) {
|
|
660
|
+
const logger = options.logger ?? consoleLogger();
|
|
661
|
+
const files = findSourceFiles(dir, options);
|
|
662
|
+
const result = { files: 0, artifacts: 0, bytes: 0, deleted: [], skipped: [] };
|
|
663
|
+
const work = [];
|
|
664
|
+
for (const source of files) {
|
|
665
|
+
const code = (0, import_node_fs4.readFileSync)(source.file);
|
|
666
|
+
const debugId = existingDebugId(code.toString("utf8"));
|
|
667
|
+
if (!debugId) {
|
|
668
|
+
result.skipped.push(source.name);
|
|
669
|
+
continue;
|
|
670
|
+
}
|
|
671
|
+
work.push({ source, debugId, code, map: (0, import_node_fs4.readFileSync)(source.map) });
|
|
672
|
+
}
|
|
673
|
+
if (result.skipped.length) {
|
|
674
|
+
logger.warn(`${result.skipped.length} file(s) have a source map but no debug ID \u2014 run \`zharp sourcemaps inject\` first: ${result.skipped.slice(0, 3).join(", ")}${result.skipped.length > 3 ? ", \u2026" : ""}`);
|
|
675
|
+
}
|
|
676
|
+
if (work.length === 0) {
|
|
677
|
+
logger.warn(`Nothing to upload in ${dir}.`);
|
|
678
|
+
return result;
|
|
679
|
+
}
|
|
680
|
+
const total = work.length;
|
|
681
|
+
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}` : ""}`);
|
|
682
|
+
let done = 0;
|
|
683
|
+
await eachLimit(work, options.concurrency ?? 4, async ({ source, debugId, code, map }) => {
|
|
684
|
+
const size = code.length + map.length;
|
|
685
|
+
if (!options.dryRun) {
|
|
686
|
+
if (!connection) throw new Error("No connection to upload to.");
|
|
687
|
+
const common = { debugId, release: options.release };
|
|
688
|
+
const opts = { fetch: options.fetch, retries: options.retries };
|
|
689
|
+
await uploadArtifact(connection, { ...common, kind: "minified-source", name: source.name, data: code }, opts);
|
|
690
|
+
await uploadArtifact(connection, { ...common, kind: "sourcemap", name: source.mapName, data: map }, opts);
|
|
691
|
+
}
|
|
692
|
+
done += 1;
|
|
693
|
+
result.files += 1;
|
|
694
|
+
result.artifacts += 2;
|
|
695
|
+
result.bytes += size;
|
|
696
|
+
logger.info(` [${done}/${total}] ${options.dryRun ? "would upload" : "uploaded"} ${source.name} + ${source.mapName} (${formatBytes(size)}) ${debugId}`);
|
|
697
|
+
});
|
|
698
|
+
if (options.deleteAfter && !options.dryRun) {
|
|
699
|
+
result.deleted = deleteSourcemaps(work.map((w) => w.source), { stripSourceMappingUrl: options.stripSourceMappingUrl });
|
|
700
|
+
logger.info(`Deleted ${result.deleted.length} source map(s) from the output.`);
|
|
701
|
+
}
|
|
702
|
+
logger.info(`${options.dryRun ? "Dry run: would have uploaded" : "Uploaded"} ${result.artifacts} artifact(s), ${formatBytes(result.bytes)}.`);
|
|
703
|
+
return result;
|
|
704
|
+
}
|
|
705
|
+
function deleteSourcemaps(files, options = {}) {
|
|
706
|
+
const deleted = [];
|
|
707
|
+
for (const source of files) {
|
|
708
|
+
if (options.stripSourceMappingUrl && (0, import_node_fs4.existsSync)(source.file)) {
|
|
709
|
+
const code = (0, import_node_fs4.readFileSync)(source.file, "utf8");
|
|
710
|
+
const stripped = withoutSourceMappingUrl(code);
|
|
711
|
+
if (stripped !== code) (0, import_node_fs4.writeFileSync)(source.file, stripped);
|
|
712
|
+
}
|
|
713
|
+
if ((0, import_node_fs4.existsSync)(source.map)) {
|
|
714
|
+
(0, import_node_fs4.unlinkSync)(source.map);
|
|
715
|
+
deleted.push(source.mapName);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
return deleted;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// src/version.ts
|
|
722
|
+
var VERSION = "0.2.0";
|
|
723
|
+
|
|
724
|
+
// src/init/index.ts
|
|
725
|
+
var import_node_child_process2 = require("child_process");
|
|
726
|
+
var import_node_fs7 = require("fs");
|
|
727
|
+
var import_promises = require("readline/promises");
|
|
728
|
+
var import_node_path7 = require("path");
|
|
729
|
+
|
|
730
|
+
// src/init/connect.ts
|
|
731
|
+
var import_node_child_process = require("child_process");
|
|
732
|
+
var import_node_os = require("os");
|
|
733
|
+
var OS_NAMES = { win32: "Windows", darwin: "macOS", linux: "Linux" };
|
|
734
|
+
function openBrowser(url) {
|
|
735
|
+
if (process.env.ZHARP_NO_BROWSER || process.env.CI || process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return;
|
|
736
|
+
try {
|
|
737
|
+
const command = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
|
|
738
|
+
const args = process.platform === "win32" ? ["/c", "start", '""', url.replace(/&/g, "^&")] : [url];
|
|
739
|
+
(0, import_node_child_process.spawn)(command, args, { stdio: "ignore", detached: true }).on("error", () => {
|
|
740
|
+
}).unref();
|
|
741
|
+
} catch {
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
var SetupFailed = class extends Error {
|
|
745
|
+
};
|
|
746
|
+
async function connect(api, project, hooks) {
|
|
747
|
+
const http = hooks.fetch ?? fetch;
|
|
748
|
+
const sleep2 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
749
|
+
const base = `${api.replace(/\/+$/, "")}/api/v1/cli-setup`;
|
|
750
|
+
const opened = await http(`${base}/sessions`, {
|
|
751
|
+
method: "POST",
|
|
752
|
+
headers: { "content-type": "application/json", "user-agent": `zharp-cli/${VERSION}` },
|
|
753
|
+
body: JSON.stringify({ name: project.name, framework: project.label, platform: project.platform, os: OS_NAMES[(0, import_node_os.platform)()] ?? `${(0, import_node_os.platform)()} ${(0, import_node_os.release)()}`, cliVersion: VERSION })
|
|
754
|
+
}).catch((error) => {
|
|
755
|
+
throw new SetupFailed(`Could not reach Zharp at ${api} (${error?.cause?.code ?? error?.message ?? error}).`);
|
|
756
|
+
});
|
|
757
|
+
if (!opened.ok) throw new SetupFailed(`Zharp refused to start a setup (${opened.status}).`);
|
|
758
|
+
const session = (await opened.json()).data;
|
|
759
|
+
hooks.showCode(session.userCode, session.verificationUrl);
|
|
760
|
+
(hooks.openBrowser ?? openBrowser)(session.verificationUrl);
|
|
761
|
+
const until = Date.now() + session.expiresIn * 1e3;
|
|
762
|
+
while (Date.now() < until) {
|
|
763
|
+
await sleep2(Math.max(1, session.interval) * 1e3);
|
|
764
|
+
hooks.waiting?.();
|
|
765
|
+
const res = await http(`${base}/collect`, {
|
|
766
|
+
method: "POST",
|
|
767
|
+
headers: { "content-type": "application/json", "user-agent": `zharp-cli/${VERSION}` },
|
|
768
|
+
body: JSON.stringify({ deviceToken: session.deviceToken })
|
|
769
|
+
}).catch(() => null);
|
|
770
|
+
if (!res) continue;
|
|
771
|
+
const body = await res.json().catch(() => ({}));
|
|
772
|
+
if (res.status === 200 && body?.data?.status === "approved") return body.data;
|
|
773
|
+
if (res.status === 200) continue;
|
|
774
|
+
throw new SetupFailed(body?.message ?? `The setup stopped (${res.status}).`);
|
|
775
|
+
}
|
|
776
|
+
throw new SetupFailed("The code expired before it was approved. Run it again.");
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
// src/init/detect.ts
|
|
780
|
+
var import_node_fs5 = require("fs");
|
|
781
|
+
var import_node_path5 = require("path");
|
|
782
|
+
var read = (path) => {
|
|
783
|
+
try {
|
|
784
|
+
return (0, import_node_fs5.readFileSync)(path, "utf8");
|
|
785
|
+
} catch {
|
|
786
|
+
return null;
|
|
787
|
+
}
|
|
788
|
+
};
|
|
789
|
+
function majorOf(range) {
|
|
790
|
+
const m = /(\d+)/.exec(range ?? "");
|
|
791
|
+
return m ? ` ${m[1]}` : "";
|
|
792
|
+
}
|
|
793
|
+
function packageManagerOf(dir) {
|
|
794
|
+
if ((0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "pnpm-lock.yaml"))) return "pnpm";
|
|
795
|
+
if ((0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "yarn.lock"))) return "yarn";
|
|
796
|
+
if ((0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "bun.lockb")) || (0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "bun.lock"))) return "bun";
|
|
797
|
+
return "npm";
|
|
798
|
+
}
|
|
799
|
+
function detect(dir) {
|
|
800
|
+
const pkgText = read((0, import_node_path5.join)(dir, "package.json"));
|
|
801
|
+
const pkg = pkgText ? (() => {
|
|
802
|
+
try {
|
|
803
|
+
return JSON.parse(pkgText);
|
|
804
|
+
} catch {
|
|
805
|
+
return null;
|
|
806
|
+
}
|
|
807
|
+
})() : null;
|
|
808
|
+
const deps = { ...pkg?.dependencies ?? {}, ...pkg?.devDependencies ?? {} };
|
|
809
|
+
const name = typeof pkg?.name === "string" && pkg.name.replace(/^@[^/]+\//, "") || (0, import_node_path5.basename)(dir);
|
|
810
|
+
const base = { dir, name, packageManager: packageManagerOf(dir), typescript: !!deps.typescript || (0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "tsconfig.json")), packageJson: pkg ?? void 0 };
|
|
811
|
+
if (deps.next) {
|
|
812
|
+
const appDir = (0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "src", "app")) ? "src/app" : (0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "app")) ? "app" : void 0;
|
|
813
|
+
return { ...base, framework: "nextjs", label: `Next.js${majorOf(deps.next)}`, platform: "browser", appDir };
|
|
814
|
+
}
|
|
815
|
+
if (deps["@nestjs/core"]) return { ...base, framework: "nestjs", label: `NestJS${majorOf(deps["@nestjs/core"])}`, platform: "node" };
|
|
816
|
+
if (deps.vite && deps.react) return { ...base, framework: "vite-react", label: "React (Vite)", platform: "browser" };
|
|
817
|
+
if (deps.express) return { ...base, framework: "express", label: `Express${majorOf(deps.express)}`, platform: "node" };
|
|
818
|
+
const py = [read((0, import_node_path5.join)(dir, "requirements.txt")), read((0, import_node_path5.join)(dir, "pyproject.toml")), read((0, import_node_path5.join)(dir, "Pipfile"))].filter(Boolean).join("\n").toLowerCase();
|
|
819
|
+
if (py) {
|
|
820
|
+
const pyName = (0, import_node_path5.basename)(dir);
|
|
821
|
+
if (/\bdjango\b/.test(py)) return { ...base, name: pyName, framework: "django", label: "Django", platform: "python" };
|
|
822
|
+
if (/\bfastapi\b/.test(py)) return { ...base, name: pyName, framework: "fastapi", label: "FastAPI", platform: "python" };
|
|
823
|
+
if (/\bflask\b/.test(py)) return { ...base, name: pyName, framework: "flask", label: "Flask", platform: "python" };
|
|
824
|
+
}
|
|
825
|
+
const composer = read((0, import_node_path5.join)(dir, "composer.json"));
|
|
826
|
+
if (composer && /laravel\/framework/.test(composer)) return { ...base, name: (0, import_node_path5.basename)(dir), framework: "laravel", label: "Laravel", platform: "php" };
|
|
827
|
+
if ((0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "go.mod"))) return { ...base, name: (0, import_node_path5.basename)(dir), framework: "go", label: "Go", platform: "go" };
|
|
828
|
+
if (pkg) return { ...base, framework: "node", label: "Node.js", platform: "node" };
|
|
829
|
+
return { ...base, framework: "unknown", label: "an unknown project", platform: "otel" };
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// src/init/recipes.ts
|
|
833
|
+
var import_node_fs6 = require("fs");
|
|
834
|
+
var import_node_path6 = require("path");
|
|
835
|
+
var DEFAULT_API = "https://api.zharp.io";
|
|
836
|
+
var read2 = (dir, path) => {
|
|
837
|
+
try {
|
|
838
|
+
return (0, import_node_fs6.readFileSync)((0, import_node_path6.join)(dir, path), "utf8");
|
|
839
|
+
} catch {
|
|
840
|
+
return null;
|
|
841
|
+
}
|
|
842
|
+
};
|
|
843
|
+
var first = (dir, paths) => paths.find((p) => (0, import_node_fs6.existsSync)((0, import_node_path6.join)(dir, p))) ?? null;
|
|
844
|
+
var mentionsZharp = (text) => !!text && /@zharp\//.test(text);
|
|
845
|
+
function styled(text, line) {
|
|
846
|
+
const imports = [...text.matchAll(/^import .*$/gm)].map((m) => m[0].trimEnd());
|
|
847
|
+
const bare = imports.length > 0 && imports.every((l) => !l.endsWith(";"));
|
|
848
|
+
const double = imports.filter((l) => /from "/.test(l)).length > imports.filter((l) => /from '/.test(l)).length;
|
|
849
|
+
const quoted = double ? line.replace(/'([^'"]*)'/g, '"$1"') : line;
|
|
850
|
+
return bare ? quoted.replace(/;$/, "") : quoted;
|
|
851
|
+
}
|
|
852
|
+
function endpointOf(api) {
|
|
853
|
+
const clean = api.replace(/\/+$/, "");
|
|
854
|
+
return clean === DEFAULT_API ? null : `${clean}/api/v1/otlp`;
|
|
855
|
+
}
|
|
856
|
+
function wrapNextConfig(text, appId, esm) {
|
|
857
|
+
if (/withZharp/.test(text)) return null;
|
|
858
|
+
const exportDefault = /export\s+default\s+([\s\S]+?);?\s*$/.exec(text);
|
|
859
|
+
if (esm && exportDefault) {
|
|
860
|
+
const value = exportDefault[1].trim().replace(/;$/, "");
|
|
861
|
+
const head = text.slice(0, exportDefault.index);
|
|
862
|
+
return `import { withZharp } from '@zharp/nextjs';
|
|
863
|
+
${head}export default withZharp(${value}, { app: ${appId} });
|
|
864
|
+
`;
|
|
865
|
+
}
|
|
866
|
+
const moduleExports = /module\.exports\s*=\s*([\s\S]+?);?\s*$/.exec(text);
|
|
867
|
+
if (!esm && moduleExports) {
|
|
868
|
+
const value = moduleExports[1].trim().replace(/;$/, "");
|
|
869
|
+
const head = text.slice(0, moduleExports.index);
|
|
870
|
+
return `const { withZharp } = require('@zharp/nextjs');
|
|
871
|
+
${head}module.exports = withZharp(${value}, { app: ${appId} });
|
|
872
|
+
`;
|
|
873
|
+
}
|
|
874
|
+
return null;
|
|
875
|
+
}
|
|
876
|
+
function addToLayout(text, importPath) {
|
|
877
|
+
if (/ZharpClient/.test(text)) return null;
|
|
878
|
+
const body = /<body\b[^>]*>/.exec(text);
|
|
879
|
+
if (!body) return null;
|
|
880
|
+
const at = body.index + body[0].length;
|
|
881
|
+
const bodyIndent = /[ \t]*$/.exec(text.slice(0, body.index))[0];
|
|
882
|
+
const inner = `${bodyIndent} `;
|
|
883
|
+
const rest = text.slice(at);
|
|
884
|
+
const after = /^\s*\n/.test(rest) ? rest : `
|
|
885
|
+
${inner}${rest.replace(/^[ \t]+/, "")}`;
|
|
886
|
+
const withComponent = `${text.slice(0, at)}
|
|
887
|
+
${inner}<ZharpClient />${after}`;
|
|
888
|
+
const imports = [...withComponent.matchAll(/^import .*$/gm)];
|
|
889
|
+
const line = styled(text, `import { ZharpClient } from '${importPath}';`);
|
|
890
|
+
if (!imports.length) return `${line}
|
|
891
|
+
${withComponent}`;
|
|
892
|
+
const last = imports[imports.length - 1];
|
|
893
|
+
const end = last.index + last[0].length;
|
|
894
|
+
return `${withComponent.slice(0, end)}
|
|
895
|
+
${line}${withComponent.slice(end)}`;
|
|
896
|
+
}
|
|
897
|
+
function nextjs(project, c, api) {
|
|
898
|
+
const dir = project.dir;
|
|
899
|
+
const ts = project.typescript;
|
|
900
|
+
const plan = { install: ["@zharp/browser", "@zharp/node"], devInstall: ["@zharp/nextjs"], changes: [], manual: [], notes: [], env: { file: ".env.local", vars: {} } };
|
|
901
|
+
const endpoint = endpointOf(api);
|
|
902
|
+
const instrumentationPath = `${project.appDir?.startsWith("src/") ? "src/" : ""}instrumentation.${ts ? "ts" : "js"}`;
|
|
903
|
+
const instrumentation = [
|
|
904
|
+
"export async function register() {",
|
|
905
|
+
" if (process.env.NEXT_RUNTIME === 'nodejs') {",
|
|
906
|
+
" const { Zharp } = await import('@zharp/node');",
|
|
907
|
+
` Zharp.init({ service: '${c.application.serviceName}' });`,
|
|
908
|
+
" }",
|
|
909
|
+
"}",
|
|
910
|
+
"",
|
|
911
|
+
"// Errors Next.js answers with an error page: reported with their route.",
|
|
912
|
+
`export async function onRequestError(...args${ts ? ": Parameters<typeof import('@zharp/node').Zharp.onRequestError>" : ""}) {`,
|
|
913
|
+
" if (process.env.NEXT_RUNTIME === 'nodejs') {",
|
|
914
|
+
" const { Zharp } = await import('@zharp/node');",
|
|
915
|
+
" Zharp.onRequestError(...args);",
|
|
916
|
+
" }",
|
|
917
|
+
"}",
|
|
918
|
+
""
|
|
919
|
+
].join("\n");
|
|
920
|
+
const existingInstrumentation = first(dir, ["instrumentation.ts", "instrumentation.js", "src/instrumentation.ts", "src/instrumentation.js"]);
|
|
921
|
+
if (!existingInstrumentation) plan.changes.push({ path: instrumentationPath, kind: "create", content: instrumentation, note: "starts Zharp on the server" });
|
|
922
|
+
else if (!mentionsZharp(read2(dir, existingInstrumentation))) plan.manual.push({ path: existingInstrumentation, why: "it already exists \u2014 add Zharp to it", snippet: instrumentation });
|
|
923
|
+
const configPath = first(dir, ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.cjs"]);
|
|
924
|
+
if (!configPath) {
|
|
925
|
+
plan.changes.push({ path: ts ? "next.config.ts" : "next.config.mjs", kind: "create", content: `import { withZharp } from '@zharp/nextjs';
|
|
926
|
+
|
|
927
|
+
export default withZharp({}, { app: ${c.application.id} });
|
|
928
|
+
`, note: "source maps uploaded on build" });
|
|
929
|
+
} else {
|
|
930
|
+
const text = read2(dir, configPath) ?? "";
|
|
931
|
+
const esm = /\.(ts|mjs)$/.test(configPath) || /^\s*(import|export)\s/m.test(text);
|
|
932
|
+
const wrapped = mentionsZharp(text) ? null : wrapNextConfig(text, c.application.id, esm);
|
|
933
|
+
if (wrapped) plan.changes.push({ path: configPath, kind: "edit", content: wrapped, note: "wrapped with withZharp" });
|
|
934
|
+
else if (!mentionsZharp(text)) plan.manual.push({ path: configPath, why: "its export isn't a plain value \u2014 wrap it yourself", snippet: `import { withZharp } from '@zharp/nextjs';
|
|
935
|
+
|
|
936
|
+
export default withZharp(nextConfig, { app: ${c.application.id} });` });
|
|
937
|
+
}
|
|
938
|
+
if (project.appDir) {
|
|
939
|
+
const ext = ts ? "tsx" : "jsx";
|
|
940
|
+
const clientPath = `${project.appDir}/zharp-client.${ext}`;
|
|
941
|
+
const client = [
|
|
942
|
+
"'use client';",
|
|
943
|
+
"import { Zharp } from '@zharp/browser';",
|
|
944
|
+
"",
|
|
945
|
+
"if (typeof window !== 'undefined' && !Zharp.isActive) {",
|
|
946
|
+
` Zharp.init({ key: process.env.NEXT_PUBLIC_ZHARP_KEY${ts ? "!" : ""}${endpoint ? ", endpoint: process.env.NEXT_PUBLIC_ZHARP_ENDPOINT" : ""}, service: '${c.application.serviceName}' });`,
|
|
947
|
+
"}",
|
|
948
|
+
"",
|
|
949
|
+
"/** Starts Zharp in the browser; rendered once, in the root layout. */",
|
|
950
|
+
"export function ZharpClient() {",
|
|
951
|
+
" return null;",
|
|
952
|
+
"}",
|
|
953
|
+
""
|
|
954
|
+
].join("\n");
|
|
955
|
+
if (!(0, import_node_fs6.existsSync)((0, import_node_path6.join)(dir, clientPath))) plan.changes.push({ path: clientPath, kind: "create", content: client, note: `starts Zharp in the browser` });
|
|
956
|
+
const layoutPath = first(dir, [`${project.appDir}/layout.tsx`, `${project.appDir}/layout.jsx`, `${project.appDir}/layout.js`]);
|
|
957
|
+
const layout = layoutPath ? read2(dir, layoutPath) : null;
|
|
958
|
+
const edited = layout ? addToLayout(layout, "./zharp-client") : null;
|
|
959
|
+
if (layoutPath && edited) plan.changes.push({ path: layoutPath, kind: "edit", content: edited, note: "renders <ZharpClient />" });
|
|
960
|
+
else if (layoutPath && !/ZharpClient/.test(layout ?? "")) plan.manual.push({ path: layoutPath, why: "add the component inside <body>", snippet: "import { ZharpClient } from './zharp-client';\n\u2026\n<body>\n <ZharpClient />" });
|
|
961
|
+
} else {
|
|
962
|
+
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 });" });
|
|
963
|
+
}
|
|
964
|
+
plan.env.vars = {
|
|
965
|
+
NEXT_PUBLIC_ZHARP_KEY: c.application.ingestKey,
|
|
966
|
+
ZHARP_KEY: c.application.ingestKey,
|
|
967
|
+
ZHARP_AUTH_TOKEN: c.uploadKey,
|
|
968
|
+
...endpoint ? { NEXT_PUBLIC_ZHARP_ENDPOINT: endpoint, ZHARP_ENDPOINT: endpoint, ZHARP_URL: api.replace(/\/+$/, "") } : {}
|
|
969
|
+
};
|
|
970
|
+
plan.notes.push("Add ZHARP_AUTH_TOKEN (and the keys) to your CI and hosting, so production builds upload their source maps.");
|
|
971
|
+
return plan;
|
|
972
|
+
}
|
|
973
|
+
function addVitePlugin(text, appId) {
|
|
974
|
+
if (/@zharp\/vite-plugin/.test(text)) return null;
|
|
975
|
+
const plugins = /plugins\s*:\s*\[/.exec(text);
|
|
976
|
+
if (!plugins) return null;
|
|
977
|
+
let depth = 0;
|
|
978
|
+
let close = -1;
|
|
979
|
+
for (let i = plugins.index + plugins[0].length; i < text.length; i++) {
|
|
980
|
+
const ch = text[i];
|
|
981
|
+
if (ch === "[" || ch === "(" || ch === "{") depth++;
|
|
982
|
+
else if (ch === "]" || ch === ")" || ch === "}") {
|
|
983
|
+
if (depth === 0 && ch === "]") {
|
|
984
|
+
close = i;
|
|
985
|
+
break;
|
|
986
|
+
}
|
|
987
|
+
depth--;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
if (close < 0) return null;
|
|
991
|
+
const inside = text.slice(plugins.index + plugins[0].length, close).trimEnd();
|
|
992
|
+
const sep2 = inside.length === 0 ? "" : inside.endsWith(",") ? " " : ", ";
|
|
993
|
+
const withPlugin = `${text.slice(0, plugins.index + plugins[0].length)}${inside}${sep2}zharp({ app: ${appId} })${text.slice(close)}`;
|
|
994
|
+
const imports = [...withPlugin.matchAll(/^import .*$/gm)];
|
|
995
|
+
const line = styled(text, "import { zharp } from '@zharp/vite-plugin';");
|
|
996
|
+
if (!imports.length) return `${line}
|
|
997
|
+
${withPlugin}`;
|
|
998
|
+
const last = imports[imports.length - 1];
|
|
999
|
+
const end = last.index + last[0].length;
|
|
1000
|
+
return `${withPlugin.slice(0, end)}
|
|
1001
|
+
${line}${withPlugin.slice(end)}`;
|
|
1002
|
+
}
|
|
1003
|
+
function addToViteMain(text, serviceName, withEndpoint) {
|
|
1004
|
+
if (/@zharp\/browser/.test(text)) return null;
|
|
1005
|
+
const call = /createRoot\(([^()]*(?:\([^()]*\)[^()]*)*)\)/.exec(text);
|
|
1006
|
+
let next = text;
|
|
1007
|
+
if (call && !call[1].includes(",")) {
|
|
1008
|
+
next = `${text.slice(0, call.index)}createRoot(${call[1]}, {
|
|
1009
|
+
onUncaughtError: Zharp.reactErrorHandler(),
|
|
1010
|
+
onCaughtError: Zharp.reactErrorHandler(),
|
|
1011
|
+
})${text.slice(call.index + call[0].length)}`;
|
|
1012
|
+
}
|
|
1013
|
+
const imports = [...next.matchAll(/^import .*$/gm)];
|
|
1014
|
+
const start = styled(text, `Zharp.init({ key: import.meta.env.VITE_ZHARP_KEY${withEndpoint ? ", endpoint: import.meta.env.VITE_ZHARP_ENDPOINT" : ""}, service: '${serviceName}' });`);
|
|
1015
|
+
const init = `
|
|
1016
|
+
${start}
|
|
1017
|
+
`;
|
|
1018
|
+
const line = styled(text, "import { Zharp } from '@zharp/browser';");
|
|
1019
|
+
if (!imports.length) return `${line}
|
|
1020
|
+
${init}
|
|
1021
|
+
${next}`;
|
|
1022
|
+
const last = imports[imports.length - 1];
|
|
1023
|
+
const end = last.index + last[0].length;
|
|
1024
|
+
return `${next.slice(0, end)}
|
|
1025
|
+
${line}
|
|
1026
|
+
${init}${next.slice(end).replace(/^\n+/, "\n")}`;
|
|
1027
|
+
}
|
|
1028
|
+
function viteReact(project, c, api) {
|
|
1029
|
+
const dir = project.dir;
|
|
1030
|
+
const endpoint = endpointOf(api);
|
|
1031
|
+
const plan = { install: ["@zharp/browser"], devInstall: ["@zharp/vite-plugin"], changes: [], manual: [], notes: [], env: { file: ".env.local", vars: {} } };
|
|
1032
|
+
const configPath = first(dir, ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"]);
|
|
1033
|
+
const config = configPath ? read2(dir, configPath) : null;
|
|
1034
|
+
const editedConfig = config ? addVitePlugin(config, c.application.id) : null;
|
|
1035
|
+
if (configPath && editedConfig) plan.changes.push({ path: configPath, kind: "edit", content: editedConfig, note: "source maps uploaded on build" });
|
|
1036
|
+
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';
|
|
1037
|
+
\u2026
|
|
1038
|
+
plugins: [react(), zharp({ app: ${c.application.id} })]` });
|
|
1039
|
+
const mainPath = first(dir, ["src/main.tsx", "src/main.jsx", "src/main.ts", "src/main.js", "src/index.tsx", "src/index.jsx"]);
|
|
1040
|
+
const main2 = mainPath ? read2(dir, mainPath) : null;
|
|
1041
|
+
const editedMain = main2 ? addToViteMain(main2, c.application.serviceName, !!endpoint) : null;
|
|
1042
|
+
if (mainPath && editedMain) plan.changes.push({ path: mainPath, kind: "edit", content: editedMain, note: "starts Zharp; React errors with their component stack" });
|
|
1043
|
+
else if (!mentionsZharp(main2)) 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() })" });
|
|
1044
|
+
plan.env.vars = {
|
|
1045
|
+
VITE_ZHARP_KEY: c.application.ingestKey,
|
|
1046
|
+
ZHARP_AUTH_TOKEN: c.uploadKey,
|
|
1047
|
+
...endpoint ? { VITE_ZHARP_ENDPOINT: endpoint, ZHARP_URL: api.replace(/\/+$/, "") } : {}
|
|
1048
|
+
};
|
|
1049
|
+
plan.notes.push("Add ZHARP_AUTH_TOKEN and VITE_ZHARP_KEY to your CI, so production builds upload their source maps.");
|
|
1050
|
+
return plan;
|
|
1051
|
+
}
|
|
1052
|
+
function nestjs(project, c, api) {
|
|
1053
|
+
const dir = project.dir;
|
|
1054
|
+
const endpoint = endpointOf(api);
|
|
1055
|
+
const plan = { install: ["@zharp/node"], devInstall: [], changes: [], manual: [], notes: [], env: { file: ".env", vars: {} } };
|
|
1056
|
+
const ext = project.typescript ? "ts" : "js";
|
|
1057
|
+
const instrumentPath = `src/instrument.${ext}`;
|
|
1058
|
+
const instrument = [
|
|
1059
|
+
"import { Zharp } from '@zharp/node';",
|
|
1060
|
+
"",
|
|
1061
|
+
"// Before anything else: http, the database drivers and NestJS are instrumented as they load.",
|
|
1062
|
+
"try { process.loadEnvFile?.('.env'); } catch { /* no .env: the environment has the keys */ }",
|
|
1063
|
+
`Zharp.init({ service: '${c.application.serviceName}' });`,
|
|
1064
|
+
""
|
|
1065
|
+
].join("\n");
|
|
1066
|
+
if (!(0, import_node_fs6.existsSync)((0, import_node_path6.join)(dir, instrumentPath))) plan.changes.push({ path: instrumentPath, kind: "create", content: instrument, note: "starts Zharp before the app loads" });
|
|
1067
|
+
const mainPath = first(dir, [`src/main.${ext}`]);
|
|
1068
|
+
const main2 = mainPath ? read2(dir, mainPath) : null;
|
|
1069
|
+
const esm = project.packageJson?.type === "module" || /from '\.{1,2}\/[^']+\.js'/.test(main2 ?? "");
|
|
1070
|
+
if (esm) {
|
|
1071
|
+
const pkgText = read2(dir, "package.json");
|
|
1072
|
+
const scripts = { ...project.packageJson?.scripts ?? {} };
|
|
1073
|
+
const preload = "--import ./dist/instrument.js";
|
|
1074
|
+
let changed = false;
|
|
1075
|
+
for (const [name, command] of Object.entries(scripts)) {
|
|
1076
|
+
if (command.includes(preload)) continue;
|
|
1077
|
+
if (/^nest start\b/.test(command) && !/--exec\b/.test(command)) {
|
|
1078
|
+
scripts[name] = `${command} --exec "node ${preload}"`;
|
|
1079
|
+
changed = true;
|
|
1080
|
+
} else if (/^node (?:--[^\s]+ )*dist\/main(?:\.js)?\s*$/.test(command)) {
|
|
1081
|
+
scripts[name] = command.replace(/^node /, `node ${preload} `);
|
|
1082
|
+
changed = true;
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
if (changed && pkgText) {
|
|
1086
|
+
let text = pkgText;
|
|
1087
|
+
for (const [name, command] of Object.entries(scripts)) {
|
|
1088
|
+
const before = (project.packageJson?.scripts ?? {})[name];
|
|
1089
|
+
if (before === command) continue;
|
|
1090
|
+
const line = new RegExp(`("${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"\\s*:\\s*)${JSON.stringify(before).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
|
|
1091
|
+
text = text.replace(line, (_, key) => `${key}${JSON.stringify(command)}`);
|
|
1092
|
+
}
|
|
1093
|
+
plan.changes.push({ path: "package.json", kind: "edit", content: text, note: "start scripts preload Zharp (--import)" });
|
|
1094
|
+
}
|
|
1095
|
+
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` });
|
|
1096
|
+
} else if (mainPath && main2 && !main2.includes("./instrument")) {
|
|
1097
|
+
plan.changes.push({ path: mainPath, kind: "edit", content: `${styled(main2, "import './instrument';")}
|
|
1098
|
+
${main2}`, note: "loads it first" });
|
|
1099
|
+
} else if (!mainPath) {
|
|
1100
|
+
plan.manual.push({ path: "src/main.ts", why: "import it first in your entry file", snippet: "import './instrument';" });
|
|
1101
|
+
}
|
|
1102
|
+
plan.env.vars = { ZHARP_KEY: c.application.ingestKey, ...endpoint ? { ZHARP_ENDPOINT: endpoint } : {} };
|
|
1103
|
+
plan.notes.push("Set ZHARP_KEY where the app runs in production.");
|
|
1104
|
+
return plan;
|
|
1105
|
+
}
|
|
1106
|
+
function planFor(project, c, api) {
|
|
1107
|
+
switch (project.framework) {
|
|
1108
|
+
case "nextjs":
|
|
1109
|
+
return nextjs(project, c, api);
|
|
1110
|
+
case "vite-react":
|
|
1111
|
+
return viteReact(project, c, api);
|
|
1112
|
+
case "nestjs":
|
|
1113
|
+
return nestjs(project, c, api);
|
|
1114
|
+
default:
|
|
1115
|
+
return null;
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
var GUIDES = {
|
|
1119
|
+
express: "https://zharp.io/docs/sdks/node",
|
|
1120
|
+
node: "https://zharp.io/docs/sdks/node",
|
|
1121
|
+
django: "https://zharp.io/docs/sdks/python",
|
|
1122
|
+
fastapi: "https://zharp.io/docs/sdks/python",
|
|
1123
|
+
flask: "https://zharp.io/docs/sdks/python",
|
|
1124
|
+
laravel: "https://zharp.io/docs/sdks/php",
|
|
1125
|
+
go: "https://zharp.io/docs/sdks/go"
|
|
1126
|
+
};
|
|
1127
|
+
|
|
1128
|
+
// src/init/index.ts
|
|
1129
|
+
var green = (s) => `\x1B[32m${s}\x1B[39m`;
|
|
1130
|
+
var dim = (s) => `\x1B[2m${s}\x1B[22m`;
|
|
1131
|
+
var bold = (s) => `\x1B[1m${s}\x1B[22m`;
|
|
1132
|
+
var yellow = (s) => `\x1B[33m${s}\x1B[39m`;
|
|
1133
|
+
var bar = dim("\u2502");
|
|
1134
|
+
function say(line = "") {
|
|
1135
|
+
process.stdout.write(`${line}
|
|
1136
|
+
`);
|
|
1137
|
+
}
|
|
1138
|
+
function mergeEnv(existing, vars) {
|
|
1139
|
+
const lines = existing ? existing.replace(/\s+$/, "").split(/\r?\n/) : [];
|
|
1140
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1141
|
+
const out = lines.map((line) => {
|
|
1142
|
+
const name = /^\s*(?:export\s+)?([A-Z0-9_]+)\s*=/.exec(line)?.[1];
|
|
1143
|
+
if (name && name in vars) {
|
|
1144
|
+
seen.add(name);
|
|
1145
|
+
return `${name}=${vars[name]}`;
|
|
1146
|
+
}
|
|
1147
|
+
return line;
|
|
1148
|
+
});
|
|
1149
|
+
const added = Object.entries(vars).filter(([k]) => !seen.has(k));
|
|
1150
|
+
if (added.length) {
|
|
1151
|
+
if (out.length) out.push("");
|
|
1152
|
+
out.push("# Zharp (npx zharp init)");
|
|
1153
|
+
for (const [k, v] of added) out.push(`${k}=${v}`);
|
|
1154
|
+
}
|
|
1155
|
+
return `${out.join("\n")}
|
|
1156
|
+
`;
|
|
1157
|
+
}
|
|
1158
|
+
function ignoredByGit(gitignore, file) {
|
|
1159
|
+
return gitignore.split(/\r?\n/).map((l) => l.trim()).some((l) => l === file || l === `/${file}` || l === ".env*" || l === ".env*.local" && file.endsWith(".local") || l === "*.local" && file.endsWith(".local") || l === ".env.*" && file !== ".env");
|
|
1160
|
+
}
|
|
1161
|
+
function installCommand(project, packages, dev, tarballs) {
|
|
1162
|
+
const specs = tarballs ? packages.map((p) => (0, import_node_path7.join)(tarballs, `${p.replace("@", "").replace("/", "-")}.tgz`)) : packages;
|
|
1163
|
+
switch (project.packageManager) {
|
|
1164
|
+
case "pnpm":
|
|
1165
|
+
return ["pnpm", ["add", ...dev ? ["-D"] : [], ...specs]];
|
|
1166
|
+
case "yarn":
|
|
1167
|
+
return ["yarn", ["add", ...dev ? ["-D"] : [], ...specs]];
|
|
1168
|
+
case "bun":
|
|
1169
|
+
return ["bun", ["add", ...dev ? ["-d"] : [], ...specs]];
|
|
1170
|
+
default:
|
|
1171
|
+
return ["npm", ["install", ...dev ? ["--save-dev"] : [], ...specs]];
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
async function ask(question) {
|
|
1175
|
+
const rl = (0, import_promises.createInterface)({ input: process.stdin, output: process.stdout });
|
|
1176
|
+
try {
|
|
1177
|
+
return (await rl.question(question)).trim().toLowerCase();
|
|
1178
|
+
} finally {
|
|
1179
|
+
rl.close();
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
async function sendTestError(api, c) {
|
|
1183
|
+
const now = `${Date.now()}000000`;
|
|
1184
|
+
const attr = (key, value) => ({ key, value: { stringValue: value } });
|
|
1185
|
+
const body = {
|
|
1186
|
+
resourceLogs: [{
|
|
1187
|
+
resource: { attributes: [attr("service.name", c.application.serviceName), attr("telemetry.sdk.name", "zharp-cli")] },
|
|
1188
|
+
scopeLogs: [{
|
|
1189
|
+
logRecords: [{
|
|
1190
|
+
timeUnixNano: now,
|
|
1191
|
+
severityNumber: 17,
|
|
1192
|
+
severityText: "ERROR",
|
|
1193
|
+
body: { stringValue: "ZharpSetupTest: Zharp is connected \u2014 this is the test error npx zharp init sent" },
|
|
1194
|
+
attributes: [
|
|
1195
|
+
attr("exception.type", "ZharpSetupTest"),
|
|
1196
|
+
attr("exception.message", "Zharp is connected \u2014 this is the test error npx zharp init sent"),
|
|
1197
|
+
attr("exception.stacktrace", "ZharpSetupTest: Zharp is connected \u2014 this is the test error npx zharp init sent\n at zharp init"),
|
|
1198
|
+
attr("zharp.handled", "true")
|
|
1199
|
+
]
|
|
1200
|
+
}]
|
|
1201
|
+
}]
|
|
1202
|
+
}]
|
|
1203
|
+
};
|
|
1204
|
+
try {
|
|
1205
|
+
const res = await fetch(`${api.replace(/\/+$/, "")}/api/v1/otlp/v1/logs`, {
|
|
1206
|
+
method: "POST",
|
|
1207
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${c.application.ingestKey}` },
|
|
1208
|
+
body: JSON.stringify(body)
|
|
1209
|
+
});
|
|
1210
|
+
return res.ok;
|
|
1211
|
+
} catch {
|
|
1212
|
+
return false;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
function showPlan(plan, c) {
|
|
1216
|
+
say(`${green("\u25C6")} ${bold("These changes will be made:")}`);
|
|
1217
|
+
const deps = [...plan.install, ...plan.devInstall];
|
|
1218
|
+
if (deps.length) say(`${bar} ${green("+")} install ${deps.join(" ")}`);
|
|
1219
|
+
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)}`);
|
|
1220
|
+
say(`${bar} ${green("+")} ${bold(plan.env.file)} ${dim(Object.keys(plan.env.vars).join(", "))}`);
|
|
1221
|
+
for (const m of plan.manual) say(`${bar} ${yellow("!")} ${m.path}: ${dim(`left as it is \u2014 ${m.why}`)}`);
|
|
1222
|
+
void c;
|
|
1223
|
+
}
|
|
1224
|
+
async function runInit(options) {
|
|
1225
|
+
const dir = (0, import_node_path7.resolve)(options.dir ?? process.cwd());
|
|
1226
|
+
const api = (options.url ?? process.env.ZHARP_URL ?? DEFAULT_API).replace(/\/+$/, "");
|
|
1227
|
+
const project = detect(dir);
|
|
1228
|
+
say();
|
|
1229
|
+
say(`${green("\u25C6")} ${bold("Zharp setup")}`);
|
|
1230
|
+
say(`${bar} Found ${bold(project.label)} in ${dim(dir)}`);
|
|
1231
|
+
say(bar);
|
|
1232
|
+
let connected;
|
|
1233
|
+
try {
|
|
1234
|
+
connected = await connect(api, project, {
|
|
1235
|
+
showCode(code, url) {
|
|
1236
|
+
say(`${bar} Open ${url} and check this code:`);
|
|
1237
|
+
say(bar);
|
|
1238
|
+
say(`${bar} ${bold(code)}`);
|
|
1239
|
+
say(bar);
|
|
1240
|
+
say(`${bar} ${dim("Waiting for you to approve it in the browser\u2026")}`);
|
|
1241
|
+
}
|
|
1242
|
+
});
|
|
1243
|
+
} catch (error) {
|
|
1244
|
+
say(`${yellow("\u25A0")} ${error instanceof SetupFailed ? error.message : String(error)}`);
|
|
1245
|
+
return 1;
|
|
1246
|
+
}
|
|
1247
|
+
say(`${green("\u25C7")} Connected to ${bold(`${connected.workspace.name} / ${connected.application.name}`)}`);
|
|
1248
|
+
say(bar);
|
|
1249
|
+
const plan = planFor(project, connected, api);
|
|
1250
|
+
if (!plan) {
|
|
1251
|
+
say(`${green("\u25C6")} ${bold(`${project.label}: add the SDK with these keys`)}`);
|
|
1252
|
+
say(`${bar} ZHARP_KEY=${connected.application.ingestKey}`);
|
|
1253
|
+
say(`${bar} ${dim("Upload key (source maps): ZHARP_AUTH_TOKEN=")}${connected.uploadKey}`);
|
|
1254
|
+
const guide = GUIDES[project.framework];
|
|
1255
|
+
say(`${bar} ${dim(`How: ${guide ?? "https://zharp.io/docs"}`)}`);
|
|
1256
|
+
return 0;
|
|
1257
|
+
}
|
|
1258
|
+
showPlan(plan, connected);
|
|
1259
|
+
say(bar);
|
|
1260
|
+
if (options.dryRun) {
|
|
1261
|
+
say(`${green("\u25C7")} Dry run: nothing was changed.`);
|
|
1262
|
+
return 0;
|
|
1263
|
+
}
|
|
1264
|
+
if (!options.yes) {
|
|
1265
|
+
for (; ; ) {
|
|
1266
|
+
const answer = await ask(`${green("\u25C6")} Apply? ${dim("[Y]es / [n]o / show the [d]iff")} `);
|
|
1267
|
+
if (answer === "d" || answer === "diff") {
|
|
1268
|
+
for (const ch of plan.changes) {
|
|
1269
|
+
say(`
|
|
1270
|
+
${bold(`\u2500\u2500 ${ch.path} ${ch.kind === "create" ? "(new)" : "(edited)"}`)}`);
|
|
1271
|
+
say(ch.content);
|
|
1272
|
+
}
|
|
1273
|
+
continue;
|
|
1274
|
+
}
|
|
1275
|
+
if (answer === "n" || answer === "no") {
|
|
1276
|
+
say(`${yellow("\u25A0")} Nothing was changed. The app is set up in Zharp: ${connected.appUrl}`);
|
|
1277
|
+
return 0;
|
|
1278
|
+
}
|
|
1279
|
+
break;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
for (const ch of plan.changes) {
|
|
1283
|
+
const path = (0, import_node_path7.join)(dir, ch.path);
|
|
1284
|
+
(0, import_node_fs7.mkdirSync)((0, import_node_path7.dirname)(path), { recursive: true });
|
|
1285
|
+
(0, import_node_fs7.writeFileSync)(path, ch.content);
|
|
1286
|
+
}
|
|
1287
|
+
const envPath = (0, import_node_path7.join)(dir, plan.env.file);
|
|
1288
|
+
(0, import_node_fs7.writeFileSync)(envPath, mergeEnv((0, import_node_fs7.existsSync)(envPath) ? (0, import_node_fs7.readFileSync)(envPath, "utf8") : "", plan.env.vars));
|
|
1289
|
+
const gitignorePath = (0, import_node_path7.join)(dir, ".gitignore");
|
|
1290
|
+
if ((0, import_node_fs7.existsSync)((0, import_node_path7.join)(dir, ".git")) || (0, import_node_fs7.existsSync)(gitignorePath)) {
|
|
1291
|
+
const gitignore = (0, import_node_fs7.existsSync)(gitignorePath) ? (0, import_node_fs7.readFileSync)(gitignorePath, "utf8") : "";
|
|
1292
|
+
if (!ignoredByGit(gitignore, plan.env.file)) (0, import_node_fs7.writeFileSync)(gitignorePath, `${gitignore.replace(/\s*$/, "\n")}${plan.env.file}
|
|
1293
|
+
`);
|
|
1294
|
+
}
|
|
1295
|
+
say(`${green("\u25C7")} Files written`);
|
|
1296
|
+
for (const [packages, dev] of [[plan.install, false], [plan.devInstall, true]]) {
|
|
1297
|
+
if (!packages.length) continue;
|
|
1298
|
+
const [command, args] = installCommand(project, [...packages], dev, options.tarballs);
|
|
1299
|
+
say(`${bar} ${dim(`${command} ${args.join(" ")}`)}`);
|
|
1300
|
+
const result = process.platform === "win32" ? (0, import_node_child_process2.spawnSync)([command, ...args].map((a) => /[\s"&|<>^]/.test(a) ? `"${a.replace(/"/g, '\\"')}"` : a).join(" "), { cwd: dir, stdio: "inherit", shell: true }) : (0, import_node_child_process2.spawnSync)(command, args, { cwd: dir, stdio: "inherit" });
|
|
1301
|
+
if (result.status !== 0) {
|
|
1302
|
+
say(`${yellow("\u25A0")} The install failed. Run it yourself: ${command} ${args.join(" ")}`);
|
|
1303
|
+
return 1;
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
say(`${green("\u25C7")} Packages installed`);
|
|
1307
|
+
for (const m of plan.manual) {
|
|
1308
|
+
say(bar);
|
|
1309
|
+
say(`${yellow("!")} ${bold(m.path)} \u2014 ${m.why}:`);
|
|
1310
|
+
for (const line of m.snippet.split("\n")) say(`${bar} ${line}`);
|
|
1311
|
+
}
|
|
1312
|
+
for (const note of plan.notes) say(`${bar} ${yellow("!")} ${note}`);
|
|
1313
|
+
const sent = await sendTestError(api, connected);
|
|
1314
|
+
say(bar);
|
|
1315
|
+
say(sent ? `${green("\u25C7")} Done. Sent a test error \u2014 see it at ${connected.appUrl}` : `${green("\u25C7")} Done. Open ${connected.appUrl} \u2014 errors show up as your app sends them.`);
|
|
1316
|
+
return 0;
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
// src/cli.ts
|
|
1320
|
+
var HELP = `zharp ${VERSION} \u2014 readable stack traces for Zharp
|
|
1321
|
+
|
|
1322
|
+
Usage:
|
|
1323
|
+
zharp init Connect this project to Zharp and set it up
|
|
1324
|
+
[--yes] [--dry-run] (signs in through the browser)
|
|
1325
|
+
zharp sourcemaps inject <dir> Add debug IDs to JS files and their maps
|
|
1326
|
+
zharp sourcemaps upload <dir> --app <id> Upload JS files and their maps
|
|
1327
|
+
[--release <r>] [--delete-after]
|
|
1328
|
+
zharp proguard upload <mapping.txt> --app <id> --uuid <uuid>
|
|
1329
|
+
zharp dart-symbols upload <dir> --app <id> Flutter --split-debug-info output
|
|
1330
|
+
[--obfuscation-map <file>] (and its obfuscation map)
|
|
1331
|
+
zharp dsym upload <path> --app <id> A .dSYM, or a folder of them
|
|
1332
|
+
|
|
1333
|
+
Options:
|
|
1334
|
+
--app <id> Application ID (or ZHARP_APP)
|
|
1335
|
+
--release <r> Release name to file the upload under (or ZHARP_RELEASE)
|
|
1336
|
+
--include <glob> Only these files (repeatable; sourcemaps)
|
|
1337
|
+
--exclude <glob> Not these files (repeatable; sourcemaps)
|
|
1338
|
+
--delete-after Delete .map files after uploading them
|
|
1339
|
+
--dry-run Show what would happen; change and send nothing
|
|
1340
|
+
--url <url> Zharp API (default ZHARP_URL or https://api.zharp.io)
|
|
1341
|
+
-h, --help, -v, --version
|
|
1342
|
+
|
|
1343
|
+
Environment:
|
|
1344
|
+
ZHARP_AUTH_TOKEN A workspace API key with the "artifacts:write" scope (required to upload)
|
|
1345
|
+
ZHARP_URL The Zharp API, default https://api.zharp.io
|
|
1346
|
+
`;
|
|
1347
|
+
var UsageError = class extends Error {
|
|
1348
|
+
};
|
|
1349
|
+
function fail(message) {
|
|
1350
|
+
throw new UsageError(message);
|
|
1351
|
+
}
|
|
1352
|
+
async function main(argv) {
|
|
1353
|
+
const { values, positionals } = (0, import_node_util.parseArgs)({
|
|
1354
|
+
args: argv,
|
|
1355
|
+
allowPositionals: true,
|
|
1356
|
+
options: {
|
|
1357
|
+
app: { type: "string" },
|
|
1358
|
+
release: { type: "string" },
|
|
1359
|
+
uuid: { type: "string" },
|
|
1360
|
+
"obfuscation-map": { type: "string" },
|
|
1361
|
+
include: { type: "string", multiple: true },
|
|
1362
|
+
exclude: { type: "string", multiple: true },
|
|
1363
|
+
"delete-after": { type: "boolean" },
|
|
1364
|
+
"dry-run": { type: "boolean" },
|
|
1365
|
+
yes: { type: "boolean", short: "y" },
|
|
1366
|
+
tarballs: { type: "string" },
|
|
1367
|
+
url: { type: "string" },
|
|
1368
|
+
help: { type: "boolean", short: "h" },
|
|
1369
|
+
version: { type: "boolean", short: "v" }
|
|
1370
|
+
}
|
|
1371
|
+
});
|
|
1372
|
+
if (values.version) {
|
|
1373
|
+
console.log(VERSION);
|
|
1374
|
+
return;
|
|
1375
|
+
}
|
|
1376
|
+
const [group, command, target] = positionals;
|
|
1377
|
+
if (values.help || !group) {
|
|
1378
|
+
console.log(HELP);
|
|
1379
|
+
return;
|
|
1380
|
+
}
|
|
1381
|
+
if (group === "init") {
|
|
1382
|
+
process.exitCode = await runInit({ url: values.url, yes: values.yes === true, dryRun: values["dry-run"] === true, tarballs: values.tarballs, dir: command });
|
|
1383
|
+
return;
|
|
1384
|
+
}
|
|
1385
|
+
const logger = consoleLogger();
|
|
1386
|
+
const dryRun = values["dry-run"] === true;
|
|
1387
|
+
const release2 = values.release ?? process.env.ZHARP_RELEASE;
|
|
1388
|
+
const needTarget = (what) => {
|
|
1389
|
+
if (!target) fail(`${group} ${command} needs ${what}. See \`zharp --help\`.`);
|
|
1390
|
+
if (!(0, import_node_fs8.existsSync)(target)) fail(`${target} does not exist.`);
|
|
1391
|
+
return target;
|
|
1392
|
+
};
|
|
1393
|
+
const connect2 = () => dryRun ? null : resolveConnection({ app: values.app, url: values.url });
|
|
1394
|
+
switch (`${group} ${command}`) {
|
|
1395
|
+
case "sourcemaps inject": {
|
|
1396
|
+
const dir = needTarget("a directory");
|
|
1397
|
+
const files = injectDirectory(dir, { include: values.include, exclude: values.exclude, dryRun, logger });
|
|
1398
|
+
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.`);
|
|
1399
|
+
return;
|
|
1400
|
+
}
|
|
1401
|
+
case "sourcemaps upload": {
|
|
1402
|
+
const dir = needTarget("a directory");
|
|
1403
|
+
const connection = connect2();
|
|
1404
|
+
const result = await uploadSourcemaps(dir, connection, {
|
|
1405
|
+
release: release2,
|
|
1406
|
+
include: values.include,
|
|
1407
|
+
exclude: values.exclude,
|
|
1408
|
+
deleteAfter: values["delete-after"] === true,
|
|
1409
|
+
dryRun,
|
|
1410
|
+
logger
|
|
1411
|
+
});
|
|
1412
|
+
if (result.files === 0) process.exitCode = 1;
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
case "proguard upload": {
|
|
1416
|
+
const file = needTarget("the mapping.txt file");
|
|
1417
|
+
if (!values.uuid) fail("proguard upload needs --uuid <uuid>: the build UUID the Zharp Gradle plugin put into the app.");
|
|
1418
|
+
await uploadProguard(file, values.uuid, connect2(), { release: release2, dryRun, logger });
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
1421
|
+
case "dart-symbols upload": {
|
|
1422
|
+
await uploadDartSymbols(needTarget("the --split-debug-info directory"), connect2(), { release: release2, dryRun, logger, obfuscationMap: values["obfuscation-map"] });
|
|
1423
|
+
return;
|
|
1424
|
+
}
|
|
1425
|
+
case "dsym upload": {
|
|
1426
|
+
await uploadDsyms(needTarget("a .dSYM bundle or a folder of them"), connect2(), { release: release2, dryRun, logger });
|
|
1427
|
+
return;
|
|
1428
|
+
}
|
|
1429
|
+
default:
|
|
1430
|
+
fail(`Unknown command "${positionals.join(" ")}". See \`zharp --help\`.`);
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
main(process.argv.slice(2)).catch((error) => {
|
|
1434
|
+
console.error(`[zharp] error: ${error instanceof UsageError || error instanceof UploadError || error instanceof Error ? error.message : String(error)}`);
|
|
1435
|
+
process.exitCode = 1;
|
|
1436
|
+
});
|
|
1437
|
+
//# sourceMappingURL=cli.js.map
|