eas-cli 25.0.0 → 25.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.
Files changed (60) hide show
  1. package/README.md +285 -150
  2. package/build/analytics/AnalyticsManager.d.ts +6 -1
  3. package/build/analytics/AnalyticsManager.js +11 -1
  4. package/build/build/build.d.ts +2 -1
  5. package/build/build/build.js +5 -4
  6. package/build/build/context.d.ts +2 -0
  7. package/build/build/createContext.d.ts +3 -1
  8. package/build/build/createContext.js +2 -1
  9. package/build/build/freeTierLimitGuidance.d.ts +19 -0
  10. package/build/build/freeTierLimitGuidance.js +39 -0
  11. package/build/build/runBuildAndSubmit.d.ts +4 -1
  12. package/build/build/runBuildAndSubmit.js +4 -2
  13. package/build/commandUtils/EasCommand.d.ts +9 -0
  14. package/build/commandUtils/EasCommand.js +9 -0
  15. package/build/commandUtils/context/ExperimentationContextField.d.ts +13 -0
  16. package/build/commandUtils/context/ExperimentationContextField.js +79 -0
  17. package/build/commandUtils/context/contextUtils/createGraphqlClient.d.ts +3 -0
  18. package/build/commandUtils/context/contextUtils/createGraphqlClient.js +29 -2
  19. package/build/commandUtils/usageUtils.d.ts +14 -0
  20. package/build/commandUtils/usageUtils.js +40 -2
  21. package/build/commands/account/usage.js +55 -2
  22. package/build/commands/analytics.js +1 -1
  23. package/build/commands/build/index.d.ts +1 -0
  24. package/build/commands/build/index.js +3 -1
  25. package/build/commands/simulator/control.d.ts +26 -0
  26. package/build/commands/simulator/control.js +250 -0
  27. package/build/commands/simulator/index.d.ts +2 -0
  28. package/build/commands/simulator/index.js +28 -1
  29. package/build/commands/update/republish.d.ts +1 -1
  30. package/build/env.d.ts +6 -0
  31. package/build/env.js +6 -0
  32. package/build/experimentation/AnalyticsExposureLogger.d.ts +7 -0
  33. package/build/experimentation/AnalyticsExposureLogger.js +21 -0
  34. package/build/experimentation/ExperimentNamespace.d.ts +24 -0
  35. package/build/experimentation/ExperimentNamespace.js +69 -0
  36. package/build/experimentation/ExperimentOverrides.d.ts +17 -0
  37. package/build/experimentation/ExperimentOverrides.js +68 -0
  38. package/build/experimentation/ExperimentationClient.d.ts +32 -0
  39. package/build/experimentation/ExperimentationClient.js +125 -0
  40. package/build/experimentation/LazyExperimentationClient.d.ts +12 -0
  41. package/build/experimentation/LazyExperimentationClient.js +22 -0
  42. package/build/graphql/generated.d.ts +124 -0
  43. package/build/graphql/queries/AccountQuery.js +25 -0
  44. package/build/graphql/queries/ExperimentationConfigQuery.d.ts +10 -0
  45. package/build/graphql/queries/ExperimentationConfigQuery.js +49 -0
  46. package/build/graphql/queries/UserQuery.d.ts +3 -1
  47. package/build/graphql/queries/UserQuery.js +2 -1
  48. package/build/graphql/types/Account.js +5 -0
  49. package/build/help.d.ts +4 -0
  50. package/build/help.js +56 -0
  51. package/build/simulator/frameAncestors.d.ts +9 -0
  52. package/build/simulator/frameAncestors.js +66 -0
  53. package/build/simulator/hostActions.d.ts +70 -0
  54. package/build/simulator/hostActions.js +411 -0
  55. package/build/simulator/utils.d.ts +19 -2
  56. package/build/simulator/utils.js +68 -8
  57. package/build/user/SessionManager.d.ts +8 -1
  58. package/build/user/SessionManager.js +7 -2
  59. package/oclif.manifest.json +1164 -243
  60. package/package.json +8 -6
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ /**
3
+ * `--frame-ancestor` and `--cors-origin` values: origins of pages that may embed the simulator
4
+ * preview host in a frame, or call its API cross-origin. The server applies the same rules;
5
+ * checking here gives a fast, local error.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.MAX_CORS_ORIGINS = exports.MAX_FRAME_ANCESTORS = void 0;
9
+ exports.parseFrameAncestorList = parseFrameAncestorList;
10
+ exports.parseCorsOriginList = parseCorsOriginList;
11
+ exports.MAX_FRAME_ANCESTORS = 10;
12
+ exports.MAX_CORS_ORIGINS = 10;
13
+ // The shapes serve-sim and expo-device-hub accept: a host, an IPv6 literal, or a subdomain
14
+ // wildcard with at least two labels after the star.
15
+ const FRAMEABLE_HOSTNAME_PATTERN = /^(?:\[[0-9a-f:.]+\]|[a-z0-9.-]+|\*\.[a-z0-9-]+(?:\.[a-z0-9-]+)+)$/i;
16
+ const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]']);
17
+ function parseFrameAncestorList(entries) {
18
+ return parseOriginList(entries, {
19
+ flag: '--frame-ancestor',
20
+ maxCount: exports.MAX_FRAME_ANCESTORS,
21
+ purpose: 'embeds the preview',
22
+ });
23
+ }
24
+ function parseCorsOriginList(entries) {
25
+ return parseOriginList(entries, {
26
+ flag: '--cors-origin',
27
+ maxCount: exports.MAX_CORS_ORIGINS,
28
+ purpose: 'calls the preview API',
29
+ });
30
+ }
31
+ function parseOriginList(entries, { flag, maxCount, purpose }) {
32
+ if (entries.length > maxCount) {
33
+ throw new Error(`${flag} accepts at most ${maxCount} origins; received ${entries.length}. ` +
34
+ `Keep only the origins of pages that ${purpose}.`);
35
+ }
36
+ return [...new Set(entries.map(entry => parseOrigin(entry, flag, purpose)))];
37
+ }
38
+ function parseOrigin(entry, flag, purpose) {
39
+ const value = entry.trim();
40
+ let url;
41
+ try {
42
+ url = new URL(value);
43
+ }
44
+ catch {
45
+ throw new Error(`${flag} ${entry} is not a URL. Pass the origin of the page that ${purpose}, ` +
46
+ 'such as https://app.example.com, or a subdomain wildcard such as https://*.example.com.');
47
+ }
48
+ if (url.pathname !== '/' ||
49
+ url.search !== '' ||
50
+ url.hash !== '' ||
51
+ url.username !== '' ||
52
+ url.password !== '') {
53
+ throw new Error(`${flag} ${entry} must be an origin only. Browsers match origins by scheme, host and port, ` +
54
+ `so drop the path, query, hash and credentials: ${url.origin}.`);
55
+ }
56
+ const isLoopback = LOOPBACK_HOSTNAMES.has(url.hostname);
57
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopback)) {
58
+ throw new Error(`${flag} ${entry} must use https. The preview is served over https, and browsers do not ` +
59
+ 'let an http page use it. Plain http is accepted for localhost only.');
60
+ }
61
+ if (!FRAMEABLE_HOSTNAME_PATTERN.test(url.hostname)) {
62
+ throw new Error(`${flag} ${entry} has a host the preview host cannot allow. Use a hostname, an IPv6 ` +
63
+ 'literal, or a subdomain wildcard with at least two labels after the star, such as https://*.example.com.');
64
+ }
65
+ return url.origin;
66
+ }
@@ -0,0 +1,70 @@
1
+ import { z } from 'zod';
2
+ import { PreviewApiAccess } from './utils';
3
+ export type HostActionResult = {
4
+ stdout: string;
5
+ stderr: string;
6
+ exitCode: number;
7
+ };
8
+ export type HostActionConnection = {
9
+ requestAsync(action: string, params?: Record<string, unknown>): Promise<HostActionResult>;
10
+ close(): void;
11
+ };
12
+ declare const CatalogEntry: z.ZodObject<{
13
+ type: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>;
14
+ properties: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
15
+ required: z.ZodOptional<z.ZodArray<z.ZodString>>;
16
+ allOf: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
17
+ anyOf: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
18
+ oneOf: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
19
+ description: z.ZodOptional<z.ZodString>;
20
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
21
+ upload: z.ZodOptional<z.ZodString>;
22
+ uploadAs: z.ZodOptional<z.ZodEnum<{
23
+ path: "path";
24
+ id: "id";
25
+ }>>;
26
+ uploadWhen: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
27
+ keepUpload: z.ZodOptional<z.ZodBoolean>;
28
+ output: z.ZodOptional<z.ZodEnum<{
29
+ path: "path";
30
+ base64: "base64";
31
+ }>>;
32
+ }, z.core.$loose>;
33
+ declare const Catalog: z.ZodRecord<z.ZodString, z.ZodObject<{
34
+ type: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>;
35
+ properties: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
36
+ required: z.ZodOptional<z.ZodArray<z.ZodString>>;
37
+ allOf: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
38
+ anyOf: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
39
+ oneOf: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
40
+ description: z.ZodOptional<z.ZodString>;
41
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
42
+ upload: z.ZodOptional<z.ZodString>;
43
+ uploadAs: z.ZodOptional<z.ZodEnum<{
44
+ path: "path";
45
+ id: "id";
46
+ }>>;
47
+ uploadWhen: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
48
+ keepUpload: z.ZodOptional<z.ZodBoolean>;
49
+ output: z.ZodOptional<z.ZodEnum<{
50
+ path: "path";
51
+ base64: "base64";
52
+ }>>;
53
+ }, z.core.$loose>>;
54
+ export type HostActionCatalog = z.infer<typeof Catalog>;
55
+ export type HostActionCatalogEntry = z.infer<typeof CatalogEntry>;
56
+ export declare function connectHostActionsAsync(access: PreviewApiAccess, { timeoutMs }?: {
57
+ timeoutMs?: number;
58
+ }): Promise<HostActionConnection>;
59
+ export declare function fetchHostActionCatalogAsync(connection: HostActionConnection): Promise<HostActionCatalog>;
60
+ export declare function formatHostActionUsage(name: string, entry: HostActionCatalogEntry): string;
61
+ export declare function buildHostActionParams(name: string, entry: HostActionCatalogEntry, values: string[]): Record<string, unknown>;
62
+ export declare function assertHostActionOutputAsync(name: string, entry: HostActionCatalogEntry, outputPath: string | undefined): Promise<void>;
63
+ export declare function uploadFileAsync(connection: HostActionConnection, localPath: string, { chunkBytes }?: {
64
+ chunkBytes?: number;
65
+ }): Promise<{
66
+ uploadId: string;
67
+ path: string;
68
+ }>;
69
+ export declare function saveHostActionOutputAsync(connection: HostActionConnection, entry: HostActionCatalogEntry, stdout: string, outputPath: string | undefined): Promise<string | null>;
70
+ export {};
@@ -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 = {
@@ -84,7 +89,12 @@ type RemoteSessionInstructionsConfigType = 'env' | 'dotenv';
84
89
  type PreviewLinkOptions = {
85
90
  privatePreviewUrl?: string;
86
91
  publicLink?: boolean;
92
+ /** Origins the session allows to embed the preview host; the embed URL is printed for them. */
93
+ frameAncestors?: readonly string[];
94
+ /** Origins the session allows to call the preview host API; the embed URL is printed for them. */
95
+ corsOrigins?: readonly string[];
87
96
  };
