eas-cli 25.3.0 → 27.1.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 (81) hide show
  1. package/README.md +268 -198
  2. package/build/build/build.js +6 -0
  3. package/build/build/createContext.d.ts +4 -3
  4. package/build/build/createContext.js +1 -4
  5. package/build/build/errors.d.ts +2 -0
  6. package/build/build/errors.js +4 -1
  7. package/build/build/evaluateConfigWithEnvVarsAsync.js +1 -3
  8. package/build/build/runBuildAndSubmit.d.ts +7 -2
  9. package/build/build/runBuildAndSubmit.js +9 -8
  10. package/build/build/utils/expoTokenRole.d.ts +4 -0
  11. package/build/build/utils/expoTokenRole.js +14 -0
  12. package/build/commandUtils/EasCommand.js +3 -3
  13. package/build/commandUtils/context/DynamicProjectConfigContextField.d.ts +2 -2
  14. package/build/commandUtils/context/DynamicProjectConfigContextField.js +40 -61
  15. package/build/commandUtils/context/LoggedInContextField.js +1 -2
  16. package/build/commandUtils/context/MaybeLoggedInContextField.js +1 -2
  17. package/build/commandUtils/context/OptionalPrivateProjectConfigContextField.js +3 -1
  18. package/build/commandUtils/context/PrivateProjectConfigContextField.js +3 -1
  19. package/build/commandUtils/context/contextUtils/findProjectDirAndVerifyProjectSetupAsync.js +2 -1
  20. package/build/commandUtils/context/contextUtils/getProjectIdAsync.d.ts +1 -0
  21. package/build/commandUtils/context/contextUtils/getProjectIdAsync.js +5 -2
  22. package/build/commandUtils/workflow/referencedFiles.d.ts +6 -0
  23. package/build/commandUtils/workflow/referencedFiles.js +63 -0
  24. package/build/commandUtils/workflow/types.d.ts +1 -1
  25. package/build/commandUtils/workflow/utils.js +34 -5
  26. package/build/commands/account/login.js +6 -0
  27. package/build/commands/account/view.d.ts +0 -7
  28. package/build/commands/account/view.js +4 -74
  29. package/build/commands/browse.js +1 -1
  30. package/build/commands/build/dev.js +3 -3
  31. package/build/commands/channel/delete.js +1 -1
  32. package/build/commands/channel/rollout.js +1 -1
  33. package/build/commands/credentials/configure-build.js +1 -1
  34. package/build/commands/deploy/alias/delete.js +1 -1
  35. package/build/commands/deploy/alias/index.js +1 -1
  36. package/build/commands/deploy/delete.js +1 -1
  37. package/build/commands/go.js +1 -1
  38. package/build/commands/observe/event.js +1 -1
  39. package/build/commands/observe/events.js +1 -1
  40. package/build/commands/project/new.js +1 -1
  41. package/build/commands/simulator/control.js +42 -7
  42. package/build/commands/simulator/get.js +14 -1
  43. package/build/commands/simulator/index.js +12 -4
  44. package/build/commands/simulator/logs.d.ts +22 -0
  45. package/build/commands/simulator/logs.js +188 -0
  46. package/build/commands/workflow/cancel.js +9 -20
  47. package/build/commands/workflow/list.js +1 -1
  48. package/build/commands/workflow/logs.js +1 -1
  49. package/build/commands/workflow/run.js +10 -1
  50. package/build/commands/workflow/runs.js +1 -1
  51. package/build/commands/workflow/status.js +1 -1
  52. package/build/commands/workflow/view.js +1 -1
  53. package/build/graphql/generated.d.ts +438 -115
  54. package/build/graphql/generated.js +40 -9
  55. package/build/graphql/mutations/WorkflowRevisionMutation.d.ts +3 -2
  56. package/build/graphql/mutations/WorkflowRevisionMutation.js +12 -3
  57. package/build/graphql/queries/DeviceRunSessionQuery.d.ts +8 -1
  58. package/build/graphql/queries/DeviceRunSessionQuery.js +67 -0
  59. package/build/graphql/queries/WorkflowRunQuery.js +6 -0
  60. package/build/graphql/types/WorkflowRun.js +1 -0
  61. package/build/help.js +13 -6
  62. package/build/log.d.ts +2 -0
  63. package/build/log.js +10 -0
  64. package/build/project/projectStatus.js +1 -0
  65. package/build/simulator/artifacts.d.ts +9 -0
  66. package/build/simulator/artifacts.js +97 -0
  67. package/build/simulator/download.d.ts +2 -0
  68. package/build/simulator/download.js +57 -0
  69. package/build/simulator/events.js +2 -10
  70. package/build/simulator/jobRunErrors.d.ts +22 -0
  71. package/build/simulator/jobRunErrors.js +134 -0
  72. package/build/simulator/preview.d.ts +26 -0
  73. package/build/simulator/preview.js +156 -0
  74. package/build/simulator/utils.d.ts +5 -0
  75. package/build/simulator/utils.js +42 -0
  76. package/build/user/SessionManager.d.ts +10 -0
  77. package/build/user/SessionManager.js +12 -0
  78. package/build/user/accountPermissions.d.ts +11 -0
  79. package/build/user/accountPermissions.js +89 -0
  80. package/oclif.manifest.json +169 -21
  81. package/package.json +7 -7
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetchSimulatorSessionErrorsAsync = fetchSimulatorSessionErrorsAsync;
4
+ exports.formatSimulatorSessionError = formatSimulatorSessionError;
5
+ exports.selectFailedStepErrors = selectFailedStepErrors;
6
+ const tslib_1 = require("tslib");
7
+ const util_1 = require("util");
8
+ const parseLogs_1 = require("../commandUtils/logs/parseLogs");
9
+ const fetch_1 = tslib_1.__importDefault(require("../fetch"));
10
+ const DeviceRunSessionQuery_1 = require("../graphql/queries/DeviceRunSessionQuery");
11
+ const log_1 = tslib_1.__importStar(require("../log"));
12
+ const terminalText_1 = require("../utils/terminalText");
13
+ // ErrorCode.UNKNOWN_ERROR and ErrorCode.UNKNOWN_CUSTOM_BUILD_ERROR from @expo/eas-build-job.
14
+ const UNKNOWN_ERROR_CODES = new Set(['UNKNOWN_ERROR', 'UNKNOWN_CUSTOM_BUILD_ERROR']);
15
+ const DEFAULT_QUERY_TIMEOUT_MS = 10_000;
16
+ const DEFAULT_LOG_DOWNLOAD_TIMEOUT_MS = 10_000;
17
+ const DEFAULT_MAX_LOG_SIZE_BYTES = 20 * 1024 * 1024;
18
+ const MAX_LOGGED_ERRORS = 4;
19
+ const MAX_LOGGED_ERROR_LENGTH = 500;
20
+ // Bunyan's "error" level.
21
+ const ERROR_LOG_LEVEL = 50;
22
+ const STDERR_CAUSE_PATTERN = /\b(error|exception|fatal)\b/i;
23
+ // Returns why the session's job run failed, or an empty list when that is not available.
24
+ async function fetchSimulatorSessionErrorsAsync(graphqlClient, deviceRunSessionId, { signal, queryTimeoutMs = DEFAULT_QUERY_TIMEOUT_MS, logDownloadTimeoutMs = DEFAULT_LOG_DOWNLOAD_TIMEOUT_MS, maxLogSizeBytes = DEFAULT_MAX_LOG_SIZE_BYTES, } = {}) {
25
+ if (signal?.aborted) {
26
+ return [];
27
+ }
28
+ let jobRun;
29
+ try {
30
+ jobRun = await DeviceRunSessionQuery_1.DeviceRunSessionQuery.jobRunErrorsByIdAsync(graphqlClient, deviceRunSessionId, {
31
+ signal: withTimeout(signal, queryTimeoutMs),
32
+ });
33
+ }
34
+ catch (err) {
35
+ log_1.default.debug(`Failed to fetch simulator session errors: ${err}`);
36
+ return [];
37
+ }
38
+ const errors = jobRun?.errors ?? [];
39
+ // Uncategorized failures only say "Unknown error. See logs", so read the real cause from the job run logs.
40
+ const logFileUrl = jobRun?.logFileUrls[0];
41
+ if (logFileUrl &&
42
+ errors.length > 0 &&
43
+ errors.every(error => UNKNOWN_ERROR_CODES.has(error.errorCode))) {
44
+ const logErrors = await fetchJobRunLogErrorsAsync(logFileUrl, {
45
+ signal: withTimeout(signal, logDownloadTimeoutMs),
46
+ maxLogSizeBytes,
47
+ });
48
+ if (logErrors.length > 0) {
49
+ return logErrors.map(message => ({ errorCode: errors[0].errorCode, message, docsUrl: null }));
50
+ }
51
+ }
52
+ return errors.map(({ errorCode, message, docsUrl }) => ({
53
+ errorCode,
54
+ message: formatMessage(message),
55
+ docsUrl,
56
+ }));
57
+ }
58
+ function formatSimulatorSessionError(error) {
59
+ return `${error.message}${error.docsUrl ? ` ${(0, log_1.learnMore)(error.docsUrl)}` : ''}`;
60
+ }
61
+ function withTimeout(signal, timeoutMs) {
62
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
63
+ return signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
64
+ }
65
+ async function fetchJobRunLogErrorsAsync(logFileUrl, { signal, maxLogSizeBytes }) {
66
+ // node-fetch stops reading on its own only when the body ends, so abort to close the connection
67
+ // after an error, an oversized body or a timeout.
68
+ const controller = new AbortController();
69
+ try {
70
+ const response = await (0, fetch_1.default)(logFileUrl, {
71
+ size: maxLogSizeBytes,
72
+ signal: AbortSignal.any([signal, controller.signal]),
73
+ });
74
+ const { logLines } = (0, parseLogs_1.parseLogLines)(await response.text());
75
+ return selectFailedStepErrors(logLines);
76
+ }
77
+ catch (err) {
78
+ // node-fetch's error messages include the signed log URL, so leave the message out.
79
+ log_1.default.debug(`Failed to read simulator session logs: ${err instanceof Error ? err.name : 'unknown error'}`);
80
+ return [];
81
+ }
82
+ finally {
83
+ controller.abort();
84
+ }
85
+ }
86
+ // Describes the steps that failed, the first one first: its last error line, preceded by the stderr
87
+ // line that names the cause and the line after it. Later failed steps only add their error line.
88
+ // Uses the log message rather than err.message because only the message has secrets masked.
89
+ function selectFailedStepErrors(logLines) {
90
+ const failedStepIds = [
91
+ ...new Set(logLines
92
+ .filter(line => line.marker === 'end-step' && line.result === 'fail' && line.buildStepId)
93
+ .map(line => line.buildStepId)),
94
+ ];
95
+ const messages = failedStepIds.flatMap((stepId, index) => {
96
+ const lines = selectStepFailureLines(logLines.filter(line => line.buildStepId === stepId));
97
+ return (index === 0 ? lines : lines.slice(-1)).map(formatLogLine);
98
+ });
99
+ return [...new Set(messages)].slice(0, MAX_LOGGED_ERRORS);
100
+ }
101
+ function selectStepFailureLines(stepLines) {
102
+ let selected = [];
103
+ let stderrCause = [];
104
+ for (const [index, line] of stepLines.entries()) {
105
+ const text = toPlainText(line.msg ?? '');
106
+ if (line.source === 'stderr') {
107
+ if (STDERR_CAUSE_PATTERN.test(text)) {
108
+ stderrCause = [line];
109
+ }
110
+ else if (stderrCause.length === 1 && stepLines[index - 1] === stderrCause[0]) {
111
+ stderrCause.push(line);
112
+ }
113
+ }
114
+ else if (line.err && (line.level ?? 0) >= ERROR_LOG_LEVEL && text) {
115
+ selected = [...stderrCause, line];
116
+ stderrCause = [];
117
+ }
118
+ }
119
+ return selected;
120
+ }
121
+ function formatLogLine(line) {
122
+ return formatMessage(line.buildStepDisplayName ? `${line.buildStepDisplayName}: ${line.msg}` : String(line.msg));
123
+ }
124
+ // Log text comes from commands run in the session, so strip escape sequences and control
125
+ // characters that could clear the terminal or spoof output.
126
+ function toPlainText(message) {
127
+ return (0, terminalText_1.sanitizeTerminalText)((0, util_1.stripVTControlCharacters)(message));
128
+ }
129
+ function formatMessage(message) {
130
+ const text = toPlainText(message);
131
+ return text.length > MAX_LOGGED_ERROR_LENGTH
132
+ ? `${text.slice(0, MAX_LOGGED_ERROR_LENGTH)}…`
133
+ : text;
134
+ }
@@ -0,0 +1,26 @@
1
+ import { type SimulatorSession } from './artifacts';
2
+ import { type Response } from '../fetch';
3
+ export type SimulatorPreview = {
4
+ deviceRunSessionId: string;
5
+ baseUrl: URL;
6
+ token: string;
7
+ };
8
+ type SimulatorPreviewRequestOptions = {
9
+ query?: Record<string, string>;
10
+ signal?: AbortSignal;
11
+ /** Message for a 404 response. Defaults to a generic message for unsupported preview data. */
12
+ notFoundMessage?: string;
13
+ };
14
+ export declare function resolveSimulatorPreviewAsync(session: SimulatorSession): Promise<SimulatorPreview>;
15
+ export declare function fetchSimulatorPreviewAsync(preview: SimulatorPreview, route: string, { query, signal, notFoundMessage, accept, }?: SimulatorPreviewRequestOptions & {
16
+ accept?: string;
17
+ }): Promise<Response>;
18
+ export declare function fetchSimulatorPreviewJsonAsync<T>(preview: SimulatorPreview, route: string, options?: Omit<SimulatorPreviewRequestOptions, 'signal'>): Promise<T>;
19
+ /**
20
+ * Calls `onData` with each server-sent event's data until `signal` aborts. The stream ending is an error.
21
+ * Errors thrown by `onData` stop the stream and are rethrown unchanged.
22
+ */
23
+ export declare function streamSimulatorPreviewAsync(preview: SimulatorPreview, route: string, onData: (data: string) => void, { signal, ...options }: SimulatorPreviewRequestOptions & {
24
+ signal: AbortSignal;
25
+ }): Promise<void>;
26
+ export {};
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveSimulatorPreviewAsync = resolveSimulatorPreviewAsync;
4
+ exports.fetchSimulatorPreviewAsync = fetchSimulatorPreviewAsync;
5
+ exports.fetchSimulatorPreviewJsonAsync = fetchSimulatorPreviewJsonAsync;
6
+ exports.streamSimulatorPreviewAsync = streamSimulatorPreviewAsync;
7
+ const tslib_1 = require("tslib");
8
+ const node_readline_1 = tslib_1.__importDefault(require("node:readline"));
9
+ const utils_1 = require("./utils");
10
+ const fetch_1 = tslib_1.__importStar(require("../fetch"));
11
+ const generated_1 = require("../graphql/generated");
12
+ const PREVIEW_API_TIMEOUT_MS = 30_000;
13
+ // The preview server sends a heartbeat every 15 seconds, so a longer silence means the stream is gone.
14
+ const PREVIEW_STREAM_IDLE_TIMEOUT_MS = 60_000;
15
+ const INVALID_PREVIEW_API_URL_MESSAGE = 'The simulator session has an invalid preview API URL. The session reported a URL that is not a valid HTTP(S) URL. Start a new session with `eas simulator:start`.';
16
+ const PREVIEW_STREAM_ENDED_MESSAGE = "The simulator preview stream ended unexpectedly. The connection to the session's preview server closed. Run `eas simulator:get` to check that the session is still running, then run the command again.";
17
+ const PREVIEW_DATA_NOT_FOUND_MESSAGE = "The requested preview data was not found. The session's preview server does not support this request. Start a new session with `eas simulator:start`, then try again.";
18
+ async function resolveSimulatorPreviewAsync(session) {
19
+ if (session.status !== generated_1.DeviceRunSessionStatus.InProgress) {
20
+ throw new Error('The simulator session is not running. Live preview data is only available while a session runs. Start a new session with `eas simulator:start`.');
21
+ }
22
+ const access = session.remoteConfig ? (0, utils_1.getPreviewApiAccess)(session.remoteConfig) : null;
23
+ if (!access) {
24
+ throw new Error('This simulator session does not expose a preview API. The command reads live data through the preview API, and the session did not report its URL and token. Start a new iOS session with `eas simulator:start --platform ios`.');
25
+ }
26
+ let baseUrl;
27
+ try {
28
+ baseUrl = new URL(access.apiUrl);
29
+ }
30
+ catch {
31
+ throw new Error(INVALID_PREVIEW_API_URL_MESSAGE);
32
+ }
33
+ if (!['https:', 'http:'].includes(baseUrl.protocol)) {
34
+ throw new Error(INVALID_PREVIEW_API_URL_MESSAGE);
35
+ }
36
+ // Requests send the token in a header, so keep it out of URLs that can appear in errors.
37
+ baseUrl.searchParams.delete('token');
38
+ baseUrl.hash = '';
39
+ return { deviceRunSessionId: session.id, baseUrl, token: access.token };
40
+ }
41
+ async function fetchSimulatorPreviewAsync(preview, route, { query, signal, notFoundMessage = PREVIEW_DATA_NOT_FOUND_MESSAGE, accept, } = {}) {
42
+ const url = new URL(route, preview.baseUrl);
43
+ for (const [key, value] of Object.entries(query ?? {})) {
44
+ url.searchParams.set(key, value);
45
+ }
46
+ // Aborting closes the connection of an error response, whose body is never read.
47
+ const controller = new AbortController();
48
+ try {
49
+ return await (0, fetch_1.default)(url.toString(), {
50
+ timeout: PREVIEW_API_TIMEOUT_MS,
51
+ redirect: 'error',
52
+ signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
53
+ headers: {
54
+ Authorization: `Bearer ${preview.token}`,
55
+ ...(accept ? { Accept: accept } : {}),
56
+ },
57
+ });
58
+ }
59
+ catch (error) {
60
+ if (signal?.aborted) {
61
+ throw error;
62
+ }
63
+ if (error instanceof fetch_1.RequestError) {
64
+ controller.abort();
65
+ if (error.response.headers.get('ngrok-error-code') === 'ERR_NGROK_3200') {
66
+ throw new Error('The simulator preview is offline. The session may have stopped or reached its time limit. Start a new session with `eas simulator:start`.');
67
+ }
68
+ const { status } = error.response;
69
+ if (status === 401 || status === 403) {
70
+ throw new Error("The preview API refused access. It did not accept the session's preview token. Run `eas simulator:get` to check that the session is still running, then try again.");
71
+ }
72
+ if (status === 404) {
73
+ throw new Error(notFoundMessage);
74
+ }
75
+ throw new Error(`The preview API request failed (HTTP ${status}). The session's preview server returned an error. Run \`eas simulator:get\` to check that the session is still running, then try again.`);
76
+ }
77
+ throw new Error("Could not connect to the simulator preview API. The request did not reach the session's preview server. Check your internet connection. Run `eas simulator:get` to check that the session is still running.");
78
+ }
79
+ }
80
+ async function fetchSimulatorPreviewJsonAsync(preview, route, options = {}) {
81
+ const response = await fetchSimulatorPreviewAsync(preview, route, {
82
+ ...options,
83
+ accept: 'application/json',
84
+ });
85
+ try {
86
+ return (await response.json());
87
+ }
88
+ catch {
89
+ throw new Error('Could not read the simulator preview API response. The response was incomplete or not valid JSON. Try again.');
90
+ }
91
+ }
92
+ /**
93
+ * Calls `onData` with each server-sent event's data until `signal` aborts. The stream ending is an error.
94
+ * Errors thrown by `onData` stop the stream and are rethrown unchanged.
95
+ */
96
+ async function streamSimulatorPreviewAsync(preview, route, onData, { signal, ...options }) {
97
+ // Aborting closes the connection, including when the stream stops because of an error.
98
+ const controller = new AbortController();
99
+ let reading = false;
100
+ let onDataError;
101
+ let idleTimer;
102
+ const resetIdleTimer = () => {
103
+ clearTimeout(idleTimer);
104
+ idleTimer = setTimeout(() => {
105
+ controller.abort();
106
+ }, PREVIEW_STREAM_IDLE_TIMEOUT_MS);
107
+ };
108
+ try {
109
+ const response = await fetchSimulatorPreviewAsync(preview, route, {
110
+ ...options,
111
+ signal: AbortSignal.any([signal, controller.signal]),
112
+ accept: 'text/event-stream',
113
+ });
114
+ if (!response.headers.get('content-type')?.includes('text/event-stream')) {
115
+ throw new Error('This simulator session does not support streaming. Its preview server did not return an event stream. Run the command without --follow.');
116
+ }
117
+ reading = true;
118
+ resetIdleTimer();
119
+ let data = [];
120
+ for await (const line of node_readline_1.default.createInterface({
121
+ input: response.body,
122
+ crlfDelay: Infinity,
123
+ })) {
124
+ resetIdleTimer();
125
+ if (line === '' && data.length > 0) {
126
+ const frame = data.join('\n');
127
+ data = [];
128
+ try {
129
+ onData(frame);
130
+ }
131
+ catch (error) {
132
+ onDataError = error;
133
+ throw error;
134
+ }
135
+ }
136
+ else if (line.startsWith('data:')) {
137
+ data.push(line.slice(5).replace(/^ /, ''));
138
+ }
139
+ }
140
+ // The server keeps the stream open while the session runs, so a clean end is unexpected too.
141
+ throw new Error(PREVIEW_STREAM_ENDED_MESSAGE);
142
+ }
143
+ catch (error) {
144
+ if (signal.aborted) {
145
+ return;
146
+ }
147
+ if (!reading || error === onDataError) {
148
+ throw error;
149
+ }
150
+ throw new Error(PREVIEW_STREAM_ENDED_MESSAGE);
151
+ }
152
+ finally {
153
+ clearTimeout(idleTimer);
154
+ controller.abort();
155
+ }
156
+ }
@@ -114,4 +114,9 @@ export declare function sanitizeRemoteConfigForJson(remoteConfig: DeviceRunSessi
114
114
  */
115
115
  export declare function formatEmbedPreviewUrl(remoteConfig: DeviceRunSessionRemoteConfig): string | null;
116
116
  export declare function formatRemoteSessionInstructions(remoteConfig: DeviceRunSessionRemoteConfig, configType: RemoteSessionInstructionsConfigType, { egressAllow, egressClientRunsInline, sessionUrl, platform, privatePreviewUrl, publicLink, frameAncestors, corsOrigins, }?: LocalEgressOptions & PreviewLinkOptions): string;
117
+ export declare function stripTerminalControlCharacters(value: string, { keepNewlinesAndTabs }?: {
118
+ keepNewlinesAndTabs?: boolean;
119
+ }): string;
120
+ export declare function isValidLogTime(at: unknown): at is number;
121
+ export declare function formatLogLine(raw: string, timestamp?: boolean, at?: number): string;
117
122
  export {};
@@ -14,8 +14,12 @@ exports.formatPreviewUrl = formatPreviewUrl;
14
14
  exports.sanitizeRemoteConfigForJson = sanitizeRemoteConfigForJson;
15
15
  exports.formatEmbedPreviewUrl = formatEmbedPreviewUrl;
16
16
  exports.formatRemoteSessionInstructions = formatRemoteSessionInstructions;
17
+ exports.stripTerminalControlCharacters = stripTerminalControlCharacters;
18
+ exports.isValidLogTime = isValidLogTime;
19
+ exports.formatLogLine = formatLogLine;
17
20
  const tslib_1 = require("tslib");
18
21
  const chalk_1 = tslib_1.__importDefault(require("chalk"));
22
+ const util_1 = require("util");
19
23
  const generated_1 = require("../graphql/generated");
20
24
  const log_1 = require("../log");
21
25
  const env_1 = require("./env");
@@ -435,3 +439,41 @@ function formatControllerInstructions(remoteConfig, configType, previewLinkOptio
435
439
  ].join('\n');
436
440
  }
