eas-cli 25.1.1 → 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 (51) hide show
  1. package/README.md +246 -144
  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/commands/analytics.js +1 -1
  20. package/build/commands/build/index.d.ts +1 -0
  21. package/build/commands/build/index.js +3 -1
  22. package/build/commands/simulator/control.d.ts +26 -0
  23. package/build/commands/simulator/control.js +250 -0
  24. package/build/commands/update/republish.d.ts +1 -1
  25. package/build/env.d.ts +6 -0
  26. package/build/env.js +6 -0
  27. package/build/experimentation/AnalyticsExposureLogger.d.ts +7 -0
  28. package/build/experimentation/AnalyticsExposureLogger.js +21 -0
  29. package/build/experimentation/ExperimentNamespace.d.ts +24 -0
  30. package/build/experimentation/ExperimentNamespace.js +69 -0
  31. package/build/experimentation/ExperimentOverrides.d.ts +17 -0
  32. package/build/experimentation/ExperimentOverrides.js +68 -0
  33. package/build/experimentation/ExperimentationClient.d.ts +32 -0
  34. package/build/experimentation/ExperimentationClient.js +125 -0
  35. package/build/experimentation/LazyExperimentationClient.d.ts +12 -0
  36. package/build/experimentation/LazyExperimentationClient.js +22 -0
  37. package/build/graphql/generated.d.ts +12 -0
  38. package/build/graphql/queries/ExperimentationConfigQuery.d.ts +10 -0
  39. package/build/graphql/queries/ExperimentationConfigQuery.js +49 -0
  40. package/build/graphql/queries/UserQuery.d.ts +3 -1
  41. package/build/graphql/queries/UserQuery.js +2 -1
  42. package/build/help.d.ts +4 -0
  43. package/build/help.js +56 -0
  44. package/build/simulator/hostActions.d.ts +70 -0
  45. package/build/simulator/hostActions.js +411 -0
  46. package/build/simulator/utils.d.ts +5 -0
  47. package/build/simulator/utils.js +11 -0
  48. package/build/user/SessionManager.d.ts +8 -1
  49. package/build/user/SessionManager.js +7 -2
  50. package/oclif.manifest.json +1110 -203
  51. package/package.json +8 -6