97
+ export type PreviewAccessOrigins = Pick<PreviewLinkOptions, 'frameAncestors' | 'corsOrigins'>;
88
98
  /**
89
99
  * Preview link for a session. A gated preview needs the session token, and a browser cannot send
90
100
  * a header on a page load. The expo.dev preview page reads it from the fragment, which no request
@@ -94,7 +104,14 @@ export declare function formatPreviewUrl(remoteConfig: DeviceRunSessionRemoteCon
94
104
  /**
95
105
  * Remote config for `--json`. Private sessions omit the direct preview API address and preview
96
106
  * tokens. Public sessions include bearer preview links while preserving controller credentials.
107
+ * A session with frame ancestors or CORS origins also includes the preview API address, since
108
+ * the page on those origins needs it.
109
+ */
110
+ export declare function sanitizeRemoteConfigForJson(remoteConfig: DeviceRunSessionRemoteConfig, privatePreviewUrl: string, publicLink?: boolean, { frameAncestors, corsOrigins }?: PreviewAccessOrigins): DeviceRunSessionRemoteConfig;
111
+ /**
112
+ * The preview host address with the session token, which an embedding page loads directly. The
113
+ * expo.dev preview page cannot be framed by other sites. Null until the worker reports the host.
97
114
  */
98
- export declare function sanitizeRemoteConfigForJson(remoteConfig: DeviceRunSessionRemoteConfig, privatePreviewUrl: string, publicLink?: boolean): DeviceRunSessionRemoteConfig;
99
- export declare function formatRemoteSessionInstructions(remoteConfig: DeviceRunSessionRemoteConfig, configType: RemoteSessionInstructionsConfigType, { egressAllow, egressClientRunsInline, sessionUrl, platform, privatePreviewUrl, publicLink, }?: LocalEgressOptions & PreviewLinkOptions): string;
115
+ export declare function formatEmbedPreviewUrl(remoteConfig: DeviceRunSessionRemoteConfig): string | null;
116
+ export declare function formatRemoteSessionInstructions(remoteConfig: DeviceRunSessionRemoteConfig, configType: RemoteSessionInstructionsConfigType, { egressAllow, egressClientRunsInline, sessionUrl, platform, privatePreviewUrl, publicLink, frameAncestors, corsOrigins, }?: LocalEgressOptions & PreviewLinkOptions): string;
100
117
  export {};