nativescript 9.1.2 → 9.2.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/config/config.json +1 -1
  2. package/config/test-deps-versions-generated.json +1 -1
  3. package/docs/man_pages/project/testing/build-android.md +2 -1
  4. package/docs/man_pages/project/testing/build-ios.md +2 -1
  5. package/docs/man_pages/project/testing/compiled-report.md +43 -0
  6. package/docs/man_pages/project/testing/compiled-verify.md +46 -0
  7. package/docs/man_pages/project/testing/run-android.md +2 -1
  8. package/docs/man_pages/project/testing/run-ios.md +2 -1
  9. package/lib/bootstrap.js +4 -0
  10. package/lib/commands/compiled-report.d.ts +40 -0
  11. package/lib/commands/compiled-report.js +153 -0
  12. package/lib/commands/compiled-verify.d.ts +16 -0
  13. package/lib/commands/compiled-verify.js +53 -0
  14. package/lib/common/services/hooks-service.js +7 -18
  15. package/lib/constants.d.ts +1 -0
  16. package/lib/constants.js +5 -4
  17. package/lib/controllers/build-controller.d.ts +4 -1
  18. package/lib/controllers/build-controller.js +25 -5
  19. package/lib/controllers/prepare-controller.d.ts +3 -1
  20. package/lib/controllers/prepare-controller.js +10 -1
  21. package/lib/data/prepare-data.d.ts +1 -0
  22. package/lib/data/prepare-data.js +1 -0
  23. package/lib/declarations.d.ts +1 -0
  24. package/lib/definitions/prepare.d.ts +5 -0
  25. package/lib/definitions/project.d.ts +32 -0
  26. package/lib/helpers/livesync-command-helper.js +2 -3
  27. package/lib/options.js +4 -0
  28. package/lib/services/compiled-release-service.d.ts +44 -0
  29. package/lib/services/compiled-release-service.js +357 -0
  30. package/lib/services/compiled-report-service.d.ts +89 -0
  31. package/lib/services/compiled-report-service.js +688 -0
  32. package/package.json +4 -4