437
441
  }
442
+ // Session text is untrusted, so strip terminal escape and control characters before printing it.
443
+ function stripTerminalControlCharacters(value, { keepNewlinesAndTabs = false } = {}) {
444
+ return (0, util_1.stripVTControlCharacters)(value).replace(/\p{Cc}/gu, character => keepNewlinesAndTabs && (character === '\n' || character === '\t') ? character : '');
445
+ }
446
+ function isValidLogTime(at) {
447
+ return typeof at === 'number' && !Number.isNaN(new Date(at).getTime());
448
+ }
449
+ function formatLogLine(raw, timestamp = false, at = Date.now()) {
450
+ const time = new Date(isValidLogTime(at) ? at : Date.now()).toISOString();
451
+ try {
452
+ const entry = JSON.parse(raw);
453
+ if (typeof entry.eventMessage === 'string') {
454
+ const prefix = timestamp
455
+ ? `${chalk_1.default.dim(stripTerminalControlCharacters(entry.timestamp ?? time))} `
456
+ : '';
457
+ const processName = entry.processImagePath?.split('/').at(-1) ?? 'unknown';
458
+ const processId = typeof entry.processID === 'number' ? `:${entry.processID}` : '';
459
+ const processLabel = chalk_1.default.cyan(stripTerminalControlCharacters(`[${processName}${processId}]`));
460
+ const level = String(entry.messageType ?? '').toLowerCase();
461
+ let message = stripTerminalControlCharacters(entry.eventMessage, {
462
+ keepNewlinesAndTabs: true,
463
+ });
464
+ if (level === 'error' || level === '16') {
465
+ message = chalk_1.default.red(message);
466
+ }
467
+ else if (level === 'fault' || level === '17') {
468
+ message = chalk_1.default.red.bold(message);
469
+ }
470
+ else if (level === 'debug' || level === '2') {
471
+ message = chalk_1.default.dim(message);
472
+ }
473
+ return `${prefix}${processLabel} ${message}`;
474
+ }
475
+ }
476
+ catch { }
477
+ const prefix = timestamp ? `${chalk_1.default.dim(time)} ` : '';
478
+ return `${prefix}${stripTerminalControlCharacters(raw, { keepNewlinesAndTabs: true })}`;
479
+ }
@@ -1,4 +1,5 @@
1
1
  import { AnalyticsWithOrchestration } from '../analytics/AnalyticsManager';