@@ -0,0 +1,250 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const core_1 = require("@oclif/core");
5
+ const chalk_1 = tslib_1.__importDefault(require("chalk"));
6
+ const fs = tslib_1.__importStar(require("fs-extra"));
7
+ const path_1 = tslib_1.__importDefault(require("path"));
8
+ const EasCommand_1 = tslib_1.__importDefault(require("../../commandUtils/EasCommand"));
9
+ const flags_1 = require("../../commandUtils/flags");
10
+ const generated_1 = require("../../graphql/generated");
11
+ const DeviceRunSessionQuery_1 = require("../../graphql/queries/DeviceRunSessionQuery");
12
+ const log_1 = tslib_1.__importDefault(require("../../log"));
13
+ const ora_1 = require("../../ora");
14
+ const env_1 = require("../../simulator/env");
15
+ const hostActions_1 = require("../../simulator/hostActions");
16
+ const utils_1 = require("../../simulator/utils");
17
+ const json_1 = require("../../utils/json");
18
+ class SimulatorControl extends EasCommand_1.default {
19
+ static aliases = ['sim:control'];
20
+ static description = '[EXPERIMENTAL] run a serve-sim action on a remote iOS simulator session on EAS. Run without an action to list the actions the session supports. To save a screenshot locally, run `eas simulator:control screenshot.capture --output ./screenshot.png`.';
21
+ static strict = false;
22
+ static examples = [
23
+ '$ eas simulator:control',
24
+ '$ eas simulator:control --id <session-id>',
25
+ '$ eas simulator:control screenshot.capture --help',
26
+ '$ eas simulator:control clipboard.write -- --some-text',
27
+ '$ eas simulator:control hardwareKeyboard.set off',
28
+ '$ eas simulator:control permissions.set grant camera com.example.app',
29
+ '$ eas simulator:control app.install ./MyApp.ipa',
30
+ '$ eas simulator:control screenshot.capture --output ./screenshot.png',
31
+ '$ eas simulator:control screenshot.capture --output ./screenshot.png --id <session-id>',
32
+ ];
33
+ static args = {
34
+ action: core_1.Args.string({
35
+ description: 'Action to run, followed by its values in order or as name=value. Omit to list the actions. Put -- before values that start with --.',
36
+ }),
37
+ };
38
+ static flags = {
39
+ help: core_1.Flags.boolean({
40
+ char: 'h',
41
+ description: 'Show command help, or usage for the selected action from the session.',
42
+ }),
43
+ id: core_1.Flags.string({
44
+ description: `Simulator session ID. Defaults to ${env_1.SIMULATOR_DOTENV_FILE_NAME}.`,
45
+ }),
46
+ list: core_1.Flags.boolean({
47
+ description: 'List the actions the session supports.',
48
+ }),
49
+ output: core_1.Flags.string({
50
+ description: 'Local path to save a returned file. For screenshots, --output ./screenshot.png sets the local filename; omit it to save with a generated filename in the current directory.',
51
+ }),
52
+ ...flags_1.EasNonInteractiveAndJsonFlags,
53
+ };
54
+ static contextDefinition = {
55
+ ...this.ContextOptions.LoggedIn,
56
+ ...this.ContextOptions.ProjectDir,
57
+ };
58
+ async runAsync() {
59
+ const { args, argv, flags } = await this.parse(SimulatorControl);
60
+ const { json: jsonFlag, nonInteractive } = (0, flags_1.resolveNonInteractiveAndJsonFlags)(flags);
61
+ if (jsonFlag) {
62
+ (0, json_1.enableJsonOutput)();
63
+ }
64
+ if (flags.id === '') {
65
+ throw new Error('--id needs a simulator session ID.');
66
+ }
67
+ const action = flags.list && !flags.help ? undefined : args.action;
68
+ const { projectDir, loggedIn: { graphqlClient }, } = await this.getContextAsync(SimulatorControl, {
69
+ nonInteractive,
70
+ });
71
+ await (0, env_1.loadSimulatorEnvAsync)(projectDir);
72
+ const sessionId = flags.id ?? process.env[env_1.EAS_SIMULATOR_SESSION_ID];
73
+ if (!sessionId) {
74
+ throw new Error(`No simulator session ID provided. Pass --id, or run \`eas simulator:start\` first to write ${env_1.SIMULATOR_DOTENV_FILE_NAME}.`);
75
+ }
76
+ const spinner = (0, ora_1.ora)(`Connecting to simulator session ${sessionId}`).start();
77
+ let connection;
78
+ try {
79
+ let catalog;
80
+ try {
81
+ const session = await DeviceRunSessionQuery_1.DeviceRunSessionQuery.byIdAsync(graphqlClient, sessionId);
82
+ connection = await (0, hostActions_1.connectHostActionsAsync)(assertControllableSession(session));
83
+ catalog = await (0, hostActions_1.fetchHostActionCatalogAsync)(connection);
84
+ spinner.succeed(`Connected to simulator session ${sessionId}`);
85
+ }
86
+ catch (err) {
87
+ spinner.fail(`Failed to connect to simulator session ${sessionId}`);
88
+ throw err;
89
+ }
90
+ if (!action) {
91
+ this.printCatalog(catalog, jsonFlag);
92
+ return;
93
+ }
94
+ const entry = Object.hasOwn(catalog, action) ? catalog[action] : undefined;
95
+ if (!entry) {
96
+ throw new Error(`Unknown simulator action "${action}". Run \`eas simulator:control\` to see the actions.`);
97
+ }
98
+ if (flags.help) {
99
+ this.printActionHelp(action, entry, jsonFlag);
100
+ return;
101
+ }
102
+ await this.runActionAsync(connection, entry, {
103
+ sessionId,
104
+ action,
105
+ values: argv.slice(1).map(String),
106
+ outputPath: flags.output,
107
+ jsonFlag,
108
+ });
109
+ }
110
+ finally {
111
+ connection?.close();
112
+ }
113
+ }
114
+ printCatalog(catalog, jsonFlag) {
115
+ if (jsonFlag) {
116
+ (0, json_1.printJsonOnlyOutput)(catalog);
117
+ return;
118
+ }
119
+ const names = Object.keys(catalog).sort();
120
+ const width = Math.max(0, ...names.map(name => name.length)) + 3;
121
+ const columns = Math.max(1, Math.min(3, Math.floor((process.stdout.columns || 80) / width)));
122
+ const rows = Math.ceil(names.length / columns);
123
+ for (let row = 0; row < rows; row++) {
124
+ const cells = Array.from({ length: columns }, (_, column) => (names[row + column * rows] ?? '').padEnd(width));
125
+ log_1.default.log(cells.join('').trimEnd());
126
+ }
127
+ log_1.default.newLine();
128
+ log_1.default.log('For action usage: eas simulator:control <action> --help');
129
+ }
130
+ printActionHelp(action, entry, jsonFlag) {
131
+ if (jsonFlag) {
132
+ (0, json_1.printJsonOnlyOutput)({ ...entry, action });
133
+ return;
134
+ }
135
+ log_1.default.newLine();
136
+ log_1.default.log(` ${chalk_1.default.bold(action)}`);
137
+ if (entry.description) {
138
+ log_1.default.log(` ${entry.description}`);
139
+ }
140
+ log_1.default.newLine();
141
+ log_1.default.log(` ${chalk_1.default.bold('USAGE')}`);
142
+ log_1.default.log(` eas simulator:control ${(0, hostActions_1.formatHostActionUsage)(action, entry)}`);
143
+ const outputFlag = entry.output === 'base64' ? '--output <path>' : '[--output <path>]';
144
+ log_1.default.log(` ${entry.output ? `${outputFlag} ` : ''}[--id <session-id>] [--json]`);
145
+ log_1.default.newLine();
146
+ log_1.default.log(` ${chalk_1.default.bold('OPTIONS')}`);
147
+ log_1.default.log(` --id <session-id> Defaults to ${env_1.SIMULATOR_DOTENV_FILE_NAME}.`);
148
+ log_1.default.log(' --json Print the action schema as JSON. Implies --non-interactive.');
149
+ if (entry.output) {
150
+ log_1.default.log(entry.output === 'base64'
151
+ ? ' --output <path> Required local filename for the returned file.'
152
+ : ' --output <path> Local filename or existing directory.');
153
+ if (entry.output === 'path') {
154
+ log_1.default.log(' Omit to save with the generated filename.');
155
+ }
156
+ log_1.default.newLine();
157
+ log_1.default.log(' Action arguments refer to the simulator host. Use --output for the local filename.');
158
+ }
159
+ log_1.default.newLine();
160
+ }
161
+ async runActionAsync(connection, entry, { sessionId, action, values, outputPath, jsonFlag, }) {
162
+ const params = (0, hostActions_1.buildHostActionParams)(action, entry, values);
163
+ await (0, hostActions_1.assertHostActionOutputAsync)(action, entry, outputPath);
164
+ const localFile = await findLocalUploadAsync(entry, params);
165
+ const spinner = (0, ora_1.ora)(`Running ${action} on simulator session ${sessionId}`).start();
166
+ let uploadId;
167
+ let succeeded = false;
168
+ let output;
169
+ let savedFile;
170
+ try {
171
+ if (localFile) {
172
+ spinner.text = `Uploading ${localFile.path}`;
173
+ const upload = await (0, hostActions_1.uploadFileAsync)(connection, localFile.path);
174
+ uploadId = upload.uploadId;
175
+ params[localFile.param] = entry.uploadAs === 'id' ? upload.uploadId : upload.path;
176
+ spinner.text = `Running ${action} on simulator session ${sessionId}`;
177
+ }
178
+ const result = await connection.requestAsync(action, params);
179
+ if (result.exitCode !== 0) {
180
+ const detail = (result.stderr || result.stdout).trim() || `exit code ${result.exitCode}`;
181
+ throw new Error(`The simulator could not run ${action}: ${detail}`);
182
+ }
183
+ succeeded = true;
184
+ savedFile = await (0, hostActions_1.saveHostActionOutputAsync)(connection, entry, result.stdout, outputPath);
185
+ output = savedFile ? '' : result.stdout.trim();
186
+ spinner.succeed(`Ran ${action} on simulator session ${sessionId}`);
187
+ }
188
+ catch (err) {
189
+ spinner.fail(`Failed to run ${action} on simulator session ${sessionId}`);
190
+ throw err;
191
+ }
192
+ finally {
193
+ if (uploadId && (!entry.keepUpload || !succeeded)) {
194
+ await connection.requestAsync('upload.remove', { uploadId }).catch(() => { });
195
+ }
196
+ }
197
+ if (jsonFlag) {
198
+ (0, json_1.printJsonOnlyOutput)({
199
+ id: sessionId,
200
+ action,
201
+ output: parseJsonOutput(output),
202
+ file: savedFile,
203
+ });
204
+ return;
205
+ }
206
+ if (savedFile) {
207
+ log_1.default.log(`Saved ${savedFile}`);
208
+ }
209
+ else if (output) {
210
+ log_1.default.log(output);
211
+ }
212
+ }
213
+ }
214
+ exports.default = SimulatorControl;
215
+ async function findLocalUploadAsync({ upload: param, uploadWhen = {} }, params) {
216
+ const value = param ? params[param] : undefined;
217
+ const applies = Object.entries(uploadWhen).every(([name, expected]) => params[name] === expected);
218
+ if (!param || typeof value !== 'string' || !applies) {
219
+ return null;
220
+ }
221
+ const stat = await fs.stat(value).catch(() => null);
222
+ if (stat?.isDirectory()) {
223
+ throw new Error(`${value} is a folder. Pass the path of a file.`);
224
+ }
225
+ if (!stat && !path_1.default.isAbsolute(value)) {
226
+ throw new Error(`${value} does not exist on this computer. Pass the path of a local file, or an absolute path on the simulator host.`);
227
+ }
228
+ return stat ? { param, path: value } : null;
229
+ }
230
+ function assertControllableSession(session) {
231
+ if (session.status !== generated_1.DeviceRunSessionStatus.InProgress) {
232
+ throw new Error(`Simulator session ${session.id} is ${session.status.toLowerCase()}. Simulator actions need a running session. Start one with \`eas simulator:start\`.`);
233
+ }
234
+ if (session.platform !== generated_1.AppPlatform.Ios) {
235
+ throw new Error(`Simulator session ${session.id} runs on ${session.platform.toLowerCase()}. Simulator actions are available only for iOS sessions.`);
236
+ }
237
+ const access = session.remoteConfig ? (0, utils_1.getPreviewApiAccess)(session.remoteConfig) : null;
238
+ if (!access) {
239
+ throw new Error(`Simulator session ${session.id} does not expose a preview server with a token. Simulator actions use that server. Start a new session with \`eas simulator:start\`.`);
240
+ }
241
+ return access;
242
+ }
243
+ function parseJsonOutput(output) {
244
+ try {
245
+ return JSON.parse(output);
246
+ }
247
+ catch {
248
+ return output;
249
+ }
250
+ }
@@ -10,7 +10,7 @@ export default class UpdateRepublish extends EasCommand {
10
10
  'destination-channel': import("@oclif/core/lib/interfaces").OptionFlag<string | undefined, import("@oclif/core/lib/interfaces").CustomOptions>;
11
11
  'destination-branch': import("@oclif/core/lib/interfaces").OptionFlag<string | undefined, import("@oclif/core/lib/interfaces").CustomOptions>;
12
12
  message: import("@oclif/core/lib/interfaces").OptionFlag<string | undefined, import("@oclif/core/lib/interfaces").CustomOptions>;
13
- platform: import("@oclif/core/lib/interfaces").OptionFlag<"android" | "ios" | "all" | "web", import("@oclif/core/lib/interfaces").CustomOptions>;
13
+ platform: import("@oclif/core/lib/interfaces").OptionFlag<"android" | "ios" | "web" | "all", import("@oclif/core/lib/interfaces").CustomOptions>;
14
14
  'private-key-path': import("@oclif/core/lib/interfaces").OptionFlag<string | undefined, import("@oclif/core/lib/interfaces").CustomOptions>;
15
15
  'rollout-percentage': import("@oclif/core/lib/interfaces").OptionFlag<number | undefined, import("@oclif/core/lib/interfaces").CustomOptions>;
16
16
  'force-end-active-rollout': import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
package/build/env.d.ts CHANGED
@@ -20,5 +20,11 @@ declare const _default: {
20
20
  * Comma separated list of feature gate keys of feature gates to evaluate override to false.
21
21
  */
22
22
  featureGateDisable: string | undefined;
23
+ /**
24
+ * Comma separated list of experiment overrides in the form `namespace:param=value`.
25
+ * Overrides apply in every scope, even when analytics is disabled. A namespace with any override
26
+ * returns defaults for its other params and logs no exposure.
27
+ */
28
+ experimentOverride: string | undefined;
23
29
  };
24
30
  export default _default;
package/build/env.js CHANGED
@@ -22,4 +22,10 @@ exports.default = {
22
22
  * Comma separated list of feature gate keys of feature gates to evaluate override to false.
23
23
  */
24
24
  featureGateDisable: process.env.EAS_FG_DISABLE,
25
+ /**
26
+ * Comma separated list of experiment overrides in the form `namespace:param=value`.
27
+ * Overrides apply in every scope, even when analytics is disabled. A namespace with any override
28
+ * returns defaults for its other params and logs no exposure.
29
+ */
30
+ experimentOverride: process.env.EAS_EXPERIMENT_OVERRIDE,
25
31
  };
@@ -0,0 +1,7 @@
1
+ import type { ExposureData, ExposureLogger } from '@expo/experimentation';
2
+ import { Analytics } from '../analytics/AnalyticsManager';
3
+ export declare class AnalyticsExposureLogger implements ExposureLogger<Record<string, any>> {
4
+ private readonly analytics;
5
+ constructor(analytics: Analytics);
6
+ logExposure(data: ExposureData<Record<string, any>>): void;
7
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AnalyticsExposureLogger = void 0;
4
+ const AnalyticsManager_1 = require("../analytics/AnalyticsManager");
5
+ class AnalyticsExposureLogger {
6
+ analytics;
7
+ constructor(analytics) {
8
+ this.analytics = analytics;
9
+ }
10
+ logExposure(data) {
11
+ const { variant } = data.params;
12
+ this.analytics.logEvent(AnalyticsManager_1.ExperimentationEvent.EXPERIMENT_VIEWED, {
13
+ experimentName: data.name,
14
+ // Analytics properties cannot be undefined. Fall back to all params when there is no variant.
15
+ variationName: variant !== undefined ? String(variant) : JSON.stringify(data.params),
16
+ // The unit is always a single value (actor ID, account ID, or device ID).
17
+ unit: String(data.unit[0]),
18
+ });
19
+ }
20
+ }
21
+ exports.AnalyticsExposureLogger = AnalyticsExposureLogger;
@@ -0,0 +1,24 @@
1
+ import type { Namespace } from '@expo/experimentation';
2
+ import { ExperimentOverrides } from './ExperimentOverrides';
3
+ export type ExperimentNamespace = {
4
+ getParam<T>(paramName: string, defaultValue: T): T;
5
+ isOverridden: boolean;
6
+ };
7
+ export declare const FALLBACK_NAMESPACE: ExperimentNamespace;
8
+ /** Serves overrides without consulting the real namespace, so no exposure is logged. */
9
+ export declare class OverrideFallbackNamespace implements ExperimentNamespace {
10
+ private readonly namespaceName;
11
+ private readonly overrides;
12
+ readonly isOverridden = true;
13
+ constructor(namespaceName: string, overrides: ExperimentOverrides);
14
+ getParam<T>(paramName: string, defaultValue: T): T;
15
+ }
16
+ /** Returns the default instead of throwing when the library rejects a param on first read. */
17
+ export declare class SafeNamespace implements ExperimentNamespace {
18
+ private readonly namespace;
19
+ private readonly namespaceName;
20
+ readonly isOverridden = false;
21
+ constructor(namespace: Namespace, namespaceName: string);
22
+ getParam<T>(paramName: string, defaultValue: T): T;
23
+ }
24
+ export declare function coerceOverrideValue<T>(overrideValue: string | undefined, defaultValue: T): T;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SafeNamespace = exports.OverrideFallbackNamespace = exports.FALLBACK_NAMESPACE = void 0;
4
+ exports.coerceOverrideValue = coerceOverrideValue;
5
+ const tslib_1 = require("tslib");
6
+ const log_1 = tslib_1.__importDefault(require("../log"));
7
+ exports.FALLBACK_NAMESPACE = {
8
+ getParam(_paramName, defaultValue) {
9
+ return defaultValue;
10
+ },
11
+ isOverridden: false,
12
+ };
13
+ /** Serves overrides without consulting the real namespace, so no exposure is logged. */
14
+ class OverrideFallbackNamespace {
15
+ namespaceName;
16
+ overrides;
17
+ isOverridden = true;
18
+ constructor(namespaceName, overrides) {
19
+ this.namespaceName = namespaceName;
20
+ this.overrides = overrides;
21
+ }
22
+ getParam(paramName, defaultValue) {
23
+ if (this.overrides.hasOverride(this.namespaceName, paramName)) {
24
+ return coerceOverrideValue(this.overrides.getOverride(this.namespaceName, paramName), defaultValue);
25
+ }
26
+ return defaultValue;
27
+ }
28
+ }
29
+ exports.OverrideFallbackNamespace = OverrideFallbackNamespace;
30
+ /** Returns the default instead of throwing when the library rejects a param on first read. */
31
+ class SafeNamespace {
32
+ namespace;
33
+ namespaceName;
34
+ isOverridden = false;
35
+ constructor(namespace, namespaceName) {
36
+ this.namespace = namespace;
37
+ this.namespaceName = namespaceName;
38
+ }
39
+ getParam(paramName, defaultValue) {
40
+ try {
41
+ return this.namespace.getParam(paramName, defaultValue);
42
+ }
43
+ catch (error) {
44
+ log_1.default.debug(`[experimentation] Failed to read param "${paramName}" from namespace "${this.namespaceName}". Returning the default.`, error);
45
+ return defaultValue;
46
+ }
47
+ }
48
+ }
49
+ exports.SafeNamespace = SafeNamespace;
50
+ function coerceOverrideValue(overrideValue, defaultValue) {
51
+ if (overrideValue === undefined || overrideValue.trim() === '') {
52
+ return defaultValue;
53
+ }
54
+ if (typeof defaultValue === 'boolean') {
55
+ const normalized = overrideValue.toLowerCase();
56
+ if (normalized === 'true') {
57
+ return true;
58
+ }
59
+ if (normalized === 'false') {
60
+ return false;
61
+ }
62
+ return defaultValue;
63
+ }
64
+ if (typeof defaultValue === 'number') {
65
+ const parsed = Number(overrideValue);
66
+ return (Number.isFinite(parsed) ? parsed : defaultValue);
67
+ }
68
+ return overrideValue;
69
+ }
@@ -0,0 +1,17 @@
1
+ export type ExperimentOverrideMap = ReadonlyMap<string, ReadonlyMap<string, string>>;
2
+ /**
3
+ * Parses `EAS_EXPERIMENT_OVERRIDE`: comma-separated `namespace:param=value` entries. Values may
4
+ * contain `:` and `=` but not `,`. Overrides are keyed by namespace name and apply in every scope.
5
+ *
6
+ * @example EAS_EXPERIMENT_OVERRIDE="onboarding:variant=treatment,cli-hints:enabled=true"
7
+ */
8
+ export declare function parseExperimentOverrides(rawValue: string | undefined): ExperimentOverrideMap;
9
+ export declare class ExperimentOverrides {
10
+ private readonly overrideMap;
11
+ constructor(overrideMap: ExperimentOverrideMap);
12
+ static fromEnv(): ExperimentOverrides;
13
+ static empty(): ExperimentOverrides;
14
+ hasNamespaceOverride(namespace: string): boolean;
15
+ hasOverride(namespace: string, param: string): boolean;
16
+ getOverride(namespace: string, param: string): string | undefined;
17
+ }
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ExperimentOverrides = void 0;
4
+ exports.parseExperimentOverrides = parseExperimentOverrides;
5
+ const tslib_1 = require("tslib");
6
+ const env_1 = tslib_1.__importDefault(require("../env"));
7
+ /**
8
+ * Parses `EAS_EXPERIMENT_OVERRIDE`: comma-separated `namespace:param=value` entries. Values may
9
+ * contain `:` and `=` but not `,`. Overrides are keyed by namespace name and apply in every scope.
10
+ *
11
+ * @example EAS_EXPERIMENT_OVERRIDE="onboarding:variant=treatment,cli-hints:enabled=true"
12
+ */
13
+ function parseExperimentOverrides(rawValue) {
14
+ const overrideMap = new Map();
15
+ if (!rawValue) {
16
+ return overrideMap;
17
+ }
18
+ for (const entry of rawValue.split(',')) {
19
+ const override = entry.trim();
20
+ if (!override) {
21
+ continue;
22
+ }
23
+ const firstEqualsIndex = override.indexOf('=');
24
+ if (firstEqualsIndex === -1) {
25
+ continue;
26
+ }
27
+ const namespaceAndParam = override.slice(0, firstEqualsIndex);
28
+ const value = override.slice(firstEqualsIndex + 1).trim();
29
+ const firstColonIndex = namespaceAndParam.indexOf(':');
30
+ if (firstColonIndex === -1) {
31
+ continue;
32
+ }
33
+ const namespace = namespaceAndParam.slice(0, firstColonIndex).trim();
34
+ const param = namespaceAndParam.slice(firstColonIndex + 1).trim();
35
+ if (!namespace || !param) {
36
+ continue;
37
+ }
38
+ let params = overrideMap.get(namespace);
39
+ if (!params) {
40
+ params = new Map();
41
+ overrideMap.set(namespace, params);
42
+ }
43
+ params.set(param, value);
44
+ }
45
+ return overrideMap;
46
+ }
47
+ class ExperimentOverrides {
48
+ overrideMap;
49
+ constructor(overrideMap) {
50
+ this.overrideMap = overrideMap;
51
+ }
52
+ static fromEnv() {
53
+ return new ExperimentOverrides(parseExperimentOverrides(env_1.default.experimentOverride));
54
+ }
55
+ static empty() {
56
+ return new ExperimentOverrides(new Map());
57
+ }
58
+ hasNamespaceOverride(namespace) {
59
+ return this.overrideMap.has(namespace);
60
+ }
61
+ hasOverride(namespace, param) {
62
+ return this.overrideMap.get(namespace)?.has(param) ?? false;
63
+ }
64
+ getOverride(namespace, param) {
65
+ return this.overrideMap.get(namespace)?.get(param);
66
+ }
67
+ }
68
+ exports.ExperimentOverrides = ExperimentOverrides;
@@ -0,0 +1,32 @@
1
+ import { type ExperimentationDefinition, type LoggerConfig } from '@expo/experimentation';
2
+ import { type ExperimentNamespace } from './ExperimentNamespace';
3
+ import { ExperimentOverrides } from './ExperimentOverrides';
4
+ import { Analytics } from '../analytics/AnalyticsManager';
5
+ export type ExperimentationScope = 'user' | 'account' | 'device';
6
+ export type ExperimentationConfigs = Record<ExperimentationScope, ExperimentationDefinition>;
7
+ /** Commands pass the account unit on each `getAccountNamespace` call. */
8
+ export type ExperimentationUnits = Record<Exclude<ExperimentationScope, 'account'>, string | null>;
9
+ export declare const EMPTY_EXPERIMENTATION_DEFINITION: ExperimentationDefinition;
10
+ export declare function createLoggerConfig(analytics: Analytics): LoggerConfig;
11
+ /**
12
+ * Resolves experiment params for the current CLI run. Units: user is the actor ID, account is the
13
+ * ID the command passes to `getAccountNamespace`, device is the analytics device ID.
14
+ * User and account units are shared across surfaces. The device unit is specific to the CLI, so a
15
+ * device namespace must not be shared with another surface.
16
+ * The first `getParam` on a namespace logs an exposure, so call it only where the variant is used.
17
+ */
18
+ export declare class ExperimentationClient {
19
+ private readonly units;
20
+ private readonly overrides;
21
+ private readonly scopes;
22
+ constructor(configs: ExperimentationConfigs, units: ExperimentationUnits, overrides: ExperimentOverrides, loggerConfig: LoggerConfig);
23
+ /** Env overrides still apply, so QA can force a variant even with analytics disabled. */
24
+ static createDisabled(overrides?: ExperimentOverrides): ExperimentationClient;
25
+ getUserNamespace(name: string): ExperimentNamespace;
26
+ /** Takes the account the command already resolved, so no extra lookup or config read happens here. */
27
+ getAccountNamespace(name: string, { accountId }: {
28
+ accountId: string;
29
+ }): ExperimentNamespace;
30
+ getDeviceNamespace(name: string): ExperimentNamespace;
31
+ private resolve;
32
+ }
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ExperimentationClient = exports.EMPTY_EXPERIMENTATION_DEFINITION = void 0;
4
+ exports.createLoggerConfig = createLoggerConfig;
5
+ const tslib_1 = require("tslib");
6
+ const experimentation_1 = require("@expo/experimentation");
7
+ const node_crypto_1 = require("node:crypto");
8
+ const AnalyticsExposureLogger_1 = require("./AnalyticsExposureLogger");
9
+ const ExperimentNamespace_1 = require("./ExperimentNamespace");
10
+ const ExperimentOverrides_1 = require("./ExperimentOverrides");
11
+ const log_1 = tslib_1.__importDefault(require("../log"));
12
+ exports.EMPTY_EXPERIMENTATION_DEFINITION = {
13
+ experiments: [],
14
+ namespaces: [],
15
+ };
16
+ const EMPTY_CONFIGS = {
17
+ user: exports.EMPTY_EXPERIMENTATION_DEFINITION,
18
+ account: exports.EMPTY_EXPERIMENTATION_DEFINITION,
19
+ device: exports.EMPTY_EXPERIMENTATION_DEFINITION,
20
+ };
21
+ const NULL_UNITS = { user: null, device: null };
22
+ function sha1(input) {
23
+ return (0, node_crypto_1.createHash)('sha1').update(input).digest('hex');
24
+ }
25
+ function createLoggerConfig(analytics) {
26
+ return {
27
+ flavorMap: new Map([
28
+ ['no-op', new experimentation_1.NoOpExposureLogger()],
29
+ ['rudderstack', new AnalyticsExposureLogger_1.AnalyticsExposureLogger(analytics)],
30
+ ]),
31
+ fallbackLoggerType: 'no-op',
32
+ };
33
+ }
34
+ const NO_OP_LOGGER_CONFIG = {
35
+ flavorMap: new Map([['no-op', new experimentation_1.NoOpExposureLogger()]]),
36
+ fallbackLoggerType: 'no-op',
37
+ };
38
+ /** Cached per (unit, name): the library deduplicates exposures per Namespace instance. */
39
+ class ScopedNamespaces {
40
+ factories;
41
+ instances = new Map();
42
+ constructor(definition, loggerConfig, defaultUnit) {
43
+ this.factories = (0, experimentation_1.parseExperimentationConfig)(definition, { sha1Fn: sha1 }, loggerConfig);
44
+ // Build every namespace now so an invalid server config throws here, in the fail-open path.
45
+ if (defaultUnit) {
46
+ for (const name of this.factories.keys()) {
47
+ this.getNamespace(name, defaultUnit);
48
+ }
49
+ }
50
+ }
51
+ getNamespace(name, unit) {
52
+ const factory = this.factories.get(name);
53
+ if (!factory) {
54
+ return null;
55
+ }
56
+ let byName = this.instances.get(unit);
57
+ if (!byName) {
58
+ byName = new Map();
59
+ this.instances.set(unit, byName);
60
+ }
61
+ let namespace = byName.get(name);
62
+ if (!namespace) {
63
+ namespace = factory([unit]);
64
+ byName.set(name, namespace);
65
+ }
66
+ return namespace;
67
+ }
68
+ }
69
+ /**
70
+ * Resolves experiment params for the current CLI run. Units: user is the actor ID, account is the
71
+ * ID the command passes to `getAccountNamespace`, device is the analytics device ID.
72
+ * User and account units are shared across surfaces. The device unit is specific to the CLI, so a
73
+ * device namespace must not be shared with another surface.
74
+ * The first `getParam` on a namespace logs an exposure, so call it only where the variant is used.
75
+ */
76
+ class ExperimentationClient {
77
+ units;
78
+ overrides;
79
+ scopes;
80
+ constructor(configs, units, overrides, loggerConfig) {
81
+ this.units = units;
82
+ this.overrides = overrides;
83
+ this.scopes = {
84
+ user: new ScopedNamespaces(configs.user, loggerConfig, units.user),
85
+ account: new ScopedNamespaces(configs.account, loggerConfig, null),
86
+ device: new ScopedNamespaces(configs.device, loggerConfig, units.device),
87
+ };
88
+ }
89
+ /** Env overrides still apply, so QA can force a variant even with analytics disabled. */
90
+ static createDisabled(overrides = ExperimentOverrides_1.ExperimentOverrides.fromEnv()) {
91
+ return new ExperimentationClient(EMPTY_CONFIGS, NULL_UNITS, overrides, NO_OP_LOGGER_CONFIG);
92
+ }
93
+ getUserNamespace(name) {
94
+ return this.resolve('user', name, this.units.user);
95
+ }
96
+ /** Takes the account the command already resolved, so no extra lookup or config read happens here. */
97
+ getAccountNamespace(name, { accountId }) {
98
+ return this.resolve('account', name, accountId);
99
+ }
100
+ getDeviceNamespace(name) {
101
+ return this.resolve('device', name, this.units.device);
102
+ }
103
+ resolve(scope, name, unit) {
104
+ if (this.overrides.hasNamespaceOverride(name)) {
105
+ return new ExperimentNamespace_1.OverrideFallbackNamespace(name, this.overrides);
106
+ }
107
+ if (!unit) {
108
+ return ExperimentNamespace_1.FALLBACK_NAMESPACE;
109
+ }
110
+ let namespace;
111
+ try {
112
+ namespace = this.scopes[scope].getNamespace(name, unit);
113
+ }
114
+ catch (error) {
115
+ log_1.default.debug(`[experimentation] Failed to build namespace "${name}" in the ${scope} config. Returning defaults.`, error);
116
+ return ExperimentNamespace_1.FALLBACK_NAMESPACE;
117
+ }
118
+ if (!namespace) {
119
+ log_1.default.debug(`[experimentation] Namespace "${name}" not found in the ${scope} config. Returning defaults.`);
120
+ return ExperimentNamespace_1.FALLBACK_NAMESPACE;
121
+ }
122
+ return new ExperimentNamespace_1.SafeNamespace(namespace, name);
123
+ }
124
+ }
125
+ exports.ExperimentationClient = ExperimentationClient;
@@ -0,0 +1,12 @@
1
+ import { ExperimentationClient } from './ExperimentationClient';
2
+ /**
3
+ * Defers building the experimentation client, and the config fetch behind it, until a command
4
+ * first needs a variant.
5
+ */
6
+ export declare class LazyExperimentationClient {
7
+ private readonly loadAsync;
8
+ private pending;
9
+ constructor(loadAsync: () => Promise<ExperimentationClient>);
10
+ static fromClient(client: ExperimentationClient): LazyExperimentationClient;
11
+ getClientAsync(): Promise<ExperimentationClient>;
12
+ }