eas-cli 25.1.1 → 25.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +282 -162
  2. package/build/analytics/AnalyticsManager.d.ts +7 -1
  3. package/build/analytics/AnalyticsManager.js +12 -1
  4. package/build/billing/resolveAccount.d.ts +12 -0
  5. package/build/billing/resolveAccount.js +1 -0
  6. package/build/build/build.d.ts +3 -1
  7. package/build/build/build.js +14 -12
  8. package/build/build/context.d.ts +4 -0
  9. package/build/build/createContext.d.ts +5 -1
  10. package/build/build/createContext.js +3 -1
  11. package/build/build/freeTierLimitCheckout.d.ts +39 -0
  12. package/build/build/freeTierLimitCheckout.js +106 -0
  13. package/build/build/freeTierLimitGuidance.d.ts +19 -0
  14. package/build/build/freeTierLimitGuidance.js +39 -0
  15. package/build/build/runBuildAndSubmit.d.ts +7 -1
  16. package/build/build/runBuildAndSubmit.js +6 -2
  17. package/build/build/utils/url.d.ts +1 -0
  18. package/build/build/utils/url.js +4 -0
  19. package/build/commandUtils/EasCommand.d.ts +9 -0
  20. package/build/commandUtils/EasCommand.js +12 -1
  21. package/build/commandUtils/context/ExperimentationContextField.d.ts +13 -0
  22. package/build/commandUtils/context/ExperimentationContextField.js +79 -0
  23. package/build/commandUtils/context/contextUtils/createGraphqlClient.d.ts +3 -0
  24. package/build/commandUtils/context/contextUtils/createGraphqlClient.js +29 -2
  25. package/build/commandUtils/errors.d.ts +5 -1
  26. package/build/commandUtils/errors.js +4 -3
  27. package/build/commands/analytics.js +1 -1
  28. package/build/commands/build/index.d.ts +1 -0
  29. package/build/commands/build/index.js +4 -1
  30. package/build/commands/simulator/control.d.ts +26 -0
  31. package/build/commands/simulator/control.js +250 -0
  32. package/build/commands/simulator/index.d.ts +1 -0
  33. package/build/commands/simulator/index.js +18 -4
  34. package/build/commands/update/republish.d.ts +1 -1
  35. package/build/env.d.ts +6 -0
  36. package/build/env.js +6 -0
  37. package/build/experimentation/AnalyticsExposureLogger.d.ts +7 -0
  38. package/build/experimentation/AnalyticsExposureLogger.js +21 -0
  39. package/build/experimentation/ExperimentNamespace.d.ts +24 -0
  40. package/build/experimentation/ExperimentNamespace.js +69 -0
  41. package/build/experimentation/ExperimentOverrides.d.ts +17 -0
  42. package/build/experimentation/ExperimentOverrides.js +68 -0
  43. package/build/experimentation/ExperimentationClient.d.ts +32 -0
  44. package/build/experimentation/ExperimentationClient.js +125 -0
  45. package/build/experimentation/LazyExperimentationClient.d.ts +12 -0
  46. package/build/experimentation/LazyExperimentationClient.js +22 -0
  47. package/build/graphql/generated.d.ts +12 -0
  48. package/build/graphql/queries/ExperimentationConfigQuery.d.ts +10 -0
  49. package/build/graphql/queries/ExperimentationConfigQuery.js +49 -0
  50. package/build/graphql/queries/UserQuery.d.ts +3 -1
  51. package/build/graphql/queries/UserQuery.js +2 -1
  52. package/build/help.d.ts +4 -0
  53. package/build/help.js +56 -0
  54. package/build/simulator/hostActions.d.ts +70 -0
  55. package/build/simulator/hostActions.js +411 -0
  56. package/build/simulator/utils.d.ts +5 -0
  57. package/build/simulator/utils.js +11 -0
  58. package/build/user/SessionManager.d.ts +8 -1
  59. package/build/user/SessionManager.js +7 -2
  60. package/oclif.manifest.json +917 -3
  61. package/package.json +8 -6