2
+ import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
2
3
  import { CurrentUserQuery } from '../graphql/generated';
3
4
  export type LoggedInAuthenticationInfo = {
4
5
  accessToken: string;
@@ -11,12 +12,21 @@ type Actor = NonNullable<CurrentUserQuery['meActor']>;
11
12
  export default class SessionManager {
12
13
  private readonly analytics;
13
14
  private currentActor;
15
+ private graphqlClient;
14
16
  constructor(analytics: AnalyticsWithOrchestration);
15
17
  getAccessToken(): string | null;
16
18
  getSessionSecret(): string | null;
17
19
  private getSession;
18
20
  private setSessionAsync;
19
21
  logoutAsync(): Promise<void>;
22
+ /**
23
+ * Returns one GraphQL client per credential, so context fields of one command share
24
+ * the urql cache. For example, the project ID check and the command both query the app.
25
+ */
26
+ getGraphqlClient(authenticationInfo: {
27
+ accessToken: string | null;
28
+ sessionSecret: string | null;
29
+ }): ExpoGraphqlClient;
20
30
  /**
21
31
  * @param requestTimeoutMs caps the actor lookup when no actor is cached yet. Callers that must
22
32
  * not delay a command past a deadline pass it; the default has no timeout. A capped lookup
@@ -18,6 +18,7 @@ const paths_1 = require("../utils/paths");
18
18
  class SessionManager {
19
19
  analytics;
20
20
  currentActor;
21
+ graphqlClient;
21
22
  constructor(analytics) {
22
23
  this.analytics = analytics;
23
24
  }
@@ -59,6 +60,17 @@ class SessionManager {
59
60
  this.currentActor = undefined;
60
61
  await this.setSessionAsync(undefined);
61
62
  }
63
+ /**
64
+ * Returns one GraphQL client per credential, so context fields of one command share
65
+ * the urql cache. For example, the project ID check and the command both query the app.
66
+ */
67
+ getGraphqlClient(authenticationInfo) {
68
+ const credential = authenticationInfo.accessToken ?? authenticationInfo.sessionSecret;
69
+ if (this.graphqlClient?.credential !== credential) {
70
+ this.graphqlClient = { credential, client: (0, createGraphqlClient_1.createGraphqlClient)(authenticationInfo) };
71
+ }
72
+ return this.graphqlClient.client;
73
+ }
62
74
  /**
63
75
  * @param requestTimeoutMs caps the actor lookup when no actor is cached yet. Callers that must
64
76
  * not delay a command past a deadline pass it; the default has no timeout. A capped lookup
@@ -0,0 +1,11 @@
1
+ import { Actor } from './User';
2
+ /**
3
+ * Logs the actor's role on each account, and whether the credentials used for this command limit
4
+ * it. The list is skipped when it only contains the personal account and the credentials do not
5
+ * limit it.
6
+ *
7
+ * @returns whether the credentials limit the permissions on any account
8
+ */
9
+ export declare function logAccountPermissions(actor: Actor): {
10
+ hasLimitedAccount: boolean;
11
+ };
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.logAccountPermissions = logAccountPermissions;
4
+ const tslib_1 = require("tslib");
5
+ const chalk_1 = tslib_1.__importDefault(require("chalk"));
6
+ const generated_1 = require("../graphql/generated");
7
+ const log_1 = tslib_1.__importDefault(require("../log"));
8
+ const roles_1 = require("./roles");
9
+ /**
10
+ * Logs the actor's role on each account, and whether the credentials used for this command limit
11
+ * it. The list is skipped when it only contains the personal account and the credentials do not
12
+ * limit it.
13
+ *
14
+ * @returns whether the credentials limit the permissions on any account
15
+ */
16
+ function logAccountPermissions(actor) {
17
+ // personal account is included, only show if more accounts that personal account
18
+ // but do show personal account in list if there are more, or if the credentials used for
19
+ // this command limit the permissions on it
20
+ const accountExcludingPersonalAccount = actor.accounts.filter(account => !('username' in actor) || account.name !== actor.username);
21
+ const hasLimitedAccount = actor.accounts.some(isLimitedByCredentials);
22
+ if (accountExcludingPersonalAccount.length === 0 && !hasLimitedAccount) {
23
+ return { hasLimitedAccount };
24
+ }
25
+ log_1.default.newLine();
26
+ log_1.default.log('Accounts:');
27
+ actor.accounts.forEach(account => {
28
+ const { permissions, effectivePermissions } = account.viewerUserPermission2;
29
+ const roleLabel = getLabelForPermissions(permissions);
30
+ if (isLimitedByCredentials(account)) {
31
+ const effectiveRoleLabel = getLabelForPermissions(effectivePermissions);
32
+ log_1.default.log(`• ${account.name} (Role: ${roleLabel}, ${chalk_1.default.yellow(`limited to ${effectiveRoleLabel} by the current credentials`)})`);
33
+ }
34
+ else {
35
+ log_1.default.log(`• ${account.name} (Role: ${roleLabel})`);
36
+ }
37
+ });
38
+ return { hasLimitedAccount };
39
+ }
40
+ /**
41
+ * Whether the scopes of the credential used for this command remove any of the permissions that
42
+ * the viewer's role grants on the account.
43
+ */
44
+ function isLimitedByCredentials(account) {
45
+ const { permissions, effectivePermissions } = account.viewerUserPermission2;
46
+ return permissions.some(permission => !effectivePermissions.includes(permission));
47
+ }
48
+ function getLabelForPermissions(permissions) {
49
+ const role = (0, roles_1.getRoleForPermissions)(permissions);
50
+ if (role !== generated_1.Role.Custom) {
51
+ return getLabelForRole(role);
52
+ }
53
+ if (permissions.length === 0) {
54
+ return 'No permissions';
55
+ }
56
+ return `Custom: ${permissions
57
+ .map(permission => permission.toLowerCase().replaceAll('_', ' '))
58
+ .join(', ')}`;
59
+ }
60
+ function getLabelForRole(role) {
61
+ switch (role) {
62
+ case generated_1.Role.Owner:
63
+ return 'Owner';
64
+ case generated_1.Role.Admin:
65
+ return 'Admin';
66
+ case generated_1.Role.Developer:
67
+ return 'Developer';
68
+ case generated_1.Role.ReleaseManager:
69
+ return 'Release Manager';
70
+ case generated_1.Role.Runner:
71
+ return 'Runner';
72
+ case generated_1.Role.ViewOnly:
73
+ return 'Viewer';
74
+ case generated_1.Role.Custom:
75
+ case generated_1.Role.HasAdmin:
76
+ case generated_1.Role.NotAdmin:
77
+ return 'Custom';
78
+ // A role added to the API after this version of the CLI was published. TypeScript narrows
79
+ // `role` to `never` here, but the server can still send one, so render its name rather than
80
+ // returning undefined.
81
+ default: {
82
+ const unknownRole = role;
83
+ return unknownRole
84
+ .split('_')
85
+ .map(word => word.charAt(0) + word.slice(1).toLowerCase())
86
+ .join(' ');
87
+ }
88
+ }
89
+ }