awesome-emulator-cli 0.3.0 → 0.5.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.
- package/README.md +84 -2
- package/dist/cli.js +102 -8
- package/dist/emulator-environment.d.ts +12 -1
- package/dist/emulator-environment.js +133 -7
- package/dist/emulator-options.d.ts +5 -0
- package/dist/index.d.ts +19 -8
- package/dist/index.js +146 -7
- package/dist/process.d.ts +1 -1
- package/dist/process.js +2 -2
- package/dist/session-store.d.ts +24 -0
- package/dist/session-store.js +152 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# Awesome Emulator CLI
|
|
2
2
|
|
|
3
3
|
<p align="center">
|
|
4
|
-
<img src="./assets/social-preview.png" alt="Awesome Emulator CLI — Local emulator testing for
|
|
4
|
+
<img src="./assets/social-preview-v2.png" alt="Awesome Emulator CLI — Local emulator testing for AWS SDKs" width="100%">
|
|
5
5
|
</p>
|
|
6
6
|
|
|
7
|
-
Awesome Emulator CLI
|
|
7
|
+
Awesome Emulator CLI is a Docker wrapper for AWS Emulator: it starts a local container and supplies connection settings to your test command. The CLI is distributed with Node.js, but the project under test can use any AWS SDK language and does not need to be a Node.js project.
|
|
8
8
|
|
|
9
9
|
This is an independent project and is not affiliated with or endorsed by Amazon Web Services.
|
|
10
10
|
|
|
@@ -14,6 +14,8 @@ This is an independent project and is not affiliated with or endorsed by Amazon
|
|
|
14
14
|
- Docker Engine or Docker Desktop
|
|
15
15
|
- x86_64/amd64 or ARM64/aarch64
|
|
16
16
|
|
|
17
|
+
Node.js is required to run the CLI. Your application and test project can use any language.
|
|
18
|
+
|
|
17
19
|
On first start, Docker downloads the selected AWS Emulator RPM and its signature, verifies the signature, and builds a local image. Later starts reuse the image for that version and architecture.
|
|
18
20
|
|
|
19
21
|
Prepare the image ahead of the first test run with:
|
|
@@ -33,6 +35,61 @@ npx awesome-emulator run -- npm test
|
|
|
33
35
|
|
|
34
36
|
`run` starts the emulator, supplies the connection settings to the child process, then stops the container. Use `--version` to select a release and `--port 0` to choose a free local port. Run `npx awesome-emulator --help` for all options.
|
|
35
37
|
|
|
38
|
+
Set the child's default AWS region with `--region`:
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
npx awesome-emulator run --region ap-northeast-1 -- npm test
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
By default, both `AWS_REGION` and `AWS_DEFAULT_REGION` are `us-east-1`. `--region` sets both for the child command without changing the emulator endpoint. An SDK client configured with its own region continues to use that explicit region.
|
|
45
|
+
|
|
46
|
+
### Run non-Node projects
|
|
47
|
+
|
|
48
|
+
You can run an existing project command even when the project has no `package.json`. Use `npm exec` to download the CLI for the run:
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- python -m pytest
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The same pattern works with other SDK projects:
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
# AWS CLI v2, Boto3, and AWS SDK for Go v2 use AWS_CA_BUNDLE automatically.
|
|
58
|
+
npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- aws sts get-caller-identity
|
|
59
|
+
npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- python -m pytest
|
|
60
|
+
npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- go test ./...
|
|
61
|
+
|
|
62
|
+
# AWS SDK for JavaScript v3 uses NODE_EXTRA_CA_CERTS, which the CLI sets by default.
|
|
63
|
+
npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- npm test
|
|
64
|
+
|
|
65
|
+
# Java, Rust, and .NET need an additional TLS setting.
|
|
66
|
+
npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run --sdk java-v2 -- ./mvnw -B -o test
|
|
67
|
+
npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run --sdk rust -- cargo test --offline
|
|
68
|
+
npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run --sdk dotnet -- dotnet test --no-restore
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Resolve Java, Rust, and .NET dependencies before the wrapped command when they are not already cached. For example, run `./mvnw -B dependency:go-offline`, `cargo fetch`, or `dotnet restore` before starting the emulator.
|
|
72
|
+
|
|
73
|
+
The repository runs an integration smoke check for AWS CLI v2, Boto3, AWS SDK for JavaScript v3, Java 2.x, Go v2, Rust, and .NET. It verifies that each client reaches the emulator's STS endpoint with TLS enabled and receives the emulator account ID.
|
|
74
|
+
|
|
75
|
+
The common child environment sets `AWS_ENDPOINT_URL`, the emulator credentials and config files, `AWS_CA_BUNDLE`, and the region. The CLI removes inherited credential variables, profile selectors, and service-specific endpoint variables so those host environment settings cannot redirect or authenticate the test. `AWS_DISABLE_HOST_PREFIX_INJECTION` is enabled for SDKs that otherwise rewrite the local host. The wrapper manages inherited environment and JVM option variables; project code or build configuration that explicitly sets credentials or endpoints must be configured for the emulator.
|
|
76
|
+
|
|
77
|
+
Use `--sdk` only when a process needs SDK-specific TLS configuration. It can be repeated when one command runs more than one SDK:
|
|
78
|
+
|
|
79
|
+
| SDK | TLS configuration |
|
|
80
|
+
| --- | --- |
|
|
81
|
+
| AWS CLI v2, Boto3, AWS SDK for Go v2 | `AWS_CA_BUNDLE` |
|
|
82
|
+
| AWS SDK for JavaScript v3 | `NODE_EXTRA_CA_CERTS` |
|
|
83
|
+
| AWS SDK for Java 2.x | `--sdk java-v2` adds the emulator `truststore.p12` to `JAVA_TOOL_OPTIONS` |
|
|
84
|
+
| AWS SDK for Rust | `--sdk rust` sets `SSL_CERT_FILE` to `ca.pem` |
|
|
85
|
+
| AWS SDK for .NET | `--sdk dotnet` sets `SSL_CERT_FILE` to `ca.pem` |
|
|
86
|
+
|
|
87
|
+
Java's `JAVA_TOOL_OPTIONS` applies to every JVM started by the child command, including Maven or Gradle and test workers. Resolve Java build dependencies before invoking `awesome-emulator run`, or use a truststore that contains both the emulator certificate and the certificates for other HTTPS hosts. The emulator truststore contains only the emulator certificate, so HTTPS calls to Maven Central, AWS, or other hosts can fail while it is active. The CLI appends to existing `JAVA_TOOL_OPTIONS`; if `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS`, or `_JAVA_OPTIONS` already sets `javax.net.ssl.trustStore`, it preserves that truststore. If only `javax.net.ssl.trustStoreType=PKCS12` is set, the CLI adds the emulator truststore path and preserves the type. An incompatible truststore type requires a custom truststore path. A preserved truststore must also trust the emulator. `MAVEN_OPTS` and `GRADLE_OPTS` remain in their own variables; if either sets a separate truststore, make sure the Java test JVM trusts the emulator too.
|
|
88
|
+
|
|
89
|
+
The AWS SDK for Java gives JVM system properties precedence over environment variables. When `--sdk java-v2` is selected, the CLI checks inherited `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS`, `_JAVA_OPTIONS`, `JAVA_OPTS`, `MAVEN_OPTS`, `GRADLE_OPTS`, `ANT_OPTS`, and `SBT_OPTS` values and rejects AWS credential, profile, or endpoint properties and `@argument-file` references so inherited JVM options cannot bypass the emulator settings.
|
|
90
|
+
|
|
91
|
+
`AWS_CA_BUNDLE` and `SSL_CERT_FILE` replace the default CA bundle for SDKs that read them. If the same process must contact other HTTPS services, create a combined bundle with the emulator CA and the roots it needs. `NODE_EXTRA_CA_CERTS` is additive to Node.js's default trust roots.
|
|
92
|
+
|
|
36
93
|
Child commands run without a shell by default, so each argument is passed as data. On Windows, `.cmd` and `.bat` launchers such as `npm`, and shell built-ins such as `echo` and `dir`, require an explicit shell opt-in:
|
|
37
94
|
|
|
38
95
|
```sh
|
|
@@ -41,6 +98,31 @@ npx awesome-emulator run --shell -- npm test
|
|
|
41
98
|
|
|
42
99
|
Use `--shell` only with trusted command and argument values. Shell metacharacters are interpreted in this mode. Node.js API callers can opt in with `runWithEmulator(command, args, { shell: true })` under the same restriction.
|
|
43
100
|
|
|
101
|
+
## Reuse an emulator across commands
|
|
102
|
+
|
|
103
|
+
Use a named session when setup and tests run in separate commands or CI steps. The session metadata is stored under `~/.aws/emulator/sessions/` with restrictive file permissions on Unix systems; it contains container and connection details, not credential values. `exec` supplies the same emulator environment as `run` and can be called repeatedly:
|
|
104
|
+
|
|
105
|
+
```sh
|
|
106
|
+
npx awesome-emulator up --session ci-tests --port 0
|
|
107
|
+
npx awesome-emulator exec --session ci-tests -- npm run seed
|
|
108
|
+
npx awesome-emulator exec --session ci-tests -- npm test
|
|
109
|
+
npx awesome-emulator down --session ci-tests
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
In CI, put the final `down` command in an always-run cleanup step so the container is removed even when a test step fails. Each CI job should use its own session name. `up` prints the connection settings as JSON; it does not print the container ID or credential values.
|
|
113
|
+
|
|
114
|
+
Persistent sessions use `ps` on Unix or Windows PowerShell on Windows to distinguish an active startup from an abandoned session record.
|
|
115
|
+
|
|
116
|
+
Run a one-time seed or setup command after the emulator becomes healthy with `--init`. The initializer receives the same emulator environment as `exec`; a non-zero exit makes `up` fail and stops the session. Initializer stdout is sent to stderr so the JSON printed by `up` remains machine-readable:
|
|
117
|
+
|
|
118
|
+
```sh
|
|
119
|
+
npx awesome-emulator up --session ci-tests --init -- node scripts/seed-emulator.js
|
|
120
|
+
npx awesome-emulator exec --session ci-tests -- npm test
|
|
121
|
+
npx awesome-emulator down --session ci-tests
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Initializer arguments are passed directly without a shell by default. Use `--shell` before `--` only when you need shell behavior and trust all command values.
|
|
125
|
+
|
|
44
126
|
## Use from Node.js
|
|
45
127
|
|
|
46
128
|
Use the API when your test harness needs to control the emulator lifecycle directly:
|
package/dist/cli.js
CHANGED
|
@@ -1,19 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { prepareEmulatorImage, runWithEmulator, startEmulator } from "./index.js";
|
|
2
|
+
import { prepareEmulatorImage, downEmulatorSession, execEmulatorSession, runWithEmulator, startEmulator, upEmulatorSession, } from "./index.js";
|
|
3
3
|
import { DEFAULT_VERSION } from "./emulator-options.js";
|
|
4
4
|
import { FORWARDED_SIGNALS, getSignalExitCode } from "./signals.js";
|
|
5
|
+
import { DEFAULT_AWS_REGION, SUPPORTED_EMULATOR_SDKS } from "./emulator-environment.js";
|
|
5
6
|
function usage() {
|
|
6
7
|
console.log(`Usage:
|
|
7
8
|
awesome-emulator prepare [--version <version>]
|
|
8
9
|
awesome-emulator start [options]
|
|
9
|
-
awesome-emulator run [options] [--shell] -- <command> [args...]
|
|
10
|
+
awesome-emulator run [options] [--region <region>] [--sdk <family>]... [--shell] -- <command> [args...]
|
|
11
|
+
awesome-emulator up --session <name> [options] [--init [child options] -- <command> [args...]]
|
|
12
|
+
awesome-emulator exec --session <name> [--region <region>] [--sdk <family>]... [--shell] -- <command> [args...]
|
|
13
|
+
awesome-emulator down --session <name>
|
|
10
14
|
|
|
11
15
|
Options:
|
|
12
16
|
-v, --version <version> AWS Emulator version (default: ${DEFAULT_VERSION})
|
|
13
|
-
-p, --port <port> (start/run) Host port; 0 chooses an available port (default: 9297)
|
|
14
|
-
-t, --telemetry <on|off> (start/run) Telemetry setting (default: on)
|
|
15
|
-
--memory <limit> (start/run) Container memory limit (default: 2g)
|
|
16
|
-
--
|
|
17
|
+
-p, --port <port> (start/run/up) Host port; 0 chooses an available port (default: 9297)
|
|
18
|
+
-t, --telemetry <on|off> (start/run/up) Telemetry setting (default: on)
|
|
19
|
+
--memory <limit> (start/run/up) Container memory limit (default: 2g)
|
|
20
|
+
--region <region> (run/exec/up --init) Default region for the child command (default: ${DEFAULT_AWS_REGION})
|
|
21
|
+
--session <name> (up/exec/down) Persistent emulator session name
|
|
22
|
+
--sdk <family> (run/exec/up --init) Add SDK-specific TLS settings; repeatable
|
|
23
|
+
(${SUPPORTED_EMULATOR_SDKS.join(", ")})
|
|
24
|
+
--shell (run/exec/up --init) Enable .cmd/.bat and built-ins; trusted values only
|
|
25
|
+
--init (up only) Run a command after the emulator becomes healthy
|
|
17
26
|
-h, --help Show this help`);
|
|
18
27
|
}
|
|
19
28
|
function parse(argv) {
|
|
@@ -23,6 +32,7 @@ function parse(argv) {
|
|
|
23
32
|
const options = {};
|
|
24
33
|
const commandArgs = [];
|
|
25
34
|
let separator = false;
|
|
35
|
+
let initRequested = false;
|
|
26
36
|
for (let index = 1; index < argv.length; index += 1) {
|
|
27
37
|
const token = argv[index];
|
|
28
38
|
if (separator) {
|
|
@@ -30,35 +40,82 @@ function parse(argv) {
|
|
|
30
40
|
continue;
|
|
31
41
|
}
|
|
32
42
|
if (token === "--") {
|
|
43
|
+
if (command === "up" && !initRequested)
|
|
44
|
+
throw new Error("The up command accepts child arguments only after --init --.");
|
|
33
45
|
separator = true;
|
|
34
46
|
continue;
|
|
35
47
|
}
|
|
36
48
|
if (token === "-h" || token === "--help")
|
|
37
49
|
return { help: true };
|
|
50
|
+
if (token === "--init") {
|
|
51
|
+
if (command !== "up")
|
|
52
|
+
throw new Error("--init can only be used with the up command.");
|
|
53
|
+
if (initRequested)
|
|
54
|
+
throw new Error("--init can only be specified once.");
|
|
55
|
+
initRequested = true;
|
|
56
|
+
options.init = true;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
38
59
|
if (token === "--shell") {
|
|
39
|
-
if (command !== "run")
|
|
40
|
-
throw new Error("--shell can only be used with the run command.");
|
|
60
|
+
if (command !== "run" && command !== "exec" && command !== "up")
|
|
61
|
+
throw new Error("--shell can only be used with the run or exec command, or with up --init.");
|
|
41
62
|
options.shell = true;
|
|
42
63
|
continue;
|
|
43
64
|
}
|
|
65
|
+
if (token === "--sdk") {
|
|
66
|
+
if (command !== "run" && command !== "exec" && command !== "up")
|
|
67
|
+
throw new Error("--sdk can only be used with the run or exec command, or with up --init.");
|
|
68
|
+
const value = argv[index + 1];
|
|
69
|
+
if (!value || value.startsWith("--"))
|
|
70
|
+
throw new Error("Missing value for --sdk");
|
|
71
|
+
if (!SUPPORTED_EMULATOR_SDKS.includes(value)) {
|
|
72
|
+
throw new Error(`Unsupported SDK: ${value}. Choose from ${SUPPORTED_EMULATOR_SDKS.join(", ")}.`);
|
|
73
|
+
}
|
|
74
|
+
options.sdks ??= [];
|
|
75
|
+
options.sdks.push(value);
|
|
76
|
+
index += 1;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
44
79
|
const optionNames = {
|
|
45
80
|
"-v": "version", "--version": "version",
|
|
46
81
|
"-p": "port", "--port": "port",
|
|
47
82
|
"-t": "telemetry", "--telemetry": "telemetry",
|
|
48
83
|
"--memory": "memory",
|
|
84
|
+
"--region": "region",
|
|
85
|
+
"--session": "session",
|
|
49
86
|
};
|
|
50
87
|
const key = optionNames[token];
|
|
51
88
|
if (!key)
|
|
52
89
|
throw new Error(`Unknown option: ${token}`);
|
|
90
|
+
if (key === "region" && command !== "run" && command !== "exec" && command !== "up") {
|
|
91
|
+
throw new Error("--region can only be used with the run or exec command, or with up --init.");
|
|
92
|
+
}
|
|
93
|
+
if (key === "session" && command !== "up" && command !== "exec" && command !== "down") {
|
|
94
|
+
throw new Error("--session can only be used with the up, exec, or down command.");
|
|
95
|
+
}
|
|
53
96
|
if (command === "prepare" && key !== "version") {
|
|
54
97
|
throw new Error(`${token} can only be used with the start or run command.`);
|
|
55
98
|
}
|
|
99
|
+
if ((command === "exec" || command === "down") && key !== "region" && key !== "session") {
|
|
100
|
+
throw new Error(`${token} cannot be used with the ${command} command.`);
|
|
101
|
+
}
|
|
56
102
|
const value = argv[index + 1];
|
|
57
103
|
if (!value || value.startsWith("--"))
|
|
58
104
|
throw new Error(`Missing value for ${token}`);
|
|
59
105
|
options[key] = value;
|
|
60
106
|
index += 1;
|
|
61
107
|
}
|
|
108
|
+
if ((command === "up" || command === "exec" || command === "down") && !options.session) {
|
|
109
|
+
throw new Error(`--session is required with the ${command} command.`);
|
|
110
|
+
}
|
|
111
|
+
if (command === "up") {
|
|
112
|
+
if (initRequested && (!separator || commandArgs.length === 0)) {
|
|
113
|
+
throw new Error("Usage: awesome-emulator up --session <name> [options] --init -- <command> [args...]");
|
|
114
|
+
}
|
|
115
|
+
if (!initRequested && (separator || options.region || options.sdks || options.shell)) {
|
|
116
|
+
throw new Error("Child command options and arguments for up require --init.");
|
|
117
|
+
}
|
|
118
|
+
}
|
|
62
119
|
return { help: false, command, options, commandArgs };
|
|
63
120
|
}
|
|
64
121
|
function waitForAbort(signal) {
|
|
@@ -88,6 +145,43 @@ async function main(signal) {
|
|
|
88
145
|
throw new Error("Usage: awesome-emulator run [options] -- <command> [args...]");
|
|
89
146
|
return runWithEmulator(program, args, { ...parsed.options, signal });
|
|
90
147
|
}
|
|
148
|
+
if (parsed.command === "up") {
|
|
149
|
+
const [initCommand, ...initArgs] = parsed.commandArgs;
|
|
150
|
+
const session = await upEmulatorSession(parsed.options.session, {
|
|
151
|
+
version: parsed.options.version,
|
|
152
|
+
port: parsed.options.port,
|
|
153
|
+
telemetry: parsed.options.telemetry,
|
|
154
|
+
memory: parsed.options.memory,
|
|
155
|
+
signal,
|
|
156
|
+
init: parsed.options.init ? {
|
|
157
|
+
command: initCommand,
|
|
158
|
+
args: initArgs,
|
|
159
|
+
region: parsed.options.region,
|
|
160
|
+
sdks: parsed.options.sdks,
|
|
161
|
+
shell: parsed.options.shell,
|
|
162
|
+
} : undefined,
|
|
163
|
+
});
|
|
164
|
+
console.log(JSON.stringify(session, null, 2));
|
|
165
|
+
return 0;
|
|
166
|
+
}
|
|
167
|
+
if (parsed.command === "exec") {
|
|
168
|
+
const [program, ...args] = parsed.commandArgs;
|
|
169
|
+
if (!program)
|
|
170
|
+
throw new Error("Usage: awesome-emulator exec --session <name> -- <command> [args...]");
|
|
171
|
+
return execEmulatorSession(parsed.options.session, program, args, {
|
|
172
|
+
region: parsed.options.region,
|
|
173
|
+
sdks: parsed.options.sdks,
|
|
174
|
+
shell: parsed.options.shell,
|
|
175
|
+
signal,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
if (parsed.command === "down") {
|
|
179
|
+
if (parsed.commandArgs.length > 0)
|
|
180
|
+
throw new Error("The down command does not accept child command arguments.");
|
|
181
|
+
await downEmulatorSession(parsed.options.session);
|
|
182
|
+
console.log(`Emulator session "${parsed.options.session}" stopped.`);
|
|
183
|
+
return 0;
|
|
184
|
+
}
|
|
91
185
|
if (parsed.command === "prepare") {
|
|
92
186
|
const image = await prepareEmulatorImage({ version: parsed.options.version, signal });
|
|
93
187
|
console.log(`AWS Emulator image is ready: ${image}`);
|
|
@@ -7,6 +7,15 @@ export type EmulatorEnvironment = {
|
|
|
7
7
|
AWS_REGION: string;
|
|
8
8
|
AWS_DEFAULT_REGION: string;
|
|
9
9
|
NODE_EXTRA_CA_CERTS: string;
|
|
10
|
+
AWS_DISABLE_HOST_PREFIX_INJECTION: "true";
|
|
11
|
+
};
|
|
12
|
+
export declare const SUPPORTED_EMULATOR_SDKS: readonly ["java-v2", "rust", "dotnet"];
|
|
13
|
+
export type EmulatorSdk = typeof SUPPORTED_EMULATOR_SDKS[number];
|
|
14
|
+
export declare const DEFAULT_AWS_REGION = "us-east-1";
|
|
15
|
+
export type ChildEnvironmentOptions = {
|
|
16
|
+
sdks?: readonly EmulatorSdk[];
|
|
17
|
+
region?: string;
|
|
18
|
+
platform?: NodeJS.Platform;
|
|
10
19
|
};
|
|
11
20
|
export type EmulatorConnectionSettings = {
|
|
12
21
|
endpointUrl: string;
|
|
@@ -16,5 +25,7 @@ export type EmulatorConnectionSettings = {
|
|
|
16
25
|
caFile: string;
|
|
17
26
|
environment: EmulatorEnvironment;
|
|
18
27
|
};
|
|
28
|
+
export declare function normalizeEmulatorSdks(sdks?: readonly string[]): EmulatorSdk[];
|
|
29
|
+
export declare function resolveAwsRegion(region: string | undefined, defaultRegion?: string): string;
|
|
19
30
|
export declare function createEmulatorConnectionSettings(port: number, stateDirectory: string): EmulatorConnectionSettings;
|
|
20
|
-
export declare function createChildEnvironment(parentEnvironment: NodeJS.ProcessEnv, emulatorEnvironment: EmulatorEnvironment): NodeJS.ProcessEnv;
|
|
31
|
+
export declare function createChildEnvironment(parentEnvironment: NodeJS.ProcessEnv, emulatorEnvironment: EmulatorEnvironment, options?: ChildEnvironmentOptions): NodeJS.ProcessEnv;
|
|
@@ -1,18 +1,60 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
export const SUPPORTED_EMULATOR_SDKS = [
|
|
3
|
+
"java-v2",
|
|
4
|
+
"rust",
|
|
5
|
+
"dotnet",
|
|
6
|
+
];
|
|
7
|
+
export const DEFAULT_AWS_REGION = "us-east-1";
|
|
2
8
|
const AWS_CREDENTIAL_ENVIRONMENT_KEYS = [
|
|
9
|
+
"AWS_ACCESS_KEY",
|
|
3
10
|
"AWS_ACCESS_KEY_ID",
|
|
11
|
+
"AWS_SECRET_KEY",
|
|
4
12
|
"AWS_SECRET_ACCESS_KEY",
|
|
13
|
+
"AWS_SECURITY_TOKEN",
|
|
5
14
|
"AWS_SESSION_TOKEN",
|
|
6
15
|
"AWS_PROFILE",
|
|
7
16
|
"AWS_DEFAULT_PROFILE",
|
|
8
17
|
"AWS_ROLE_ARN",
|
|
9
18
|
"AWS_WEB_IDENTITY_TOKEN_FILE",
|
|
19
|
+
"AWS_CREDENTIAL_PROFILES_FILE",
|
|
10
20
|
"AWS_CONTAINER_CREDENTIALS_FULL_URI",
|
|
11
21
|
"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
|
|
12
22
|
"AWS_CONTAINER_AUTHORIZATION_TOKEN",
|
|
13
23
|
"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",
|
|
24
|
+
"AWS_EC2_METADATA_SERVICE_ENDPOINT",
|
|
25
|
+
"AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",
|
|
14
26
|
"AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",
|
|
27
|
+
"AWS_ENDPOINT_URL_PREFIX",
|
|
28
|
+
"AWS_ENDPOINT_URL_SUFFIX",
|
|
29
|
+
];
|
|
30
|
+
const JAVA_OPTION_ENVIRONMENT_KEYS = [
|
|
31
|
+
"JAVA_TOOL_OPTIONS",
|
|
32
|
+
"JDK_JAVA_OPTIONS",
|
|
33
|
+
"_JAVA_OPTIONS",
|
|
34
|
+
"JAVA_OPTS",
|
|
35
|
+
"MAVEN_OPTS",
|
|
36
|
+
"GRADLE_OPTS",
|
|
37
|
+
"ANT_OPTS",
|
|
38
|
+
"SBT_OPTS",
|
|
39
|
+
];
|
|
40
|
+
const JVM_WIDE_JAVA_OPTION_ENVIRONMENT_KEYS = [
|
|
41
|
+
"JAVA_TOOL_OPTIONS",
|
|
42
|
+
"JDK_JAVA_OPTIONS",
|
|
43
|
+
"_JAVA_OPTIONS",
|
|
15
44
|
];
|
|
45
|
+
export function normalizeEmulatorSdks(sdks = []) {
|
|
46
|
+
const unsupportedSdk = sdks.find((sdk) => !SUPPORTED_EMULATOR_SDKS.includes(sdk));
|
|
47
|
+
if (unsupportedSdk !== undefined) {
|
|
48
|
+
throw new Error(`Unsupported SDK: ${unsupportedSdk}. Choose from ${SUPPORTED_EMULATOR_SDKS.join(", ")}.`);
|
|
49
|
+
}
|
|
50
|
+
return [...new Set(sdks)];
|
|
51
|
+
}
|
|
52
|
+
export function resolveAwsRegion(region, defaultRegion = DEFAULT_AWS_REGION) {
|
|
53
|
+
const resolvedRegion = region ?? defaultRegion;
|
|
54
|
+
if (resolvedRegion.trim().length === 0)
|
|
55
|
+
throw new Error("Region must not be empty.");
|
|
56
|
+
return resolvedRegion;
|
|
57
|
+
}
|
|
16
58
|
export function createEmulatorConnectionSettings(port, stateDirectory) {
|
|
17
59
|
const endpointUrl = `https://127.0.0.1:${port}`;
|
|
18
60
|
const portDirectory = path.join(stateDirectory, String(port));
|
|
@@ -22,9 +64,10 @@ export function createEmulatorConnectionSettings(port, stateDirectory) {
|
|
|
22
64
|
AWS_CONFIG_FILE: path.join(portDirectory, "config"),
|
|
23
65
|
AWS_CA_BUNDLE: path.join(portDirectory, "ca.pem"),
|
|
24
66
|
AWS_EC2_METADATA_DISABLED: "true",
|
|
25
|
-
AWS_REGION:
|
|
26
|
-
AWS_DEFAULT_REGION:
|
|
67
|
+
AWS_REGION: DEFAULT_AWS_REGION,
|
|
68
|
+
AWS_DEFAULT_REGION: DEFAULT_AWS_REGION,
|
|
27
69
|
NODE_EXTRA_CA_CERTS: path.join(portDirectory, "ca.pem"),
|
|
70
|
+
AWS_DISABLE_HOST_PREFIX_INJECTION: "true",
|
|
28
71
|
};
|
|
29
72
|
return {
|
|
30
73
|
endpointUrl,
|
|
@@ -35,13 +78,96 @@ export function createEmulatorConnectionSettings(port, stateDirectory) {
|
|
|
35
78
|
environment,
|
|
36
79
|
};
|
|
37
80
|
}
|
|
38
|
-
export function createChildEnvironment(parentEnvironment, emulatorEnvironment) {
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
81
|
+
export function createChildEnvironment(parentEnvironment, emulatorEnvironment, options = {}) {
|
|
82
|
+
const { sdks = [], region, platform = process.platform } = options;
|
|
83
|
+
const caseInsensitiveEnvironment = platform === "win32";
|
|
84
|
+
const normalizeName = (name) => caseInsensitiveEnvironment ? name.toUpperCase() : name;
|
|
85
|
+
const childEnvironment = { ...parentEnvironment };
|
|
86
|
+
const controlledEnvironmentKeys = new Set([
|
|
87
|
+
...Object.keys(emulatorEnvironment),
|
|
88
|
+
...AWS_CREDENTIAL_ENVIRONMENT_KEYS,
|
|
89
|
+
...(sdks.includes("rust") || sdks.includes("dotnet") ? ["SSL_CERT_FILE"] : []),
|
|
90
|
+
].map(normalizeName));
|
|
42
91
|
for (const key of Object.keys(childEnvironment)) {
|
|
43
|
-
|
|
92
|
+
const normalizedKey = normalizeName(key);
|
|
93
|
+
if (controlledEnvironmentKeys.has(normalizedKey) || normalizedKey.startsWith("AWS_ENDPOINT_URL_")) {
|
|
44
94
|
delete childEnvironment[key];
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const childRegion = resolveAwsRegion(region, emulatorEnvironment.AWS_REGION);
|
|
98
|
+
Object.assign(childEnvironment, emulatorEnvironment, {
|
|
99
|
+
AWS_REGION: childRegion,
|
|
100
|
+
AWS_DEFAULT_REGION: childRegion,
|
|
101
|
+
});
|
|
102
|
+
if (sdks.includes("java-v2")) {
|
|
103
|
+
const inheritedJavaOptions = [];
|
|
104
|
+
const inheritedJvmWideOptions = [];
|
|
105
|
+
for (const name of JAVA_OPTION_ENVIRONMENT_KEYS) {
|
|
106
|
+
const matchingKeys = Object.keys(parentEnvironment)
|
|
107
|
+
.filter((key) => normalizeName(key) === normalizeName(name));
|
|
108
|
+
const values = matchingKeys
|
|
109
|
+
.map((key) => parentEnvironment[key])
|
|
110
|
+
.filter((value) => value !== undefined);
|
|
111
|
+
for (const key of Object.keys(childEnvironment)) {
|
|
112
|
+
if (normalizeName(key) === normalizeName(name))
|
|
113
|
+
delete childEnvironment[key];
|
|
114
|
+
}
|
|
115
|
+
if (values.length > 0) {
|
|
116
|
+
const combinedOptions = values.join(" ");
|
|
117
|
+
childEnvironment[name] = combinedOptions;
|
|
118
|
+
inheritedJavaOptions.push(combinedOptions);
|
|
119
|
+
if (JVM_WIDE_JAVA_OPTION_ENVIRONMENT_KEYS.includes(name)) {
|
|
120
|
+
inheritedJvmWideOptions.push(combinedOptions);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const existingOptions = childEnvironment.JAVA_TOOL_OPTIONS;
|
|
125
|
+
rejectJavaAwsOverrides(inheritedJavaOptions);
|
|
126
|
+
const hasConfiguredTrustStore = inheritedJvmWideOptions.some((options) => /(?:^|[\s"'])-Djavax\.net\.ssl\.trustStore(?:=|\s|["'])/.test(options));
|
|
127
|
+
const hasConfiguredTrustStoreType = inheritedJvmWideOptions.some((options) => /(?:^|[\s"'])-Djavax\.net\.ssl\.trustStoreType(?:=|\s|["'])/.test(options));
|
|
128
|
+
const hasIncompatibleTrustStoreTypeWithoutPath = inheritedJavaOptions.some((options) => {
|
|
129
|
+
const hasCustomTrustStore = /(?:^|[\s"'])-Djavax\.net\.ssl\.trustStore(?:=|\s|["'])/.test(options);
|
|
130
|
+
if (hasCustomTrustStore)
|
|
131
|
+
return false;
|
|
132
|
+
const types = [...options.matchAll(/(?:^|[\s"'])-Djavax\.net\.ssl\.trustStoreType=(?:"([^"]*)"|'([^']*)'|([^\s"']+))/g)]
|
|
133
|
+
.map((match) => match[1] ?? match[2] ?? match[3] ?? "");
|
|
134
|
+
return types.some((type) => type.toUpperCase() !== "PKCS12");
|
|
135
|
+
});
|
|
136
|
+
if (hasIncompatibleTrustStoreTypeWithoutPath) {
|
|
137
|
+
throw new Error("The emulator truststore uses PKCS12. Set javax.net.ssl.trustStoreType=PKCS12 or provide a compatible custom truststore with javax.net.ssl.trustStore.");
|
|
138
|
+
}
|
|
139
|
+
if (hasConfiguredTrustStore) {
|
|
140
|
+
childEnvironment.JAVA_TOOL_OPTIONS = existingOptions;
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
const trustStore = path.join(path.dirname(emulatorEnvironment.AWS_CA_BUNDLE), "truststore.p12");
|
|
144
|
+
const trustStoreOption = quoteJavaToolOption(`-Djavax.net.ssl.trustStore=${trustStore}`);
|
|
145
|
+
childEnvironment.JAVA_TOOL_OPTIONS = [
|
|
146
|
+
existingOptions?.trim(),
|
|
147
|
+
trustStoreOption,
|
|
148
|
+
hasConfiguredTrustStoreType ? undefined : "-Djavax.net.ssl.trustStoreType=PKCS12",
|
|
149
|
+
].filter(Boolean).join(" ");
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (sdks.includes("rust") || sdks.includes("dotnet")) {
|
|
153
|
+
childEnvironment.SSL_CERT_FILE = emulatorEnvironment.AWS_CA_BUNDLE;
|
|
45
154
|
}
|
|
46
155
|
return childEnvironment;
|
|
47
156
|
}
|
|
157
|
+
function rejectJavaAwsOverrides(options) {
|
|
158
|
+
const property = /(?:^|[\s"'])-Daws\.(?:accessKeyId|secretAccessKey|secretKey|sessionToken|profile|webIdentityTokenFile|roleArn|roleSessionName|sharedCredentialsFile|configFile|ignoreConfiguredEndpointUrls|disableEc2Metadata|ec2MetadataServiceEndpointMode|ec2MetadataServiceEndpoint|endpointUrl(?:\.[A-Za-z0-9_-]+|[A-Z][A-Za-z0-9_-]*)?)(?==|\s|["'])/;
|
|
159
|
+
if (options.some((value) => /(?:^|[\s"'])@/.test(value))) {
|
|
160
|
+
throw new Error("Inherited JVM options reference an @argument file, which can hide AWS credential or endpoint overrides. Remove it when using --sdk java-v2.");
|
|
161
|
+
}
|
|
162
|
+
if (options.some((value) => property.test(value))) {
|
|
163
|
+
throw new Error("Inherited JVM options contain an AWS credential, profile, or endpoint override. Remove the aws.* system property so the emulator settings can be used.");
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function quoteJavaToolOption(option) {
|
|
167
|
+
if (/[\r\n]/.test(option))
|
|
168
|
+
throw new Error("Java truststore path cannot contain line breaks.");
|
|
169
|
+
const quote = option.includes('"') ? "'" : '"';
|
|
170
|
+
if (option.includes(quote))
|
|
171
|
+
throw new Error("Java truststore path cannot contain both quote characters.");
|
|
172
|
+
return `${quote}${option}${quote}`;
|
|
173
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { EmulatorSdk } from "./emulator-environment.js";
|
|
1
2
|
export type StartEmulatorOptions = {
|
|
2
3
|
version?: string;
|
|
3
4
|
port?: number | string;
|
|
@@ -13,6 +14,10 @@ export type RunWithEmulatorOptions = StartEmulatorOptions & {
|
|
|
13
14
|
* Defaults to false.
|
|
14
15
|
*/
|
|
15
16
|
shell?: boolean;
|
|
17
|
+
/** Set AWS_REGION and AWS_DEFAULT_REGION for the child command. */
|
|
18
|
+
region?: string;
|
|
19
|
+
/** Add SDK-specific TLS settings for the selected SDK families. */
|
|
20
|
+
sdks?: EmulatorSdk[];
|
|
16
21
|
};
|
|
17
22
|
export type PrepareEmulatorOptions = Pick<StartEmulatorOptions, "version" | "signal">;
|
|
18
23
|
export type ResolvedEmulatorOptions = {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { type EmulatorEnvironment } from "./emulator-environment.js";
|
|
1
|
+
import { type EmulatorEnvironment, type EmulatorSdk } from "./emulator-environment.js";
|
|
2
2
|
import { type PrepareEmulatorOptions, type RunWithEmulatorOptions, type StartEmulatorOptions } from "./emulator-options.js";
|
|
3
3
|
export type { PrepareEmulatorOptions, RunWithEmulatorOptions, StartEmulatorOptions } from "./emulator-options.js";
|
|
4
|
-
export type { EmulatorEnvironment } from "./emulator-environment.js";
|
|
4
|
+
export type { EmulatorEnvironment, EmulatorSdk } from "./emulator-environment.js";
|
|
5
5
|
export type EmulatorSession = {
|
|
6
6
|
version: string;
|
|
7
7
|
port: number;
|
|
@@ -14,15 +14,26 @@ export type EmulatorSession = {
|
|
|
14
14
|
containerId: string;
|
|
15
15
|
stop: () => Promise<void>;
|
|
16
16
|
};
|
|
17
|
+
export type PersistentEmulatorSession = Omit<EmulatorSession, "containerId" | "stop"> & {
|
|
18
|
+
name: string;
|
|
19
|
+
};
|
|
20
|
+
export type EmulatorSessionExecOptions = Pick<RunWithEmulatorOptions, "shell" | "sdks" | "region" | "signal">;
|
|
21
|
+
export type EmulatorSessionInitCommand = {
|
|
22
|
+
command: string;
|
|
23
|
+
args?: string[];
|
|
24
|
+
shell?: boolean;
|
|
25
|
+
sdks?: EmulatorSdk[];
|
|
26
|
+
region?: string;
|
|
27
|
+
};
|
|
28
|
+
export type UpEmulatorSessionOptions = StartEmulatorOptions & {
|
|
29
|
+
init?: EmulatorSessionInitCommand;
|
|
30
|
+
};
|
|
17
31
|
/** Build or reuse the selected AWS Emulator Docker image without starting a container. */
|
|
18
32
|
export declare function prepareEmulatorImage(options?: PrepareEmulatorOptions): Promise<string>;
|
|
19
|
-
/**
|
|
20
|
-
* Start AWS Emulator in a local Docker container.
|
|
21
|
-
*
|
|
22
|
-
* The returned object includes SDK environment variables and an idempotent
|
|
23
|
-
* stop() function. Port 0 asks the wrapper to choose an available local port.
|
|
24
|
-
*/
|
|
25
33
|
export declare function startEmulator(options?: StartEmulatorOptions): Promise<EmulatorSession>;
|
|
34
|
+
export declare function upEmulatorSession(name: string, options?: UpEmulatorSessionOptions): Promise<PersistentEmulatorSession>;
|
|
35
|
+
export declare function execEmulatorSession(name: string, command: string, args?: string[], options?: EmulatorSessionExecOptions): Promise<number>;
|
|
36
|
+
export declare function downEmulatorSession(name: string): Promise<void>;
|
|
26
37
|
/**
|
|
27
38
|
* Run a child process with AWS Emulator settings and stop the emulator afterward.
|
|
28
39
|
*/
|
package/dist/index.js
CHANGED
|
@@ -6,10 +6,16 @@ import os from "node:os";
|
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { createRetryableStop, startContainer, stopContainer, withEmulator } from "./container-lifecycle.js";
|
|
8
8
|
import { docker, throwIfAborted } from "./docker.js";
|
|
9
|
-
import { createChildEnvironment, createEmulatorConnectionSettings } from "./emulator-environment.js";
|
|
9
|
+
import { createChildEnvironment, createEmulatorConnectionSettings, normalizeEmulatorSdks, resolveAwsRegion, } from "./emulator-environment.js";
|
|
10
10
|
import { ensureEmulatorImage, getArchitecture } from "./emulator-image.js";
|
|
11
|
+
import { isSessionOwnerRunning, readSession, removeSession, reserveSession, validateSessionName, writeRunningSession } from "./session-store.js";
|
|
11
12
|
import { resolveEmulatorOptions, resolveEmulatorVersion, } from "./emulator-options.js";
|
|
12
13
|
import { runCommand } from "./process.js";
|
|
14
|
+
const MANAGED_CONTAINER_LABEL = "io.github.c19yamamoto.awesome-emulator-cli.managed";
|
|
15
|
+
const SESSION_CONTAINER_LABEL = "io.github.c19yamamoto.awesome-emulator-cli.session";
|
|
16
|
+
function emulatorStateDirectory() {
|
|
17
|
+
return path.join(os.homedir(), ".aws", "emulator");
|
|
18
|
+
}
|
|
13
19
|
/** Build or reuse the selected AWS Emulator Docker image without starting a container. */
|
|
14
20
|
export async function prepareEmulatorImage(options = {}) {
|
|
15
21
|
throwIfAborted(options.signal);
|
|
@@ -49,16 +55,18 @@ function requestHealth(port, ca, signal) {
|
|
|
49
55
|
});
|
|
50
56
|
}
|
|
51
57
|
const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
52
|
-
function createContainerRunArguments({ architecture, containerName, image, memory, port, stateDirectory, telemetry, }) {
|
|
58
|
+
function createContainerRunArguments({ architecture, containerName, image, labels, memory, port, stateDirectory, telemetry, }) {
|
|
53
59
|
const hostUser = process.platform === "linux"
|
|
54
60
|
&& typeof process.getuid === "function"
|
|
55
61
|
&& typeof process.getgid === "function"
|
|
56
62
|
? ["--user", `${process.getuid()}:${process.getgid()}`]
|
|
57
63
|
: [];
|
|
64
|
+
const dockerLabels = Object.entries(labels).flatMap(([key, value]) => ["--label", `${key}=${value}`]);
|
|
58
65
|
return [
|
|
59
66
|
"run", "--detach",
|
|
60
67
|
"--platform", `linux/${architecture.docker}`,
|
|
61
68
|
...hostUser,
|
|
69
|
+
...dockerLabels,
|
|
62
70
|
"--memory", memory,
|
|
63
71
|
"--memory-swap", memory,
|
|
64
72
|
"--publish", `127.0.0.1:${port}:${port}`,
|
|
@@ -108,21 +116,21 @@ async function waitUntilHealthy(containerId, port, stateDirectory, timeoutMs, si
|
|
|
108
116
|
* The returned object includes SDK environment variables and an idempotent
|
|
109
117
|
* stop() function. Port 0 asks the wrapper to choose an available local port.
|
|
110
118
|
*/
|
|
111
|
-
|
|
119
|
+
async function startEmulatorWithIdentity(options, containerName, labels) {
|
|
112
120
|
throwIfAborted(options.signal);
|
|
113
121
|
const { version, requestedPort, telemetry, memory, startupTimeoutMs } = resolveEmulatorOptions(options);
|
|
114
122
|
const port = requestedPort === 0 ? await getAvailablePort() : requestedPort;
|
|
115
123
|
throwIfAborted(options.signal);
|
|
116
124
|
const architecture = getArchitecture();
|
|
117
|
-
const stateDirectory =
|
|
125
|
+
const stateDirectory = emulatorStateDirectory();
|
|
118
126
|
await mkdir(stateDirectory, { recursive: true, mode: 0o700 });
|
|
119
127
|
const image = await ensureEmulatorImage(version, architecture, options.signal);
|
|
120
128
|
throwIfAborted(options.signal);
|
|
121
|
-
const containerName = `awesome-emulator-cli-${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
122
129
|
const runArguments = createContainerRunArguments({
|
|
123
130
|
architecture,
|
|
124
131
|
containerName,
|
|
125
132
|
image,
|
|
133
|
+
labels,
|
|
126
134
|
memory,
|
|
127
135
|
port,
|
|
128
136
|
stateDirectory,
|
|
@@ -151,15 +159,146 @@ export async function startEmulator(options = {}) {
|
|
|
151
159
|
stop,
|
|
152
160
|
};
|
|
153
161
|
}
|
|
162
|
+
export async function startEmulator(options = {}) {
|
|
163
|
+
const containerName = `awesome-emulator-cli-${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
164
|
+
return startEmulatorWithIdentity(options, containerName, { [MANAGED_CONTAINER_LABEL]: "true" });
|
|
165
|
+
}
|
|
166
|
+
export async function upEmulatorSession(name, options = {}) {
|
|
167
|
+
validateSessionName(name);
|
|
168
|
+
const { init, ...emulatorOptions } = options;
|
|
169
|
+
const initOptions = init
|
|
170
|
+
? { sdks: normalizeEmulatorSdks(init.sdks), region: resolveAwsRegion(init.region) }
|
|
171
|
+
: undefined;
|
|
172
|
+
if (init && !init.command)
|
|
173
|
+
throw new Error("An initialization command is required.");
|
|
174
|
+
const stateDirectory = emulatorStateDirectory();
|
|
175
|
+
const containerName = `awesome-emulator-cli-session-${randomBytes(4).toString("hex")}-${name}`;
|
|
176
|
+
await reserveSession(stateDirectory, name, containerName);
|
|
177
|
+
let emulator;
|
|
178
|
+
try {
|
|
179
|
+
emulator = await startEmulatorWithIdentity(emulatorOptions, containerName, {
|
|
180
|
+
[MANAGED_CONTAINER_LABEL]: "true",
|
|
181
|
+
[SESSION_CONTAINER_LABEL]: name,
|
|
182
|
+
});
|
|
183
|
+
if (init && initOptions) {
|
|
184
|
+
const childEnvironment = createChildEnvironment(process.env, emulator.environment, initOptions);
|
|
185
|
+
const exitCode = await runCommand(init.command, init.args ?? [], childEnvironment, options.signal, init.shell ?? false, "stderr");
|
|
186
|
+
if (exitCode !== 0) {
|
|
187
|
+
throwIfAborted(options.signal);
|
|
188
|
+
throw new Error(`Emulator session "${name}" initialization command failed with exit code ${exitCode}.`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const record = {
|
|
192
|
+
schemaVersion: 1,
|
|
193
|
+
name,
|
|
194
|
+
state: "running",
|
|
195
|
+
containerName,
|
|
196
|
+
containerId: emulator.containerId,
|
|
197
|
+
version: emulator.version,
|
|
198
|
+
port: emulator.port,
|
|
199
|
+
};
|
|
200
|
+
await writeRunningSession(stateDirectory, record);
|
|
201
|
+
throwIfAborted(options.signal);
|
|
202
|
+
const { containerId: _containerId, stop: _stop, ...publicSession } = emulator;
|
|
203
|
+
return { name, ...publicSession };
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
const cleanupErrors = [];
|
|
207
|
+
if (emulator) {
|
|
208
|
+
try {
|
|
209
|
+
await emulator.stop();
|
|
210
|
+
}
|
|
211
|
+
catch (cleanupError) {
|
|
212
|
+
cleanupErrors.push(cleanupError);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (!(error instanceof AggregateError) && cleanupErrors.length === 0) {
|
|
216
|
+
try {
|
|
217
|
+
await removeSession(stateDirectory, name);
|
|
218
|
+
}
|
|
219
|
+
catch (cleanupError) {
|
|
220
|
+
cleanupErrors.push(cleanupError);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (cleanupErrors.length > 0) {
|
|
224
|
+
throw new AggregateError([error, ...cleanupErrors], `Failed to start emulator session "${name}" and clean up its state.`);
|
|
225
|
+
}
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
async function inspectSessionContainer(name, containerName) {
|
|
230
|
+
let details;
|
|
231
|
+
try {
|
|
232
|
+
details = await docker([
|
|
233
|
+
"inspect",
|
|
234
|
+
"--format",
|
|
235
|
+
`{{.Id}}|{{.State.Running}}|{{index .Config.Labels "${MANAGED_CONTAINER_LABEL}"}}|{{index .Config.Labels "${SESSION_CONTAINER_LABEL}"}}`,
|
|
236
|
+
containerName,
|
|
237
|
+
], { capture: true });
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
if (error instanceof Error && /no such (?:container|object)/i.test(error.message))
|
|
241
|
+
return undefined;
|
|
242
|
+
throw error;
|
|
243
|
+
}
|
|
244
|
+
const [containerId, running, managed, sessionName] = details.split("|");
|
|
245
|
+
if (managed !== "true" || sessionName !== name) {
|
|
246
|
+
throw new Error(`Docker container "${containerName}" is not owned by emulator session "${name}".`);
|
|
247
|
+
}
|
|
248
|
+
if (!containerId || !/^[a-f0-9]{12,64}$/i.test(containerId)) {
|
|
249
|
+
throw new Error(`Docker returned invalid session details for "${name}".`);
|
|
250
|
+
}
|
|
251
|
+
return { containerId, running: running === "true" };
|
|
252
|
+
}
|
|
253
|
+
export async function execEmulatorSession(name, command, args = [], options = {}) {
|
|
254
|
+
if (!command)
|
|
255
|
+
throw new Error("A command is required.");
|
|
256
|
+
validateSessionName(name);
|
|
257
|
+
const { signal, shell = false, sdks: requestedSdks = [], region } = options;
|
|
258
|
+
const childRegion = resolveAwsRegion(region);
|
|
259
|
+
const sdks = normalizeEmulatorSdks(requestedSdks);
|
|
260
|
+
const stateDirectory = emulatorStateDirectory();
|
|
261
|
+
const session = await readSession(stateDirectory, name);
|
|
262
|
+
if (session.state !== "running") {
|
|
263
|
+
throw new Error(`Emulator session "${name}" is still starting. Wait for "awesome-emulator up" to finish before running commands.`);
|
|
264
|
+
}
|
|
265
|
+
const container = await inspectSessionContainer(name, session.containerName);
|
|
266
|
+
if (!container) {
|
|
267
|
+
throw new Error(`Emulator session "${name}" is stale. Run "awesome-emulator down --session ${name}" to remove it.`);
|
|
268
|
+
}
|
|
269
|
+
if (container.containerId !== session.containerId) {
|
|
270
|
+
throw new Error(`Emulator session "${name}" no longer matches its Docker container. Run "awesome-emulator down --session ${name}" to remove it.`);
|
|
271
|
+
}
|
|
272
|
+
if (!container.running) {
|
|
273
|
+
throw new Error(`Emulator session "${name}" is not running. Run "awesome-emulator down --session ${name}" to remove it.`);
|
|
274
|
+
}
|
|
275
|
+
const emulator = createEmulatorConnectionSettings(session.port, stateDirectory);
|
|
276
|
+
const childEnvironment = createChildEnvironment(process.env, emulator.environment, { sdks, region: childRegion });
|
|
277
|
+
return runCommand(command, args, childEnvironment, signal, shell);
|
|
278
|
+
}
|
|
279
|
+
export async function downEmulatorSession(name) {
|
|
280
|
+
validateSessionName(name);
|
|
281
|
+
const stateDirectory = emulatorStateDirectory();
|
|
282
|
+
const session = await readSession(stateDirectory, name);
|
|
283
|
+
if (session.state === "starting" && isSessionOwnerRunning(session)) {
|
|
284
|
+
throw new Error(`Emulator session "${name}" is still starting. Retry after "awesome-emulator up" finishes.`);
|
|
285
|
+
}
|
|
286
|
+
const container = await inspectSessionContainer(name, session.containerName);
|
|
287
|
+
if (container)
|
|
288
|
+
await stopContainer(container.containerId);
|
|
289
|
+
await removeSession(stateDirectory, name);
|
|
290
|
+
}
|
|
154
291
|
/**
|
|
155
292
|
* Run a child process with AWS Emulator settings and stop the emulator afterward.
|
|
156
293
|
*/
|
|
157
294
|
export async function runWithEmulator(command, args = [], options = {}) {
|
|
158
295
|
if (!command)
|
|
159
296
|
throw new Error("A command is required.");
|
|
160
|
-
const { shell = false, ...emulatorOptions } = options;
|
|
297
|
+
const { shell = false, sdks: requestedSdks = [], region, ...emulatorOptions } = options;
|
|
298
|
+
const childRegion = resolveAwsRegion(region);
|
|
299
|
+
const sdks = normalizeEmulatorSdks(requestedSdks);
|
|
161
300
|
return withEmulator(() => startEmulator(emulatorOptions), async (emulator) => {
|
|
162
|
-
const childEnvironment = createChildEnvironment(process.env, emulator.environment);
|
|
301
|
+
const childEnvironment = createChildEnvironment(process.env, emulator.environment, { sdks, region: childRegion });
|
|
163
302
|
return runCommand(command, args, childEnvironment, emulatorOptions.signal, shell);
|
|
164
303
|
});
|
|
165
304
|
}
|
package/dist/process.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare function runCommand(command: string, args: string[], env: NodeJS.ProcessEnv, signal?: AbortSignal, shell?: boolean): Promise<number>;
|
|
1
|
+
export declare function runCommand(command: string, args: string[], env: NodeJS.ProcessEnv, signal?: AbortSignal, shell?: boolean, stdout?: "inherit" | "stderr"): Promise<number>;
|
package/dist/process.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { FORWARDED_SIGNALS, getSignalExitCode, isForwardedSignal } from "./signals.js";
|
|
3
|
-
export function runCommand(command, args, env, signal, shell = false) {
|
|
3
|
+
export function runCommand(command, args, env, signal, shell = false, stdout = "inherit") {
|
|
4
4
|
return new Promise((resolve, reject) => {
|
|
5
5
|
const child = spawn(command, args, {
|
|
6
6
|
env,
|
|
7
|
-
stdio: "inherit",
|
|
7
|
+
stdio: stdout === "stderr" ? ["inherit", 2, "inherit"] : "inherit",
|
|
8
8
|
shell,
|
|
9
9
|
windowsHide: false,
|
|
10
10
|
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export type StartingSessionRecord = {
|
|
2
|
+
schemaVersion: 1;
|
|
3
|
+
name: string;
|
|
4
|
+
state: "starting";
|
|
5
|
+
containerName: string;
|
|
6
|
+
ownerPid: number;
|
|
7
|
+
ownerStartMarker: string;
|
|
8
|
+
};
|
|
9
|
+
export type RunningSessionRecord = {
|
|
10
|
+
schemaVersion: 1;
|
|
11
|
+
name: string;
|
|
12
|
+
state: "running";
|
|
13
|
+
containerName: string;
|
|
14
|
+
containerId: string;
|
|
15
|
+
version: string;
|
|
16
|
+
port: number;
|
|
17
|
+
};
|
|
18
|
+
export type SessionRecord = StartingSessionRecord | RunningSessionRecord;
|
|
19
|
+
export declare function validateSessionName(name: string): string;
|
|
20
|
+
export declare function isSessionOwnerRunning(record: StartingSessionRecord): boolean;
|
|
21
|
+
export declare function reserveSession(stateDirectory: string, name: string, containerName: string): Promise<string>;
|
|
22
|
+
export declare function writeRunningSession(stateDirectory: string, record: RunningSessionRecord): Promise<void>;
|
|
23
|
+
export declare function readSession(stateDirectory: string, name: string): Promise<SessionRecord>;
|
|
24
|
+
export declare function removeSession(stateDirectory: string, name: string): Promise<void>;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { chmod, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
const SESSION_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
6
|
+
export function validateSessionName(name) {
|
|
7
|
+
if (!SESSION_NAME_PATTERN.test(name)) {
|
|
8
|
+
throw new Error("Invalid session name. Use 1-63 lowercase letters, numbers, or hyphens; start and end with a letter or number.");
|
|
9
|
+
}
|
|
10
|
+
return name;
|
|
11
|
+
}
|
|
12
|
+
function getProcessStartMarker(pid) {
|
|
13
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
14
|
+
return undefined;
|
|
15
|
+
const isWindows = process.platform === "win32";
|
|
16
|
+
const command = isWindows ? "powershell.exe" : "ps";
|
|
17
|
+
const args = isWindows
|
|
18
|
+
? ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", `$process = [System.Diagnostics.Process]::GetProcessById(${pid}); $process.StartTime.ToUniversalTime().ToString('o')`]
|
|
19
|
+
: ["-o", "lstart=", "-p", String(pid)];
|
|
20
|
+
const result = spawnSync(command, args, {
|
|
21
|
+
encoding: "utf8",
|
|
22
|
+
env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
|
|
23
|
+
timeout: isWindows ? 15_000 : 2_000,
|
|
24
|
+
windowsHide: true,
|
|
25
|
+
});
|
|
26
|
+
if (result.error || result.status !== 0)
|
|
27
|
+
return undefined;
|
|
28
|
+
return result.stdout.trim() || undefined;
|
|
29
|
+
}
|
|
30
|
+
function isProcessRunning(pid) {
|
|
31
|
+
try {
|
|
32
|
+
process.kill(pid, 0);
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error instanceof Error && "code" in error && error.code === "EPERM")
|
|
37
|
+
return true;
|
|
38
|
+
if (error instanceof Error && "code" in error && error.code === "ESRCH")
|
|
39
|
+
return false;
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export function isSessionOwnerRunning(record) {
|
|
44
|
+
const currentStartMarker = getProcessStartMarker(record.ownerPid);
|
|
45
|
+
if (currentStartMarker)
|
|
46
|
+
return record.ownerStartMarker === currentStartMarker;
|
|
47
|
+
if (isProcessRunning(record.ownerPid)) {
|
|
48
|
+
throw new Error(`Could not verify the owner process for emulator session "${record.name}". Ensure ${process.platform === "win32" ? "Windows PowerShell" : "ps"} is available, then retry.`);
|
|
49
|
+
}
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
function sessionPath(stateDirectory, name) {
|
|
53
|
+
return path.join(stateDirectory, "sessions", `${validateSessionName(name)}.json`);
|
|
54
|
+
}
|
|
55
|
+
export async function reserveSession(stateDirectory, name, containerName) {
|
|
56
|
+
const filename = sessionPath(stateDirectory, name);
|
|
57
|
+
const ownerStartMarker = getProcessStartMarker(process.pid);
|
|
58
|
+
if (!ownerStartMarker) {
|
|
59
|
+
throw new Error(`Could not identify the startup process. Ensure ${process.platform === "win32" ? "Windows PowerShell" : "ps"} is available to manage persistent sessions.`);
|
|
60
|
+
}
|
|
61
|
+
const directory = path.dirname(filename);
|
|
62
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
63
|
+
if (process.platform !== "win32")
|
|
64
|
+
await chmod(directory, 0o700);
|
|
65
|
+
const record = {
|
|
66
|
+
schemaVersion: 1,
|
|
67
|
+
name,
|
|
68
|
+
state: "starting",
|
|
69
|
+
containerName,
|
|
70
|
+
ownerPid: process.pid,
|
|
71
|
+
ownerStartMarker,
|
|
72
|
+
};
|
|
73
|
+
try {
|
|
74
|
+
await writeFile(filename, `${JSON.stringify(record)}\n`, { flag: "wx", mode: 0o600 });
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
if (error instanceof Error && "code" in error && error.code === "EEXIST") {
|
|
78
|
+
throw new Error(`Emulator session "${name}" already exists. Stop it with "awesome-emulator down --session ${name}" before reusing the name.`);
|
|
79
|
+
}
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
return filename;
|
|
83
|
+
}
|
|
84
|
+
export async function writeRunningSession(stateDirectory, record) {
|
|
85
|
+
validateSessionName(record.name);
|
|
86
|
+
const filename = sessionPath(stateDirectory, record.name);
|
|
87
|
+
const temporaryFilename = `${filename}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
88
|
+
try {
|
|
89
|
+
await writeFile(temporaryFilename, `${JSON.stringify(record)}\n`, { flag: "wx", mode: 0o600 });
|
|
90
|
+
await rename(temporaryFilename, filename);
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
await unlink(temporaryFilename).catch(() => { });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
export async function readSession(stateDirectory, name) {
|
|
97
|
+
const filename = sessionPath(stateDirectory, name);
|
|
98
|
+
let contents;
|
|
99
|
+
try {
|
|
100
|
+
contents = await readFile(filename, "utf8");
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
104
|
+
throw new Error(`Emulator session "${name}" was not found. Start it with "awesome-emulator up --session ${name}".`);
|
|
105
|
+
}
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
let record;
|
|
109
|
+
try {
|
|
110
|
+
record = JSON.parse(contents);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
throw new Error(`Emulator session "${name}" has invalid metadata. Remove its session file before continuing.`);
|
|
114
|
+
}
|
|
115
|
+
if (!isSessionRecord(record, name)) {
|
|
116
|
+
throw new Error(`Emulator session "${name}" has invalid metadata. Remove its session file before continuing.`);
|
|
117
|
+
}
|
|
118
|
+
return record;
|
|
119
|
+
}
|
|
120
|
+
export async function removeSession(stateDirectory, name) {
|
|
121
|
+
try {
|
|
122
|
+
await unlink(sessionPath(stateDirectory, name));
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
126
|
+
return;
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function isSessionRecord(value, expectedName) {
|
|
131
|
+
if (typeof value !== "object" || value === null)
|
|
132
|
+
return false;
|
|
133
|
+
const record = value;
|
|
134
|
+
if (record.schemaVersion !== 1 || record.name !== expectedName || typeof record.containerName !== "string")
|
|
135
|
+
return false;
|
|
136
|
+
if (!record.containerName.startsWith("awesome-emulator-cli-session-") || !record.containerName.endsWith(`-${record.name}`))
|
|
137
|
+
return false;
|
|
138
|
+
if (record.state === "starting") {
|
|
139
|
+
return Number.isSafeInteger(record.ownerPid)
|
|
140
|
+
&& Number(record.ownerPid) > 0
|
|
141
|
+
&& typeof record.ownerStartMarker === "string"
|
|
142
|
+
&& record.ownerStartMarker.length > 0;
|
|
143
|
+
}
|
|
144
|
+
if (record.state !== "running")
|
|
145
|
+
return false;
|
|
146
|
+
return typeof record.containerId === "string"
|
|
147
|
+
&& /^[a-f0-9]{12,64}$/i.test(record.containerId)
|
|
148
|
+
&& typeof record.version === "string"
|
|
149
|
+
&& Number.isInteger(record.port)
|
|
150
|
+
&& Number(record.port) > 0
|
|
151
|
+
&& Number(record.port) <= 65535;
|
|
152
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "awesome-emulator-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "Run tests for AWS SDKs in any language; the CLI manages the local emulator in Docker.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|