@@ -0,0 +1,411 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.connectHostActionsAsync = connectHostActionsAsync;
4
+ exports.fetchHostActionCatalogAsync = fetchHostActionCatalogAsync;
5
+ exports.formatHostActionUsage = formatHostActionUsage;
6
+ exports.buildHostActionParams = buildHostActionParams;
7
+ exports.assertHostActionOutputAsync = assertHostActionOutputAsync;
8
+ exports.uploadFileAsync = uploadFileAsync;
9
+ exports.saveHostActionOutputAsync = saveHostActionOutputAsync;
10
+ const tslib_1 = require("tslib");
11
+ const crypto_1 = require("crypto");
12
+ const fs = tslib_1.__importStar(require("fs-extra"));
13
+ const path_1 = tslib_1.__importDefault(require("path"));
14
+ const ws_1 = tslib_1.__importDefault(require("ws"));
15
+ const zod_1 = require("zod");
16
+ const fetch_1 = tslib_1.__importStar(require("../fetch"));
17
+ const SchemaNode = zod_1.z.looseObject({
18
+ type: zod_1.z.union([zod_1.z.string(), zod_1.z.array(zod_1.z.string())]).optional(),
19
+ properties: zod_1.z.record(zod_1.z.string(), zod_1.z.unknown()).optional(),
20
+ required: zod_1.z.array(zod_1.z.string()).optional(),
21
+ allOf: zod_1.z.array(zod_1.z.unknown()).optional(),
22
+ anyOf: zod_1.z.array(zod_1.z.unknown()).optional(),
23
+ oneOf: zod_1.z.array(zod_1.z.unknown()).optional(),
24
+ });
25
+ const CatalogEntry = SchemaNode.extend({
26
+ description: zod_1.z.string().optional(),
27
+ args: zod_1.z.array(zod_1.z.string()).optional(),
28
+ upload: zod_1.z.string().optional(),
29
+ uploadAs: zod_1.z.enum(['path', 'id']).optional(),
30
+ uploadWhen: zod_1.z.record(zod_1.z.string(), zod_1.z.unknown()).optional(),
31
+ keepUpload: zod_1.z.boolean().optional(),
32
+ output: zod_1.z.enum(['path', 'base64']).optional(),
33
+ });
34
+ const Catalog = zod_1.z.record(zod_1.z.string(), CatalogEntry);
35
+ const PreviewConfig = zod_1.z.object({ device: zod_1.z.string().min(1) });
36
+ const ReplyId = zod_1.z.object({ id: zod_1.z.number() });
37
+ const SocketMessage = zod_1.z.union([
38
+ zod_1.z.object({ ready: zod_1.z.literal(true) }),
39
+ zod_1.z.object({ id: zod_1.z.number(), error: zod_1.z.string() }),
40
+ zod_1.z.object({
41
+ id: zod_1.z.number(),
42
+ stdout: zod_1.z.string(),
43
+ stderr: zod_1.z.string(),
44
+ exitCode: zod_1.z.number(),
45
+ }),
46
+ ]);
47
+ const HOST_ACTION_TIMEOUT_MS = 130_000;
48
+ const PREVIEW_API_TIMEOUT_MS = 30_000;
49
+ const UPLOAD_CHUNK_BYTES = 2 * 1024 * 1024;
50
+ const NAMED_VALUE = /^([A-Za-z][A-Za-z0-9]*)=(.*)$/s;
51
+ const NUMBER = /^-?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
52
+ function previewEndpoint(apiUrl, endpoint) {
53
+ const base = new URL(apiUrl);
54
+ const loopback = base.hostname === 'localhost' ||
55
+ base.hostname === '[::1]' ||
56
+ /^127(?:\.\d{1,3}){3}$/.test(base.hostname);
57
+ if (base.protocol !== 'https:' && (base.protocol !== 'http:' || !loopback)) {
58
+ throw new Error('Simulator actions require HTTPS for remote preview servers. HTTP is supported only on localhost or a loopback address. Start a new session with `eas simulator:start`.');
59
+ }
60
+ base.search = '';
61
+ base.hash = '';
62
+ if (!base.pathname.endsWith('/')) {
63
+ base.pathname += '/';
64
+ }
65
+ return new URL(endpoint, base);
66
+ }
67
+ async function fetchSimulatorUdidAsync({ apiUrl, token }) {
68
+ let text;
69
+ try {
70
+ const response = await (0, fetch_1.default)(previewEndpoint(apiUrl, 'api').toString(), {
71
+ headers: { Authorization: `Bearer ${token}` },
72
+ redirect: 'error',
73
+ signal: AbortSignal.timeout(PREVIEW_API_TIMEOUT_MS),
74
+ });
75
+ text = await response.text();
76
+ }
77
+ catch (error) {
78
+ if (error instanceof fetch_1.RequestError && [401, 403].includes(error.response.status)) {
79
+ throw new Error(`The simulator preview server refused the session token (HTTP ${error.response.status}). Run \`eas simulator:get\` to check that the session still runs, then try again.`);
80
+ }
81
+ if (error instanceof Error && error.name === 'AbortError') {
82
+ throw new Error(`The simulator preview server did not answer within ${PREVIEW_API_TIMEOUT_MS / 1000} seconds. Run \`eas simulator:get\` to check that the session still runs, then try again.`);
83
+ }
84
+ throw error;
85
+ }
86
+ let body = null;
87
+ try {
88
+ body = JSON.parse(text);
89
+ }
90
+ catch { }
91
+ const config = PreviewConfig.safeParse(body);
92
+ if (!config.success) {
93
+ throw new Error('The simulator preview server did not report which simulator it streams. The session may still be starting. Wait a few seconds and run the command again.');
94
+ }
95
+ return config.data.device;
96
+ }
97
+ function refusedError(error) {
98
+ return error.startsWith('unknown action')
99
+ ? new Error('This simulator session runs a serve-sim version that does not support this action. Start a new session with `eas simulator:start` to get a newer version.')
100
+ : new Error(`The simulator refused the request: ${error}`);
101
+ }
102
+ async function connectHostActionsAsync(access, { timeoutMs = HOST_ACTION_TIMEOUT_MS } = {}) {
103
+ const udid = await fetchSimulatorUdidAsync(access);
104
+ const socketUrl = previewEndpoint(access.apiUrl, 'exec-ws');
105
+ socketUrl.protocol = socketUrl.protocol === 'https:' ? 'wss:' : 'ws:';
106
+ const ws = new ws_1.default(socketUrl.toString(), [`serve-sim.token.${access.token}`], fetch_1.httpsProxyAgent ? { agent: fetch_1.httpsProxyAgent } : {});
107
+ const pending = new Map();
108
+ let nextId = 1;
109
+ let lost = null;
110
+ let ready = false;
111
+ function settle(id) {
112
+ const request = pending.get(id);
113
+ if (request) {
114
+ pending.delete(id);
115
+ clearTimeout(request.timer);
116
+ }
117
+ return request;
118
+ }
119
+ function loseConnection(error) {
120
+ lost ??= error;
121
+ for (const id of [...pending.keys()]) {
122
+ settle(id)?.reject(error);
123
+ }
124
+ }
125
+ await new Promise((resolve, reject) => {
126
+ const timer = setTimeout(() => {
127
+ reject(new Error(`The simulator preview server did not accept the connection within ${PREVIEW_API_TIMEOUT_MS / 1000} seconds. Check that the session still runs with \`eas simulator:get\`, then try again.`));
128
+ ws.terminate();
129
+ }, PREVIEW_API_TIMEOUT_MS);
130
+ const fail = (error) => {
131
+ clearTimeout(timer);
132
+ reject(error);
133
+ loseConnection(error);
134
+ if (!ready) {
135
+ ws.terminate();
136
+ }
137
+ };
138
+ ws.on('message', data => {
139
+ let message;
140
+ try {
141
+ message = JSON.parse(data.toString());
142
+ }
143
+ catch {
144
+ return;
145
+ }
146
+ const parsed = SocketMessage.safeParse(message);
147
+ if (!parsed.success) {
148
+ const id = ReplyId.safeParse(message);
149
+ if (id.success) {
150
+ settle(id.data.id)?.reject(new Error('The simulator preview server sent a reply that this version of eas-cli cannot read. Update eas-cli and try again.'));
151
+ }
152
+ return;
153
+ }
154
+ const reply = parsed.data;
155
+ if ('ready' in reply) {
156
+ ready = true;
157
+ clearTimeout(timer);
158
+ resolve();
159
+ }
160
+ else if ('error' in reply) {
161
+ settle(reply.id)?.reject(refusedError(reply.error));
162
+ }
163
+ else {
164
+ settle(reply.id)?.resolve({
165
+ stdout: reply.stdout,
166
+ stderr: reply.stderr,
167
+ exitCode: reply.exitCode,
168
+ });
169
+ }
170
+ });
171
+ ws.on('unexpected-response', (_req, res) => {
172
+ res.destroy();
173
+ fail(new Error(`The simulator preview server refused the connection (HTTP ${res.statusCode}). The session token may be out of date. Run \`eas simulator:get\` to check the session, then try again.`));
174
+ });
175
+ ws.on('error', error => {
176
+ fail(new Error(`Could not connect to the simulator preview server: ${error.message}. Check your network connection and that the session still runs.`));
177
+ });
178
+ ws.on('close', () => {
179
+ fail(new Error(ready
180
+ ? 'The simulator preview server closed the connection before it answered. The action may still have run. Check the current state before you try again.'
181
+ : 'The simulator preview server closed the connection during setup. The session token may be invalid or expired, or the session may run an older serve-sim version. Check the session with `eas simulator:get` before starting a new session.'));
182
+ });
183
+ });
184
+ return {
185
+ async requestAsync(action, params = {}) {
186
+ if (lost) {
187
+ throw lost;
188
+ }
189
+ const id = nextId++;
190
+ return await new Promise((resolve, reject) => {
191
+ const timer = setTimeout(() => {
192
+ settle(id)?.reject(new Error(`The simulator did not answer within ${Math.round(timeoutMs / 1000)} seconds. The action may still have run. Check the session with \`eas simulator:get\` and the current state before you try again.`));
193
+ }, timeoutMs);
194
+ pending.set(id, { resolve, reject, timer });
195
+ ws.send(JSON.stringify({ id, action, params: { ...params, udid } }));
196
+ });
197
+ },
198
+ close() {
199
+ ws.close();
200
+ },
201
+ };
202
+ }
203
+ async function fetchHostActionCatalogAsync(connection) {
204
+ const result = await connection.requestAsync('actions.describe');
205
+ let body = null;
206
+ try {
207
+ body = JSON.parse(result.stdout);
208
+ }
209
+ catch { }
210
+ const catalog = Catalog.safeParse(body);
211
+ if (result.exitCode !== 0 || !catalog.success) {
212
+ throw new Error('The simulator did not return its list of actions. Start a new session with `eas simulator:start` to get a newer serve-sim version.');
213
+ }
214
+ return catalog.data;
215
+ }
216
+ function collectProperties(node, into) {
217
+ const parsed = SchemaNode.safeParse(node);
218
+ if (!parsed.success) {
219
+ return;
220
+ }
221
+ for (const [name, schema] of Object.entries(parsed.data.properties ?? {})) {
222
+ into.set(name, [...(into.get(name) ?? []), schema]);
223
+ }
224
+ const { allOf = [], anyOf = [], oneOf = [] } = parsed.data;
225
+ for (const child of [...allOf, ...anyOf, ...oneOf]) {
226
+ collectProperties(child, into);
227
+ }
228
+ }
229
+ function hostActionProperties(entry) {
230
+ const properties = new Map();
231
+ collectProperties(entry, properties);
232
+ properties.delete('udid');
233
+ return properties;
234
+ }
235
+ function positionalNames(entry) {
236
+ return entry.args ?? Object.keys(entry.properties ?? {}).filter(name => name !== 'udid');
237
+ }
238
+ function requiredProperties(node) {
239
+ const parsed = SchemaNode.safeParse(node);
240
+ if (!parsed.success) {
241
+ return new Set();
242
+ }
243
+ const required = new Set(parsed.data.required ?? []);
244
+ for (const child of parsed.data.allOf ?? []) {
245
+ requiredProperties(child).forEach(name => required.add(name));
246
+ }
247
+ const branches = [...(parsed.data.anyOf ?? []), ...(parsed.data.oneOf ?? [])].map(requiredProperties);
248
+ for (const name of branches[0] ?? []) {
249
+ if (branches.every(branch => branch.has(name))) {
250
+ required.add(name);
251
+ }
252
+ }
253
+ return required;
254
+ }
255
+ function acceptsType(schema, types) {
256
+ const node = SchemaNode.safeParse(schema);
257
+ if (!node.success) {
258
+ return false;
259
+ }
260
+ const own = [node.data.type ?? []].flat();
261
+ return (own.some(type => types.includes(type)) ||
262
+ [...(node.data.anyOf ?? []), ...(node.data.oneOf ?? [])].some(child => acceptsType(child, types)));
263
+ }
264
+ function coerce(value, schemas) {
265
+ if (/^[[{]/.test(value) && schemas.some(schema => acceptsType(schema, ['array', 'object']))) {
266
+ try {
267
+ return JSON.parse(value);
268
+ }
269
+ catch {
270
+ return value;
271
+ }
272
+ }
273
+ if (NUMBER.test(value) && schemas.some(schema => acceptsType(schema, ['number', 'integer']))) {
274
+ return Number(value);
275
+ }
276
+ if ((value === 'true' || value === 'false') &&
277
+ schemas.some(schema => acceptsType(schema, ['boolean']))) {
278
+ return value === 'true';
279
+ }
280
+ return value;
281
+ }
282
+ function formatHostActionUsage(name, entry) {
283
+ const required = requiredProperties(entry);
284
+ const alternatives = (entry.anyOf ?? entry.oneOf ?? []).map(branch => [...requiredProperties(branch)].filter(property => property !== 'udid' && !required.has(property)));
285
+ const requiredAlternatives = alternatives.length > 0 && alternatives.every(properties => properties.length === 1)
286
+ ? alternatives.map(([property]) => property)
287
+ : [];
288
+ let describedAlternatives = false;
289
+ const names = positionalNames(entry).flatMap(property => {
290
+ if (requiredAlternatives.includes(property)) {
291
+ if (describedAlternatives) {
292
+ return [];
293
+ }
294
+ describedAlternatives = true;
295
+ return [
296
+ `<${requiredAlternatives.map(name => (name === property ? name : `${name}=...`)).join('|')}>`,
297
+ ];
298
+ }
299
+ return [required.has(property) ? `<${property}>` : `[${property}]`];
300
+ });
301
+ return [name, ...names].join(' ');
302
+ }
303
+ function buildHostActionParams(name, entry, values) {
304
+ const properties = hostActionProperties(entry);
305
+ const params = {};
306
+ const positional = [];
307
+ for (const value of values) {
308
+ const named = NAMED_VALUE.exec(value);
309
+ if (!named || !properties.has(named[1])) {
310
+ positional.push(value);
311
+ }
312
+ else if (Object.hasOwn(params, named[1])) {
313
+ throw new Error(`${named[1]} is given twice for ${name}.`);
314
+ }
315
+ else {
316
+ params[named[1]] = coerce(named[2], properties.get(named[1]) ?? []);
317
+ }
318
+ }
319
+ const open = positionalNames(entry).filter(property => !Object.hasOwn(params, property));
320
+ if (positional.length > open.length) {
321
+ throw new Error(`Too many values for ${name}. Usage: eas simulator:control ${formatHostActionUsage(name, entry)}. Name a value with name=value.`);
322
+ }
323
+ positional.forEach((value, index) => {
324
+ params[open[index]] = coerce(value, properties.get(open[index]) ?? []);
325
+ });
326
+ return params;
327
+ }
328
+ async function assertHostActionOutputAsync(name, entry, outputPath) {
329
+ if (!outputPath) {
330
+ if (entry.output === 'base64') {
331
+ throw new Error(`${name} returns a file. Pass --output with the path to save it to.`);
332
+ }
333
+ return;
334
+ }
335
+ if (!entry.output) {
336
+ throw new Error(`${name} does not return a file, so --output does not apply.`);
337
+ }
338
+ if ((await fs.stat(outputPath).catch(() => null))?.isDirectory()) {
339
+ if (entry.output === 'base64') {
340
+ throw new Error(`${outputPath} is a folder. Pass --output with a file path for ${name}.`);
341
+ }
342
+ return;
343
+ }
344
+ const folder = await fs.stat(path_1.default.dirname(outputPath)).catch(() => null);
345
+ if (outputPath.endsWith('/') || outputPath.endsWith(path_1.default.sep) || !folder?.isDirectory()) {
346
+ throw new Error(`The folder for ${outputPath} does not exist. Create it, or pass --output with a path in a folder that exists.`);
347
+ }
348
+ }
349
+ async function uploadFileAsync(connection, localPath, { chunkBytes = UPLOAD_CHUNK_BYTES } = {}) {
350
+ const uploadId = `eas-cli-${(0, crypto_1.randomUUID)()}${path_1.default.extname(localPath).replace(/[^A-Za-z0-9.]/g, '')}`;
351
+ let remotePath = '';
352
+ let first = true;
353
+ try {
354
+ for await (const chunk of fs.createReadStream(localPath, { highWaterMark: chunkBytes })) {
355
+ const result = await connection.requestAsync('upload.append', {
356
+ uploadId,
357
+ data: Buffer.from(chunk).toString('base64'),
358
+ first,
359
+ });
360
+ if (result.exitCode !== 0) {
361
+ throw new Error(`Could not upload ${localPath}: ${result.stderr.trim()}`);
362
+ }
363
+ remotePath = result.stdout.trim();
364
+ first = false;
365
+ }
366
+ }
367
+ catch (error) {
368
+ await connection.requestAsync('upload.remove', { uploadId }).catch(() => { });
369
+ throw error;
370
+ }
371
+ if (first) {
372
+ throw new Error(`${localPath} is empty. Pass a file with content.`);
373
+ }
374
+ return { uploadId, path: remotePath };
375
+ }
376
+ async function saveHostActionOutputAsync(connection, entry, stdout, outputPath) {
377
+ if (!entry.output) {
378
+ return null;
379
+ }
380
+ let base64 = stdout;
381
+ let defaultName;
382
+ if (entry.output === 'path') {
383
+ const remotePath = stdout.trim();
384
+ const file = await connection.requestAsync('file.readBase64', { path: remotePath });
385
+ if (file.exitCode !== 0) {
386
+ throw new Error(`Could not download ${remotePath}: ${file.stderr.trim()}`);
387
+ }
388
+ base64 = file.stdout;
389
+ defaultName = path_1.default.basename(remotePath);
390
+ }
391
+ const outputIsFolder = outputPath
392
+ ? (await fs.stat(outputPath).catch(() => null))?.isDirectory()
393
+ : false;
394
+ const generatedName = outputIsFolder || !outputPath ? defaultName : undefined;
395
+ const target = generatedName ? path_1.default.join(outputPath ?? '.', generatedName) : outputPath;
396
+ if (!target) {
397
+ throw new Error('Pass --output with a file path to save the file.');
398
+ }
399
+ try {
400
+ await fs.writeFile(target, Buffer.from(base64, 'base64'), {
401
+ flag: target === outputPath ? 'w' : 'wx',
402
+ });
403
+ }
404
+ catch (error) {
405
+ if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'EEXIST') {
406
+ throw new Error(`${target} already exists. Pass --output with a new path to save the file.`);
407
+ }
408
+ throw error;
409
+ }
410
+ return path_1.default.resolve(target);
411
+ }
@@ -54,6 +54,11 @@ export type LocalEgressOptions = {
54
54
  * from the worker.
55
55
  */
56
56
  export declare function getLocalEgressConfig(remoteConfig: DeviceRunSessionRemoteConfig, allow?: readonly string[], platform?: AppPlatform): LocalEgressConfig | null;
57
+ export type PreviewApiAccess = {
58
+ apiUrl: string;
59
+ token: string;
60
+ };
61
+ export declare function getPreviewApiAccess(remoteConfig: DeviceRunSessionRemoteConfig): PreviewApiAccess | null;
57
62
  /** The worker relay that the Android emulator's proxy points at; see build-tools androidLocalEgress.ts. */
58
63
  export declare const ANDROID_EMULATOR_EGRESS_RELAY_PORT = 8898;
59
64
  export type LoopbackForwardPlan = {
@@ -5,6 +5,7 @@ exports.formatSimulatorUnavailableMessage = formatSimulatorUnavailableMessage;
5
5
  exports.deviceRunSessionTypesForFlagValue = deviceRunSessionTypesForFlagValue;
6
6
  exports.deviceRunSessionTypeToFlagValue = deviceRunSessionTypeToFlagValue;
7
7
  exports.getLocalEgressConfig = getLocalEgressConfig;
8
+ exports.getPreviewApiAccess = getPreviewApiAccess;
8
9
  exports.getLoopbackForwardPlan = getLoopbackForwardPlan;
9
10
  exports.formatLoopbackForwardNotice = formatLoopbackForwardNotice;
10
11
  exports.getLocalEgressEnvironmentVariables = getLocalEgressEnvironmentVariables;
@@ -76,6 +77,16 @@ function getLocalEgressConfig(remoteConfig, allow = [], platform = generated_1.A
76
77
  platform,
77
78
  };
78
79
  }
80
+ function getPreviewApiAccess(remoteConfig) {
81
+ const token = remoteConfig.__typename === 'ServeSimRunSessionRemoteConfig' ||
82
+ remoteConfig.__typename === 'WebPreviewOnlyRunSessionRemoteConfig'
83
+ ? remoteConfig.previewToken
84
+ : remoteConfig.webPreviewToken;
85
+ if (!remoteConfig.previewApiUrl || !token) {
86
+ return null;
87
+ }
88
+ return { apiUrl: remoteConfig.previewApiUrl, token };
89
+ }
79
90
  /** The worker relay that the Android emulator's proxy points at; see build-tools androidLocalEgress.ts. */
80
91
  exports.ANDROID_EMULATOR_EGRESS_RELAY_PORT = 8898;
81
92
  /**
@@ -17,7 +17,14 @@ export default class SessionManager {
17
17
  private getSession;
18
18
  private setSessionAsync;
19
19
  logoutAsync(): Promise<void>;
20
- getUserAsync(): Promise<Actor | undefined>;
20
+ /**
21
+ * @param requestTimeoutMs caps the actor lookup when no actor is cached yet. Callers that must
22
+ * not delay a command past a deadline pass it; the default has no timeout. A capped lookup
23
+ * also skips the retry exchange, since a retry would double the wait.
24
+ */
25
+ getUserAsync({ requestTimeoutMs }?: {
26
+ requestTimeoutMs?: number;
27
+ }): Promise<Actor | undefined>;
21
28
  /**
22
29
  * Ensure that there is a logged-in actor. Show a login prompt if not.
23
30
  *
@@ -59,13 +59,18 @@ class SessionManager {
59
59
  this.currentActor = undefined;
60
60
  await this.setSessionAsync(undefined);
61
61
  }
62
- async getUserAsync() {
62
+ /**
63
+ * @param requestTimeoutMs caps the actor lookup when no actor is cached yet. Callers that must
64
+ * not delay a command past a deadline pass it; the default has no timeout. A capped lookup
65
+ * also skips the retry exchange, since a retry would double the wait.
66
+ */
67
+ async getUserAsync({ requestTimeoutMs } = {}) {
63
68
  if (!this.currentActor && (this.getAccessToken() || this.getSessionSecret())) {
64
69
  const authenticationInfo = {
65
70
  accessToken: this.getAccessToken(),
66
71
  sessionSecret: this.getSessionSecret(),
67
72
  };
68
- const actor = await UserQuery_1.UserQuery.currentUserAsync((0, createGraphqlClient_1.createGraphqlClient)(authenticationInfo));
73
+ const actor = await UserQuery_1.UserQuery.currentUserAsync((0, createGraphqlClient_1.createGraphqlClient)(authenticationInfo, { requestTimeoutMs }), { noRetry: requestTimeoutMs !== undefined });
69
74
  this.currentActor = actor ?? undefined;
70
75
  if (actor) {
71
76
  this.analytics.setActor(actor);