@@ -0,0 +1,688 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CompiledReportService = exports.ISSUE_FORM = exports.ISSUES_REPO = void 0;
4
+ exports.redact = redact;
5
+ exports.abstractMessage = abstractMessage;
6
+ exports.constructOf = constructOf;
7
+ exports.computeSignature = computeSignature;
8
+ exports.extractDiagnostics = extractDiagnostics;
9
+ exports.newIssueUrl = newIssueUrl;
10
+ exports.readField = readField;
11
+ exports.environmentKey = environmentKey;
12
+ const crypto = require("crypto");
13
+ const os = require("os");
14
+ const path = require("path");
15
+ const resolve_package_path_1 = require("@rigor789/resolve-package-path");
16
+ const constants_1 = require("../constants");
17
+ const yok_1 = require("../common/yok");
18
+ exports.ISSUES_REPO = "NativeScript/NativeScript";
19
+ exports.ISSUE_FORM = "compiled.yml";
20
+ const MAX_URL_LENGTH = 8000;
21
+ const SEARCH_TIMEOUT_MS = 5000;
22
+ const MAX_DRAFT_OUTPUT = 200 * 1024;
23
+ const MAX_DIAGNOSTICS = 10;
24
+ const FORM_FIELDS = [
25
+ { id: "platform", label: "Platform" },
26
+ { id: "framework", label: "Framework" },
27
+ { id: "kind", label: "Kind" },
28
+ { id: "signature", label: "Signature" },
29
+ { id: "diagnostic", label: "Diagnostic", render: "text" },
30
+ { id: "source", label: "Source" },
31
+ { id: "environment", label: "Environment" },
32
+ ];
33
+ const FRAMEWORKS = [
34
+ {
35
+ name: "angular",
36
+ markers: ["@nativescript/angular"],
37
+ versionOf: "@angular/core",
38
+ },
39
+ { name: "vue", markers: ["nativescript-vue"], versionOf: "nativescript-vue" },
40
+ {
41
+ name: "svelte",
42
+ markers: ["@nativescript-community/svelte-native", "svelte-native"],
43
+ versionOf: "svelte",
44
+ },
45
+ { name: "react", markers: ["react-nativescript"], versionOf: "react" },
46
+ {
47
+ name: "solid",
48
+ markers: ["@nativescript-community/solid-js", "dominative"],
49
+ versionOf: "solid-js",
50
+ },
51
+ ];
52
+ const SOURCE_EXTENSIONS = "ts|tsx|js|jsx|mjs|vue|svelte|xml|html|css|scss";
53
+ const SOURCE_REFERENCE = new RegExp(`((?:file://)?[^\\s()'"\`]+\\.(?:${SOURCE_EXTENSIONS})):(\\d+)(?::\\d+)?`);
54
+ const LOCATED_LINE = /^(?:e: |error: )?(?:file:\/\/)?(\S+?:\d+(?::\d+)?):? (?:error: )?(.+)$/;
55
+ const REFUSAL = /^(.* is not supported in a release build(?: yet)?): (.+)$/;
56
+ const SECRETS = [
57
+ [
58
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
59
+ "<private key>",
60
+ ],
61
+ [/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, "<token>"],
62
+ [/\bAKIA[0-9A-Z]{16}\b/g, "<token>"],
63
+ [/\bAIza[0-9A-Za-z_-]{35}\b/g, "<token>"],
64
+ [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, "<token>"],
65
+ [/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{10,}/g, "<token>"],
66
+ [/\bsk-[A-Za-z0-9_-]{20,}/g, "<token>"],
67
+ [/\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,}/g, "<token>"],
68
+ [/(\/\/[^\s:/@]+:)[^\s@/]+@/g, "$1<redacted>@"],
69
+ [
70
+ /\b((?:password|passwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|auth)[\w.-]*["']?\s*[=:]\s*)(["']?)[^\s"',;]+\2/gi,
71
+ "$1<redacted>",
72
+ ],
73
+ ];
74
+ const stripAnsi = (text) => text.replace(/\x1b\[[0-9;]*[A-Za-z]/g, "");
75
+ function redact(text, projectDir, homeDir = os.homedir()) {
76
+ let result = text;
77
+ for (const dir of [projectDir, homeDir]) {
78
+ if (!dir) {
79
+ continue;
80
+ }
81
+ const replacement = dir === projectDir ? "" : "~/";
82
+ result = result
83
+ .split(`file://${dir}/`)
84
+ .join(replacement)
85
+ .split(`${dir}/`)
86
+ .join(replacement)
87
+ .split(dir)
88
+ .join(dir === projectDir ? "." : "~");
89
+ }
90
+ result = result
91
+ .replace(/(\/(?:Users|home))\/[^/\s]+/g, "$1/<user>")
92
+ .replace(/([A-Za-z]:\\Users)\\[^\\\s]+/g, "$1\\<user>");
93
+ for (const [pattern, replacement] of SECRETS) {
94
+ result = result.replace(pattern, replacement);
95
+ }
96
+ return result;
97
+ }
98
+ function abstractMessage(message, kind) {
99
+ if (kind === "native-compile") {
100
+ return message
101
+ .replace(/(?:[\w.~-]*\/)+[\w.-]+/g, "<path>")
102
+ .replace(/\b[\w-]+\.(?:kt|swift|java|ts|tsx|js|m|h)\b/g, "<path>")
103
+ .replace(/\b\d+(?:\.\d+)*\b/g, "<n>")
104
+ .replace(/\s+/g, " ")
105
+ .trim();
106
+ }
107
+ return message
108
+ .replace(/(['"`‘“])(?:(?!\1).)*?(['"`’”])/g, "<q>")
109
+ .replace(/(?:[\w.~-]*\/)+[\w.-]+/g, "<path>")
110
+ .replace(/\b\d+(?:\.\d+)*\b/g, "<n>")
111
+ .replace(/[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+/g, "<id>")
112
+ .replace(/\b[a-z_$][\w$]*(?:[A-Z_$]|\d)[\w$]*\b/g, "<id>")
113
+ .replace(/\s+/g, " ")
114
+ .trim();
115
+ }
116
+ function constructOf(message) {
117
+ const what = message
118
+ .split(/ is not supported| does not | cannot |: /)[0]
119
+ .trim();
120
+ return /^[A-Z][\w$]*(?:\.[\w$]+)*$/.test(what) ? what : "";
121
+ }
122
+ function computeSignature(kind, message) {
123
+ return crypto
124
+ .createHash("sha256")
125
+ .update(`${kind}\n${abstractMessage(message, kind)}\n${constructOf(message)}`)
126
+ .digest("hex")
127
+ .slice(0, 6);
128
+ }
129
+ function parseDiagnostic(line) {
130
+ const located = LOCATED_LINE.exec(line);
131
+ const message = located ? located[2] : line;
132
+ const refusal = REFUSAL.exec(message);
133
+ return {
134
+ location: located === null || located === void 0 ? void 0 : located[1],
135
+ message: refusal ? refusal[1] : message,
136
+ snippet: refusal === null || refusal === void 0 ? void 0 : refusal[2],
137
+ };
138
+ }
139
+ function extractDiagnostics(kind, output) {
140
+ const lines = stripAnsi(output)
141
+ .split(/\r?\n/)
142
+ .map((line) => line.trimEnd())
143
+ .filter((line) => line.trim());
144
+ const isStackLine = (line) => /^\s+at /.test(line);
145
+ let found;
146
+ if (kind === "runtime") {
147
+ const start = lines.findIndex((line) => /\b(?:[A-Z]\w*(?:Error|Exception)|Fatal error|Uncaught)\b/.test(line));
148
+ found =
149
+ start === -1
150
+ ? lines.slice(0, 15)
151
+ : [
152
+ lines[start].replace(/^.*?(?=(?:Uncaught )?\b[A-Z][\w.]*(?:Error|Exception)\b|Fatal error)/, ""),
153
+ ...lines.slice(start + 1, start + 15),
154
+ ];
155
+ }
156
+ else if (kind === "compile-refused") {
157
+ found = lines.filter((line) => /^\S+:\d+(?::\d+)?: /.test(line) ||
158
+ /is not supported in a release build|does not apply/.test(line));
159
+ if (!found.length) {
160
+ const start = lines.findIndex((line) => /^\w*Error: /.test(line));
161
+ found =
162
+ start === -1
163
+ ? lines.slice(-5)
164
+ : lines
165
+ .slice(start)
166
+ .filter((line) => !isStackLine(line) && !/^Node\.js v/.test(line));
167
+ }
168
+ found = found.map((line) => line.replace(/^Error: /, ""));
169
+ }
170
+ else {
171
+ found = lines.filter((line) => /: error: |^e: |^error: /.test(line));
172
+ if (!found.length) {
173
+ const wrong = lines.findIndex((line) => /What went wrong:/.test(line));
174
+ found =
175
+ wrong !== -1 ? lines.slice(wrong + 1, wrong + 4) : lines.slice(-10);
176
+ }
177
+ }
178
+ return [...new Set(found.map((line) => line.trim()))].slice(0, MAX_DIAGNOSTICS);
179
+ }
180
+ function newIssueUrl(title, fields, labels) {
181
+ var _a;
182
+ const note = "\n\n_(Cut to fit a URL.)_";
183
+ const values = { ...fields };
184
+ const cut = {};
185
+ const build = () => `https://github.com/${exports.ISSUES_REPO}/issues/new?` +
186
+ [
187
+ ["template", exports.ISSUE_FORM],
188
+ ["title", title],
189
+ ["labels", labels.join(",")],
190
+ ...Object.entries(values),
191
+ ]
192
+ .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
193
+ .join("&");
194
+ let url = build();
195
+ while (url.length > MAX_URL_LENGTH) {
196
+ const key = Object.keys(values).sort((a, b) => values[b].length - values[a].length)[0];
197
+ const text = (_a = cut[key]) !== null && _a !== void 0 ? _a : values[key];
198
+ const lines = text.split("\n");
199
+ cut[key] =
200
+ lines.length > 1
201
+ ? lines.slice(0, Math.floor(lines.length * 0.9)).join("\n")
202
+ : text.slice(0, Math.floor(text.length * 0.9));
203
+ values[key] = cut[key] + note;
204
+ url = build();
205
+ }
206
+ return { url, truncated: Object.keys(cut).length > 0 };
207
+ }
208
+ function readField(body, label) {
209
+ const match = new RegExp(`^###\\s+${label}\\s*\\n+([^\\n]*)`, "m").exec(body !== null && body !== void 0 ? body : "");
210
+ return match === null || match === void 0 ? void 0 : match[1].trim();
211
+ }
212
+ const majorMinor = (version) => { var _a, _b; return (_b = (_a = /(\d+\.\d+)/.exec(version !== null && version !== void 0 ? version : "")) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : "?"; };
213
+ function environmentKey(body) {
214
+ var _a;
215
+ const platform = readField(body, "Platform");
216
+ if (!platform) {
217
+ return undefined;
218
+ }
219
+ const row = (name) => {
220
+ var _a;
221
+ return (_a = new RegExp(`^\\|\\s*${name.replace(/[/.]/g, "\\$&")}\\s*\\|\\s*([^|]+)\\|`, "m").exec(body)) === null || _a === void 0 ? void 0 : _a[1];
222
+ };
223
+ return [
224
+ platform.toLowerCase(),
225
+ ((_a = readField(body, "Framework")) !== null && _a !== void 0 ? _a : "").toLowerCase(),
226
+ majorMinor(row(constants_1.COMPILER_PACKAGE_NAME)),
227
+ majorMinor(row("@nativescript/core")),
228
+ ].join("|");
229
+ }
230
+ class CompiledReportService {
231
+ constructor($childProcess, $fs, $httpClient, $logger, $staticConfig, $sysInfo) {
232
+ this.$childProcess = $childProcess;
233
+ this.$fs = $fs;
234
+ this.$httpClient = $httpClient;
235
+ this.$logger = $logger;
236
+ this.$staticConfig = $staticConfig;
237
+ this.$sysInfo = $sysInfo;
238
+ }
239
+ getReportDir(projectData, platform) {
240
+ return path.join(projectData.platformsDir, "compiled", platform.toLowerCase());
241
+ }
242
+ getDraftPath(projectData, platform) {
243
+ return path.join(this.getReportDir(projectData, platform), "report.json");
244
+ }
245
+ saveDraft(projectData, platform, kind, output) {
246
+ const draft = {
247
+ kind,
248
+ platform: platform.toLowerCase(),
249
+ createdAt: new Date().toISOString(),
250
+ output: output.slice(-MAX_DRAFT_OUTPUT),
251
+ };
252
+ try {
253
+ this.$fs.writeJson(this.getDraftPath(projectData, platform), draft);
254
+ }
255
+ catch (err) {
256
+ this.$logger.trace(`Saving the compiled report draft failed: ${err.message}`);
257
+ return "";
258
+ }
259
+ return `If this looks like a NativeScript problem, report it with 'ns compiled report ${draft.platform}' (it shows you the report before anything is sent).`;
260
+ }
261
+ clearDraft(projectData, platform) {
262
+ this.$fs.deleteFile(this.getDraftPath(projectData, platform));
263
+ }
264
+ loadDraft(projectData, platform) {
265
+ var _a;
266
+ const drafts = (platform ? [platform] : ["ios", "android"])
267
+ .map((p) => this.getDraftPath(projectData, p))
268
+ .filter((file) => this.$fs.exists(file))
269
+ .map((file) => this.$fs.readJson(file))
270
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
271
+ return (_a = drafts[0]) !== null && _a !== void 0 ? _a : null;
272
+ }
273
+ async createReport(projectData, draft) {
274
+ var _a, _b;
275
+ const projectDir = projectData.projectDir;
276
+ const clean = (text) => redact(text, projectDir);
277
+ const diagnostics = extractDiagnostics(draft.kind, draft.output).map((line) => parseDiagnostic(clean(line)));
278
+ const primary = (_b = (_a = diagnostics[0]) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : "Unknown failure";
279
+ const signature = computeSignature(draft.kind, primary);
280
+ const framework = this.detectFramework(projectData);
281
+ const headline = primary.length > 100 ? `${primary.slice(0, 97)}...` : primary;
282
+ const location = this.findLocation(projectDir, draft.output);
283
+ return {
284
+ kind: draft.kind,
285
+ platform: draft.platform,
286
+ framework: framework.name,
287
+ signature,
288
+ title: `[compiled][${draft.platform}] ${headline} (sig ${signature})`,
289
+ labels: [
290
+ "compiled",
291
+ `platform:${draft.platform}`,
292
+ `framework:${framework.name}`,
293
+ `kind:${draft.kind}`,
294
+ ],
295
+ environment: await this.collectEnvironment(projectData, draft.platform, framework),
296
+ plugins: this.collectPlugins(projectData),
297
+ diagnostics,
298
+ location,
299
+ code: location && this.readCode(projectDir, location),
300
+ };
301
+ }
302
+ formFields(report, includeCode) {
303
+ const diagnostic = report.diagnostics
304
+ .map((d) => [
305
+ d.location && `${d.location}: `,
306
+ d.message,
307
+ includeCode && d.snippet ? `: ${d.snippet}` : "",
308
+ ]
309
+ .filter(Boolean)
310
+ .join(""))
311
+ .join("\n");
312
+ const source = report.location
313
+ ? [
314
+ `\`${report.location.file}:${report.location.line}\``,
315
+ ...(includeCode && report.code
316
+ ? [
317
+ "",
318
+ "Shared with the reporter's consent:",
319
+ "~~~",
320
+ report.code,
321
+ "~~~",
322
+ ]
323
+ : []),
324
+ ].join("\n")
325
+ : "";
326
+ return {
327
+ platform: report.platform,
328
+ framework: report.framework,
329
+ kind: report.kind,
330
+ signature: report.signature,
331
+ diagnostic: diagnostic || "(no diagnostic found in the output)",
332
+ source,
333
+ environment: [
334
+ this.formatEnvironment(report),
335
+ "",
336
+ `Labels: ${report.labels.map((label) => `\`${label}\``).join(", ")}`,
337
+ ].join("\n"),
338
+ };
339
+ }
340
+ formatBody(report, includeCode) {
341
+ const fields = this.formFields(report, includeCode);
342
+ return [
343
+ ...FORM_FIELDS.map(({ id, label, render }) => {
344
+ const value = fields[id] || "_No response_";
345
+ return `### ${label}\n\n${render && fields[id] ? `\`\`\`${render}\n${value}\n\`\`\`` : value}`;
346
+ }),
347
+ "_Filed with `ns compiled report`._",
348
+ ].join("\n\n");
349
+ }
350
+ formatComment(report) {
351
+ const primary = report.diagnostics[0];
352
+ const fields = this.formFields(report, false);
353
+ return [
354
+ `+1 from \`ns compiled report\` (sig ${report.signature}), in an environment no earlier report has.`,
355
+ `### Platform\n\n${fields.platform}`,
356
+ `### Framework\n\n${fields.framework}`,
357
+ primary
358
+ ? `### Diagnostic\n\n\`\`\`text\n${primary.location ? `${primary.location}: ` : ""}${primary.message}\n\`\`\``
359
+ : "",
360
+ `### Environment\n\n${this.formatEnvironment(report)}`,
361
+ ]
362
+ .filter(Boolean)
363
+ .join("\n\n");
364
+ }
365
+ formatEnvironment(report) {
366
+ const rows = report.environment.map(([name, value]) => `| ${name} | ${value} |`);
367
+ const plugins = report.plugins.map(([name, version]) => `- ${name} ${version}`);
368
+ return [
369
+ "| | |",
370
+ "| --- | --- |",
371
+ ...rows,
372
+ "",
373
+ `<details><summary>Dependencies (${plugins.length})</summary>`,
374
+ "",
375
+ ...plugins,
376
+ "",
377
+ "</details>",
378
+ ].join("\n");
379
+ }
380
+ async hasGh() {
381
+ const result = await this.gh([
382
+ "auth",
383
+ "status",
384
+ "--hostname",
385
+ "github.com",
386
+ ]);
387
+ return result.exitCode === 0;
388
+ }
389
+ async findIssues(signature, useGh) {
390
+ var _a;
391
+ const query = `"sig ${signature}" in:title`;
392
+ if (useGh) {
393
+ const result = await this.gh([
394
+ "issue",
395
+ "list",
396
+ "--repo",
397
+ exports.ISSUES_REPO,
398
+ "--state",
399
+ "all",
400
+ "--search",
401
+ query,
402
+ "--json",
403
+ "number,title,state,url",
404
+ "--limit",
405
+ "5",
406
+ ]);
407
+ if (result.exitCode === 0) {
408
+ try {
409
+ return JSON.parse(result.stdout);
410
+ }
411
+ catch (_b) {
412
+ return null;
413
+ }
414
+ }
415
+ }
416
+ const url = `https://api.github.com/search/issues?q=${encodeURIComponent(`repo:${exports.ISSUES_REPO} is:issue ${query}`)}&per_page=5`;
417
+ try {
418
+ const response = await Promise.race([
419
+ this.$httpClient.httpRequest({
420
+ url,
421
+ method: "GET",
422
+ headers: { Accept: "application/vnd.github+json" },
423
+ }),
424
+ new Promise((_, reject) => setTimeout(() => reject(new Error("timed out")), SEARCH_TIMEOUT_MS).unref()),
425
+ ]);
426
+ const items = (_a = JSON.parse(response.body).items) !== null && _a !== void 0 ? _a : [];
427
+ return items.map((item) => ({
428
+ number: item.number,
429
+ title: item.title,
430
+ state: item.state,
431
+ url: item.html_url,
432
+ }));
433
+ }
434
+ catch (err) {
435
+ this.$logger.trace(`Searching GitHub for the report's signature failed: ${err.message}`);
436
+ return null;
437
+ }
438
+ }
439
+ async createIssue(projectData, report, body) {
440
+ const bodyFile = this.writeBodyFile(projectData, report.platform, "report.md", body);
441
+ const args = [
442
+ "issue",
443
+ "create",
444
+ "--repo",
445
+ exports.ISSUES_REPO,
446
+ "--title",
447
+ report.title,
448
+ "--body-file",
449
+ bodyFile,
450
+ ];
451
+ let result = await this.gh([
452
+ ...args,
453
+ ...report.labels.flatMap((label) => ["--label", label]),
454
+ ]);
455
+ if (result.exitCode !== 0 && /label/i.test(result.stderr)) {
456
+ this.$logger.warn("GitHub refused the labels; filing without them (they are listed in the body).");
457
+ result = await this.gh(args);
458
+ }
459
+ if (result.exitCode !== 0) {
460
+ this.$logger.warn(`gh issue create failed: ${result.stderr.trim()}`);
461
+ return null;
462
+ }
463
+ return result.stdout.trim().split("\n").pop();
464
+ }
465
+ async plusOne(projectData, report, issue) {
466
+ const reaction = await this.gh([
467
+ "api",
468
+ "--method",
469
+ "POST",
470
+ `repos/${exports.ISSUES_REPO}/issues/${issue.number}/reactions`,
471
+ "-f",
472
+ "content=+1",
473
+ ]);
474
+ if (reaction.exitCode !== 0) {
475
+ this.$logger.warn(`Adding the 👍 failed: ${reaction.stderr.trim()}`);
476
+ }
477
+ const view = await this.gh([
478
+ "issue",
479
+ "view",
480
+ String(issue.number),
481
+ "--repo",
482
+ exports.ISSUES_REPO,
483
+ "--json",
484
+ "body,comments",
485
+ ]);
486
+ let known;
487
+ try {
488
+ const { body, comments } = JSON.parse(view.stdout);
489
+ known = new Set([body, ...(comments !== null && comments !== void 0 ? comments : []).map((c) => c.body)]
490
+ .map(environmentKey)
491
+ .filter(Boolean));
492
+ }
493
+ catch (_a) {
494
+ this.$logger.trace(`Reading #${issue.number}'s reports failed: ${view.stderr}`);
495
+ return { reacted: reaction.exitCode === 0, commented: false };
496
+ }
497
+ const comment = this.formatComment(report);
498
+ if (known.has(environmentKey(comment))) {
499
+ return { reacted: reaction.exitCode === 0, commented: false };
500
+ }
501
+ const bodyFile = this.writeBodyFile(projectData, report.platform, "report-comment.md", comment);
502
+ const result = await this.gh([
503
+ "issue",
504
+ "comment",
505
+ String(issue.number),
506
+ "--repo",
507
+ exports.ISSUES_REPO,
508
+ "--body-file",
509
+ bodyFile,
510
+ ]);
511
+ if (result.exitCode !== 0) {
512
+ this.$logger.warn(`gh issue comment failed: ${result.stderr.trim()}`);
513
+ }
514
+ return {
515
+ reacted: reaction.exitCode === 0,
516
+ commented: result.exitCode === 0,
517
+ };
518
+ }
519
+ writeBodyFile(projectData, platform, name, body) {
520
+ const file = path.join(this.getReportDir(projectData, platform), name);
521
+ this.$fs.writeFile(file, body);
522
+ return file;
523
+ }
524
+ gh(args) {
525
+ return this.$childProcess.spawnFromEvent("gh", args, "close", {}, { throwError: false });
526
+ }
527
+ findLocation(projectDir, output) {
528
+ for (const line of stripAnsi(output).split(/\r?\n/)) {
529
+ const match = SOURCE_REFERENCE.exec(line);
530
+ if (!match) {
531
+ continue;
532
+ }
533
+ const file = path.resolve(projectDir, match[1].replace(/^file:\/\//, ""));
534
+ const relative = path.relative(projectDir, file);
535
+ if (relative.startsWith("..") ||
536
+ path.isAbsolute(relative) ||
537
+ relative.startsWith(`platforms${path.sep}`) ||
538
+ relative.includes(path.join("node_modules", constants_1.COMPILER_PACKAGE_NAME))) {
539
+ continue;
540
+ }
541
+ return {
542
+ file: relative.split(path.sep).join("/"),
543
+ line: Number(match[2]),
544
+ };
545
+ }
546
+ return undefined;
547
+ }
548
+ readCode(projectDir, location) {
549
+ const file = path.join(projectDir, location.file);
550
+ if (!this.$fs.exists(file)) {
551
+ return undefined;
552
+ }
553
+ const lines = this.$fs.readText(file).split(/\r?\n/);
554
+ const first = Math.max(1, location.line - 3);
555
+ const last = Math.min(lines.length, location.line + 3);
556
+ const width = String(last).length;
557
+ const numbered = [];
558
+ for (let n = first; n <= last; n++) {
559
+ numbered.push(`${String(n).padStart(width)} ${n === location.line ? ">" : "|"} ${lines[n - 1]}`);
560
+ }
561
+ return redact(numbered.join("\n"), projectDir);
562
+ }
563
+ readPackageJson(projectDir) {
564
+ const file = path.join(projectDir, "package.json");
565
+ return this.$fs.exists(file) ? this.$fs.readJson(file) : {};
566
+ }
567
+ installedVersion(projectData, name) {
568
+ var _a, _b, _c;
569
+ const pkg = this.readPackageJson(projectData.projectDir);
570
+ try {
571
+ const dir = (0, resolve_package_path_1.resolvePackagePath)(name, { paths: [projectData.projectDir] });
572
+ if (dir) {
573
+ return this.$fs.readJson(path.join(dir, "package.json")).version;
574
+ }
575
+ }
576
+ catch (err) {
577
+ this.$logger.trace(`Reading ${name}'s version failed: ${err.message}`);
578
+ }
579
+ return (_b = (_a = pkg.dependencies) === null || _a === void 0 ? void 0 : _a[name]) !== null && _b !== void 0 ? _b : (_c = pkg.devDependencies) === null || _c === void 0 ? void 0 : _c[name];
580
+ }
581
+ detectFramework(projectData) {
582
+ var _a;
583
+ const pkg = this.readPackageJson(projectData.projectDir);
584
+ const deps = { ...pkg.devDependencies, ...pkg.dependencies };
585
+ const framework = FRAMEWORKS.find((f) => f.markers.some((marker) => marker in deps));
586
+ if (!framework) {
587
+ return { name: "xml", version: "" };
588
+ }
589
+ return {
590
+ name: framework.name,
591
+ version: (_a = this.installedVersion(projectData, framework.versionOf)) !== null && _a !== void 0 ? _a : "unknown",
592
+ };
593
+ }
594
+ collectPlugins(projectData) {
595
+ var _a;
596
+ const dependencies = (_a = this.readPackageJson(projectData.projectDir).dependencies) !== null && _a !== void 0 ? _a : {};
597
+ return Object.keys(dependencies)
598
+ .sort()
599
+ .map((name) => {
600
+ var _a;
601
+ return [
602
+ name,
603
+ (_a = this.installedVersion(projectData, name)) !== null && _a !== void 0 ? _a : "unknown",
604
+ ];
605
+ });
606
+ }
607
+ async collectEnvironment(projectData, platform, framework) {
608
+ const version = (name) => { var _a; return (_a = this.installedVersion(projectData, name)) !== null && _a !== void 0 ? _a : "not installed"; };
609
+ const rows = [
610
+ ["NativeScript CLI", this.$staticConfig.version],
611
+ [constants_1.COMPILER_PACKAGE_NAME, version(constants_1.COMPILER_PACKAGE_NAME)],
612
+ ["@nativescript/core", version("@nativescript/core")],
613
+ [
614
+ "Framework",
615
+ `${framework.name}${framework.version ? ` ${framework.version}` : ""}`,
616
+ ],
617
+ ["Platform", platform],
618
+ ];
619
+ if (platform === "ios") {
620
+ let xcode;
621
+ try {
622
+ xcode = await this.$sysInfo.getXcodeVersion();
623
+ }
624
+ catch (err) {
625
+ this.$logger.trace(`Reading Xcode's version failed: ${err.message}`);
626
+ }
627
+ rows.push(["Xcode", xcode || "unknown"]);
628
+ }
629
+ else {
630
+ rows.push(...this.androidToolVersions(projectData));
631
+ }
632
+ rows.push(["OS", `${os.type()} ${os.release()} ${os.arch()}`], ["Node.js", process.version]);
633
+ return rows;
634
+ }
635
+ androidToolVersions(projectData) {
636
+ var _a, _b;
637
+ let compilerDir;
638
+ try {
639
+ compilerDir = (0, resolve_package_path_1.resolvePackagePath)(constants_1.COMPILER_PACKAGE_NAME, {
640
+ paths: [projectData.projectDir],
641
+ });
642
+ }
643
+ catch (err) {
644
+ this.$logger.trace(`Resolving ${constants_1.COMPILER_PACKAGE_NAME} failed: ${err.message}`);
645
+ }
646
+ const read = (file) => this.$fs.exists(file) && this.$fs.getFsStats(file).isFile()
647
+ ? this.$fs.readText(file)
648
+ : "";
649
+ const projectRoot = this.getReportDir(projectData, "android");
650
+ const generated = this.$fs.exists(projectRoot)
651
+ ? this.$fs
652
+ .readDirectory(projectRoot)
653
+ .filter((file) => /\.gradle(\.kts)?$/.test(file))
654
+ .map((file) => read(path.join(projectRoot, file)))
655
+ : [];
656
+ const sources = [
657
+ ...generated,
658
+ ...(compilerDir
659
+ ? [
660
+ path.join("kit-android", "build.gradle.kts"),
661
+ path.join("dist", "android.js"),
662
+ path.join("src", "android.ts"),
663
+ ].map((file) => read(path.join(compilerDir, file)))
664
+ : []),
665
+ ];
666
+ const plugin = (id) => {
667
+ var _a;
668
+ const pattern = new RegExp(`id\\s*\\(?\\s*["']${id.replace(/\./g, "\\.")}["']\\s*\\)?\\s*version\\s*["']([^"']+)`);
669
+ for (const source of sources) {
670
+ const version = (_a = pattern.exec(source)) === null || _a === void 0 ? void 0 : _a[1];
671
+ if (version) {
672
+ return version;
673
+ }
674
+ }
675
+ return "unknown";
676
+ };
677
+ const wrapper = compilerDir
678
+ ? read(path.join(compilerDir, "kit-android", "gradle", "wrapper", "gradle-wrapper.properties"))
679
+ : "";
680
+ return [
681
+ ["Gradle", (_b = (_a = /gradle-([\d.]+)-/.exec(wrapper)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : "unknown"],
682
+ ["Android Gradle Plugin", plugin("com.android.application")],
683
+ ["Kotlin", plugin("org.jetbrains.kotlin.android")],
684
+ ];
685
+ }
686
+ }
687
+ exports.CompiledReportService = CompiledReportService;
688
+ yok_1.injector.register("compiledReportService", CompiledReportService);