@specific.dev/spectest 0.33.0 → 0.35.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.
@@ -0,0 +1,119 @@
1
+ import type { ServiceSetupContext } from "../index.js";
2
+ export interface AwsOptions {
3
+ /**
4
+ * Lambda functions to deploy from the project's own source, keyed by
5
+ * function name — the name the app (or a state machine) invokes.
6
+ *
7
+ * ```ts
8
+ * lambdas: {
9
+ * add: { source: "lambda/add" },
10
+ * resize: { source: "lambda/resize", runtime: "python3.12", timeoutSecs: 60 },
11
+ * }
12
+ * ```
13
+ *
14
+ * Each is packaged and deployed during environment bring-up, so it is part
15
+ * of the warm-template snapshot: a warm start restores the deployed
16
+ * function instead of deploying it again.
17
+ */
18
+ lambdas?: Record<string, LambdaOptions>;
19
+ }
20
+ export interface LambdaOptions {
21
+ /**
22
+ * The function's code, as a path in your repository — either a directory
23
+ * (packaged whole, recursively, with its contents at the root of the
24
+ * package) or a single file. Relative paths resolve against the project
25
+ * root, so `"lambda/add"` is the repo's own `lambda/add/`.
26
+ *
27
+ * The code is taken from the repository on purpose: the function you test
28
+ * is the function you ship. Anything the handler imports at runtime —
29
+ * including its dependencies — must be inside this path, exactly as a real
30
+ * deployment package requires.
31
+ */
32
+ source: string;
33
+ /** Entry point, as AWS spells it: `<file>.<exported function>`. Default
34
+ * `"index.handler"`. */
35
+ handler?: string;
36
+ /** Lambda runtime identifier. Default `"nodejs20.x"`. */
37
+ runtime?: string;
38
+ /** Environment variables for the function. */
39
+ env?: Record<string, string>;
40
+ /** Function timeout in seconds. Default `30`. */
41
+ timeoutSecs?: number;
42
+ /** Execution-role ARN. Defaults to a fixed placeholder — the emulator does
43
+ * not enforce IAM. Set it only when the code reads the ARN itself. */
44
+ role?: string;
45
+ }
46
+ /**
47
+ * The AWS cloud APIs, emulated in the environment and answering at their real
48
+ * endpoints. Drop into `environment.services`:
49
+ *
50
+ * ```ts
51
+ * import { aws } from "@specific.dev/spectest/components";
52
+ *
53
+ * services: {
54
+ * aws: aws({
55
+ * lambdas: {
56
+ * add: { source: "lambda/add" },
57
+ * subtract: { source: "lambda/subtract" },
58
+ * },
59
+ * }),
60
+ * app: {
61
+ * image: { type: "dockerfile", content: appDockerfile },
62
+ * // Whatever the app already reads in production. An AWS SDK needs a
63
+ * // region and credentials; the emulator accepts any credential value.
64
+ * env: {
65
+ * AWS_REGION: "us-east-1",
66
+ * AWS_ACCESS_KEY_ID: "test",
67
+ * AWS_SECRET_ACCESS_KEY: "test",
68
+ * },
69
+ * dependsOn: ["aws"],
70
+ * },
71
+ * }
72
+ * ```
73
+ *
74
+ * The app keeps its production configuration — `new SFNClient({})`, no
75
+ * endpoint — because the component owns DNS and TLS for the AWS domains. It
76
+ * answers for **every region**, so an app that talks to two of them, or that
77
+ * reads its region from configuration, needs nothing declared here.
78
+ *
79
+ * Tests reach the same cloud with the AWS CLI, which the emulator's image
80
+ * ships as `awslocal` (the CLI, already pointed at it):
81
+ *
82
+ * ```ts
83
+ * const listed = await ctx.exec("aws", "awslocal stepfunctions list-state-machines");
84
+ * expect(listed.exitCode).toBe(0);
85
+ * const machines = listed.stdout.transform("machines", (out) =>
86
+ * (JSON.parse(out) as { stateMachines: unknown[] }).stateMachines,
87
+ * );
88
+ * expect(machines).toHaveLength(1);
89
+ * ```
90
+ *
91
+ * For S3, prefer the `s3()` component and give it the endpoint your app uses
92
+ * (`s3({ hosts: ["s3.us-east-1.amazonaws.com"] })`). An exact hostname always
93
+ * beats this component's wildcard, so the two compose without further
94
+ * configuration.
95
+ */
96
+ export declare function aws(opts?: AwsOptions): {
97
+ setup?: (({ name, projectRoot }: ServiceSetupContext) => Promise<void>) | undefined;
98
+ image: {
99
+ type: "registry";
100
+ reference: string;
101
+ };
102
+ env: {
103
+ AWS_DEFAULT_REGION: string;
104
+ LAMBDA_EXECUTOR: string;
105
+ LAMBDA_STRICT: string;
106
+ LAMBDA_DOCKER_NETWORK: string;
107
+ };
108
+ volumes: {
109
+ source: string;
110
+ target: string;
111
+ }[];
112
+ ports: number[];
113
+ readyCheck: {
114
+ type: "http";
115
+ port: number;
116
+ path: string;
117
+ timeoutSecs: number;
118
+ };
119
+ };
@@ -0,0 +1,444 @@
1
+ // `aws()` — the AWS cloud APIs, emulated inside the environment, answering
2
+ // at their **real** endpoints.
3
+ //
4
+ // The component runs one emulator container and claims the AWS domains for
5
+ // it: DNS, a leaf certificate minted from the in-VM root CA, and a
6
+ // TLS-terminating reverse proxy. An AWS SDK in the app under test therefore
7
+ // resolves `https://states.us-east-1.amazonaws.com` the way it does in
8
+ // production and reaches the emulator — the app needs no endpoint override,
9
+ // no test-only branch, and no knowledge that it is under test.
10
+ //
11
+ // Lambda functions are declared next to the services and deployed from the
12
+ // project's own source. Deployment happens in the service `setup` hook, which
13
+ // runs before the warm-template snapshot, so a warm start restores functions
14
+ // that are already deployed, already active, and already warm.
15
+ //
16
+ // ── Internal notes (deliberately not in the user-facing docs) ──────────────
17
+ //
18
+ // The backing image is MiniStack (MIT, github.com/ministackorg/ministack),
19
+ // pinned rather than floated. It replaced LocalStack, which folded its
20
+ // Apache-2.0 Community edition into one paid product in March 2026 (current
21
+ // images demand a LOCALSTACK_AUTH_TOKEN). MiniStack also suits fork-per-test
22
+ // far better: ~270 MB against ~1 GB and a ~2 s boot.
23
+ //
24
+ // Lambda runs in MiniStack's **docker** executor, never its default `local`
25
+ // one, because `local` has no runtime fidelity at all: it maps `python*` to
26
+ // its own `sys.executable` and `nodejs*` to its own `node`, so the declared
27
+ // `Runtime` selects only the language. A function declared `python3.11` runs
28
+ // on the emulator image's CPython 3.13/musl, and one declared `nodejs20.x`
29
+ // runs on Node 24 — which is why a native wheel built for the real target
30
+ // fails to import ("No module named 'pydantic_core._pydantic_core'"). The
31
+ // docker executor runs the handler under AWS's own Runtime Interface
32
+ // Emulator in `public.ecr.aws/lambda/<runtime>`, giving the real
33
+ // interpreter, glibc, `/var/task` and `AWS_EXECUTION_ENV`. Measured on
34
+ // aarch64: it is also ~7x FASTER per warm invoke (7 ms against 53 ms) at
35
+ // ~25-40 MiB per function container.
36
+ //
37
+ // None of this is configurable, on purpose — a knob here is a knob between
38
+ // "behaves like AWS" and "does not".
39
+ //
40
+ // The cost is a bind-mount of the VM's own docker socket, which the daemon
41
+ // already supports (`ensureVolumes` treats an existing non-directory source
42
+ // as a thing to mount as-is). The RIE containers are ordinary VM containers
43
+ // on `spectest-net`, so they ride snapshots and forks like any service: a
44
+ // per-test fork inherits its parent's already-warm function.
45
+ //
46
+ // Landmine: the runtime images are pulled from `public.ecr.aws`, which the
47
+ // in-VM dockerd reaches DIRECTLY. Its `registry-mirrors` only ever applies
48
+ // to Docker Hub, so the zot mirror (which does carry public.ecr.aws, on
49
+ // :5004) is NOT consulted. MiniStack's own `MINISTACK_IMAGE_PREFIX` cannot
50
+ // close that gap either: it prepends rather than replacing the registry
51
+ // host. Routing these pulls through zot needs a pre-pull of
52
+ // `spectest-host:5004/lambda/<rt>` retagged to the `public.ecr.aws` name.
53
+ //
54
+ // Like `email()`'s mail server, the product name stays out of every
55
+ // user-facing surface (docs, examples, error messages). Users get "the AWS
56
+ // emulator"; `image` swaps it.
57
+ //
58
+ // The emulator ignores SigV4 and does not check that a role exists, both
59
+ // verified on 1.4.8. That is what lets this component deploy over plain
60
+ // unsigned HTTP from the daemon and skip IAM entirely.
61
+ import { readFile, readdir, stat } from "node:fs/promises";
62
+ import path from "node:path";
63
+ import { deflateRawSync } from "node:zlib";
64
+ import { certificate, provides, proxy, SELF_SERVICE_TOKEN } from "../index.js";
65
+ import { pauseRecording, resumeRecording } from "../recorder.js";
66
+ /** Backing image, pinned internally (not part of the documented surface). */
67
+ const AWS_IMAGE = "ministackorg/ministack:1.4.8";
68
+ /** Port the emulator serves every AWS API on. Internal: callers reach the
69
+ * emulator through the AWS hostnames, never through this port. */
70
+ const AWS_PORT = 4566;
71
+ // Every AWS region, so the component can answer for all of them and the user
72
+ // never has to declare which ones the app uses. Enumeration is forced by TLS,
73
+ // not by routing: a wildcard *route* matches any depth, but a wildcard
74
+ // *certificate* covers exactly one label (RFC 6125, enforced by every
75
+ // client), so `*.amazonaws.com` cannot serve `states.us-east-1.amazonaws.com`
76
+ // — each region needs its own `*.<region>.amazonaws.com` name. They all ride
77
+ // ONE certificate as SANs and one shared upstream, so the list costs a few
78
+ // route-table entries, not a key generation each.
79
+ //
80
+ // Sourced from AWS's own published `ip-ranges.json` (2026-07-31). A region
81
+ // added later is simply not claimed: its endpoints fail to resolve, which
82
+ // says plainly what happened — add it here.
83
+ const AWS_REGIONS = [
84
+ "af-south-1", "ap-east-1", "ap-east-2", "ap-northeast-1", "ap-northeast-2",
85
+ "ap-northeast-3", "ap-south-1", "ap-south-2", "ap-southeast-1", "ap-southeast-2",
86
+ "ap-southeast-3", "ap-southeast-4", "ap-southeast-5", "ap-southeast-6",
87
+ "ap-southeast-7", "ca-central-1", "ca-west-1", "eu-central-1", "eu-central-2",
88
+ "eu-north-1", "eu-south-1", "eu-south-2", "eu-west-1", "eu-west-2", "eu-west-3",
89
+ "eusc-de-east-1", "il-central-1", "me-central-1", "me-south-1", "me-west-1",
90
+ "mx-central-1", "sa-east-1", "sa-west-1", "us-east-1", "us-east-2",
91
+ "us-gov-east-1", "us-gov-west-1", "us-south-1", "us-west-1", "us-west-2",
92
+ ];
93
+ /** China is a separate partition on its own domain suffix. */
94
+ const AWS_CN_REGIONS = ["cn-north-1", "cn-northwest-1"];
95
+ /** Every hostname pattern the emulator answers to: the two partitions' global
96
+ * endpoints (`sts.amazonaws.com`, `iam.amazonaws.com`) plus one per region
97
+ * for the regional ones (`states.us-east-1.amazonaws.com`). */
98
+ const AWS_HOST_PATTERNS = [
99
+ "*.amazonaws.com",
100
+ ...AWS_REGIONS.map((r) => `*.${r}.amazonaws.com`),
101
+ "*.amazonaws.com.cn",
102
+ ...AWS_CN_REGIONS.map((r) => `*.${r}.amazonaws.com.cn`),
103
+ ];
104
+ /** The VM's own docker socket, bind-mounted so the emulator can start the
105
+ * official AWS runtime containers. This is the VM's dockerd, inside the
106
+ * hermetic environment — the same daemon that runs the services. */
107
+ const DOCKER_SOCKET = "/var/run/docker.sock";
108
+ /** The network the function containers join, so a handler reaches the other
109
+ * services and the AWS endpoints by the same names a test uses. */
110
+ const SPECTEST_NETWORK = "spectest-net";
111
+ /** Region the emulator's own tools default to — the AWS CLI refuses to run
112
+ * without one. Only the *container's* default; it constrains nothing about
113
+ * the app, and every region is served regardless. A `setup` hook that drives
114
+ * the CLI against another region passes `--region`. */
115
+ const CONTAINER_DEFAULT_REGION = "us-east-1";
116
+ /** Role every declared function is created with. The emulator does not
117
+ * enforce IAM, so this only has to be a well-formed ARN — which is why the
118
+ * component creates no role and takes no IAM options. A project that wants a
119
+ * real-looking role can create one itself and set `role` on the function. */
120
+ const DEFAULT_ROLE_ARN = "arn:aws:iam::000000000000:role/spectest-lambda";
121
+ /** Ready-check budget. The emulator boots in a couple of seconds; the slow
122
+ * part is a cold image pull on a machine that has never run it. */
123
+ const READY_TIMEOUT_SECS = 120;
124
+ /** Memory every declared function is created with. Kept at what this
125
+ * component has always used, rather than the emulator's own default, so the
126
+ * removal of the `memoryMb` option changed no behaviour. */
127
+ const MEMORY_MB = 512;
128
+ /**
129
+ * The AWS cloud APIs, emulated in the environment and answering at their real
130
+ * endpoints. Drop into `environment.services`:
131
+ *
132
+ * ```ts
133
+ * import { aws } from "@specific.dev/spectest/components";
134
+ *
135
+ * services: {
136
+ * aws: aws({
137
+ * lambdas: {
138
+ * add: { source: "lambda/add" },
139
+ * subtract: { source: "lambda/subtract" },
140
+ * },
141
+ * }),
142
+ * app: {
143
+ * image: { type: "dockerfile", content: appDockerfile },
144
+ * // Whatever the app already reads in production. An AWS SDK needs a
145
+ * // region and credentials; the emulator accepts any credential value.
146
+ * env: {
147
+ * AWS_REGION: "us-east-1",
148
+ * AWS_ACCESS_KEY_ID: "test",
149
+ * AWS_SECRET_ACCESS_KEY: "test",
150
+ * },
151
+ * dependsOn: ["aws"],
152
+ * },
153
+ * }
154
+ * ```
155
+ *
156
+ * The app keeps its production configuration — `new SFNClient({})`, no
157
+ * endpoint — because the component owns DNS and TLS for the AWS domains. It
158
+ * answers for **every region**, so an app that talks to two of them, or that
159
+ * reads its region from configuration, needs nothing declared here.
160
+ *
161
+ * Tests reach the same cloud with the AWS CLI, which the emulator's image
162
+ * ships as `awslocal` (the CLI, already pointed at it):
163
+ *
164
+ * ```ts
165
+ * const listed = await ctx.exec("aws", "awslocal stepfunctions list-state-machines");
166
+ * expect(listed.exitCode).toBe(0);
167
+ * const machines = listed.stdout.transform("machines", (out) =>
168
+ * (JSON.parse(out) as { stateMachines: unknown[] }).stateMachines,
169
+ * );
170
+ * expect(machines).toHaveLength(1);
171
+ * ```
172
+ *
173
+ * For S3, prefer the `s3()` component and give it the endpoint your app uses
174
+ * (`s3({ hosts: ["s3.us-east-1.amazonaws.com"] })`). An exact hostname always
175
+ * beats this component's wildcard, so the two compose without further
176
+ * configuration.
177
+ */
178
+ export function aws(opts = {}) {
179
+ const lambdas = opts.lambdas ?? {};
180
+ const service = {
181
+ image: { type: "registry", reference: AWS_IMAGE },
182
+ env: {
183
+ AWS_DEFAULT_REGION: CONTAINER_DEFAULT_REGION,
184
+ // Run every function in the official AWS runtime image rather than in
185
+ // the emulator's own interpreter — see the note at the top of the file.
186
+ LAMBDA_EXECUTOR: "docker",
187
+ // No silent fall-back to the low-fidelity executor. If the runtime
188
+ // container cannot start, say so instead of running the handler on the
189
+ // wrong interpreter and failing later, somewhere else.
190
+ LAMBDA_STRICT: "1",
191
+ LAMBDA_DOCKER_NETWORK: SPECTEST_NETWORK,
192
+ },
193
+ volumes: [{ source: DOCKER_SOCKET, target: DOCKER_SOCKET }],
194
+ ports: [AWS_PORT],
195
+ readyCheck: {
196
+ type: "http",
197
+ port: AWS_PORT,
198
+ path: "/_ministack/health",
199
+ timeoutSecs: READY_TIMEOUT_SECS,
200
+ },
201
+ ...(Object.keys(lambdas).length > 0
202
+ ? {
203
+ setup: async ({ name, projectRoot }) => {
204
+ for (const [fn, spec] of Object.entries(lambdas)) {
205
+ await deployLambda(name, projectRoot, fn, spec);
206
+ }
207
+ },
208
+ }
209
+ : {}),
210
+ };
211
+ // The low-level primitives rather than the `tls` field, for one reason:
212
+ // `tls` mints a separate leaf certificate per entry, and this component
213
+ // claims several dozen names. One `certificate(...)` decl carries them all
214
+ // as SANs of a single leaf — one key generation at bring-up instead of
215
+ // dozens — while the proxies are just route-table entries.
216
+ return provides(service, [
217
+ certificate(AWS_HOST_PATTERNS),
218
+ ...AWS_HOST_PATTERNS.map((hostname) => proxy(hostname, { service: SELF_SERVICE_TOKEN, port: AWS_PORT })),
219
+ ]);
220
+ }
221
+ // ──────────────────────────────────────────────────────────────────────────
222
+ // Talking to the emulator directly
223
+ //
224
+ // The emulator ignores request signatures, so the daemon reaches its APIs
225
+ // over plain unsigned HTTP. That keeps deployment independent of what tools
226
+ // the image happens to ship, and keeps a poll loop cheap.
227
+ // ──────────────────────────────────────────────────────────────────────────
228
+ /** One JSON-protocol AWS call (Step Functions, DynamoDB, …), by target. */
229
+ async function request(service, method, urlPath, init = {}) {
230
+ // Never let the component's own traffic land on the timeline: these calls
231
+ // are bring-up and polling, not something a test asked for.
232
+ pauseRecording();
233
+ try {
234
+ const res = await fetch(`http://${service}:${AWS_PORT}${urlPath}`, {
235
+ method,
236
+ headers: { "content-type": "application/json", ...(init.headers ?? {}) },
237
+ ...(init.body !== undefined ? { body: init.body } : {}),
238
+ });
239
+ // Coerced rather than read directly: `fetch` is wrapped during a test, so
240
+ // `res.status` is a provenance carrier there and a plain number elsewhere.
241
+ const status = Number(res.status);
242
+ const text = String(await res.text());
243
+ if (status >= 400) {
244
+ const err = new Error(`aws: ${method} ${urlPath} failed: HTTP ${status} ${text.slice(0, 400)}`);
245
+ err.status = status;
246
+ throw err;
247
+ }
248
+ return text === "" ? undefined : JSON.parse(text);
249
+ }
250
+ finally {
251
+ resumeRecording();
252
+ }
253
+ }
254
+ // ──────────────────────────────────────────────────────────────────────────
255
+ // Lambda deployment
256
+ // ──────────────────────────────────────────────────────────────────────────
257
+ /** Refuse a package that no real deployment would accept either. */
258
+ const MAX_PACKAGE_BYTES = 64 * 1024 * 1024;
259
+ async function deployLambda(service, projectRoot, name, spec) {
260
+ if (typeof spec?.source !== "string" || spec.source.trim() === "") {
261
+ throw new Error(`aws: lambda "${name}" needs a \`source\` path to its code`);
262
+ }
263
+ const zipped = await packageSource(projectRoot, name, spec.source);
264
+ if (zipped.length > MAX_PACKAGE_BYTES) {
265
+ throw new Error(`aws: lambda "${name}" packages to ${Math.round(zipped.length / 1e6)} MB from ` +
266
+ `${spec.source} — over the ${MAX_PACKAGE_BYTES / 1e6} MB limit. Point \`source\` at ` +
267
+ `the function's own directory, not a whole repository.`);
268
+ }
269
+ const code = Buffer.from(zipped).toString("base64");
270
+ const config = {
271
+ Runtime: spec.runtime ?? "nodejs20.x",
272
+ Handler: spec.handler ?? "index.handler",
273
+ Role: spec.role ?? DEFAULT_ROLE_ARN,
274
+ Timeout: spec.timeoutSecs ?? 30,
275
+ // Fixed, and not an option: the emulated cloud reports this number back
276
+ // as `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` but never caps the runtime
277
+ // container at it, so the number changes nothing about how a function
278
+ // behaves here.
279
+ MemorySize: MEMORY_MB,
280
+ ...(spec.env ? { Environment: { Variables: spec.env } } : {}),
281
+ };
282
+ try {
283
+ await request(service, "POST", "/2015-03-31/functions", {
284
+ body: JSON.stringify({ FunctionName: name, Code: { ZipFile: code }, ...config }),
285
+ });
286
+ }
287
+ catch (err) {
288
+ // Already there: a re-run of bring-up against an emulator that kept its
289
+ // state. Update instead, so the deployed code always matches the repo.
290
+ if (err.status !== 409)
291
+ throw err;
292
+ await request(service, "PUT", `/2015-03-31/functions/${encodeURIComponent(name)}/code`, {
293
+ body: JSON.stringify({ ZipFile: code }),
294
+ });
295
+ await request(service, "PUT", `/2015-03-31/functions/${encodeURIComponent(name)}/configuration`, {
296
+ body: JSON.stringify(config),
297
+ });
298
+ }
299
+ await waitActive(service, name);
300
+ // One invoke with an empty event, purely to leave a warm worker behind in
301
+ // the snapshot, so no test pays a cold start. The handler may well reject
302
+ // the event — that is fine, the worker is started either way.
303
+ try {
304
+ await request(service, "POST", `/2015-03-31/functions/${encodeURIComponent(name)}/invocations`, {
305
+ body: "{}",
306
+ });
307
+ }
308
+ catch {
309
+ // Ignored on purpose: warming is an optimisation, never a gate.
310
+ }
311
+ }
312
+ /** Wait for a newly created function to leave `Pending`, exactly as a real
313
+ * deployment must. Tolerates an emulator that reports no state at all. */
314
+ async function waitActive(service, name, timeoutMs = 60_000) {
315
+ const deadline = Date.now() + timeoutMs;
316
+ for (;;) {
317
+ const cfg = (await request(service, "GET", `/2015-03-31/functions/${encodeURIComponent(name)}/configuration`));
318
+ const state = cfg?.State;
319
+ if (state === undefined || state === "Active")
320
+ return;
321
+ if (state === "Failed") {
322
+ throw new Error(`aws: lambda "${name}" failed to deploy: ${cfg?.StateReason ?? "no reason given"}`);
323
+ }
324
+ if (Date.now() > deadline) {
325
+ throw new Error(`aws: lambda "${name}" was still ${state} after ${timeoutMs} ms`);
326
+ }
327
+ await new Promise((resolve) => setTimeout(resolve, 100));
328
+ }
329
+ }
330
+ async function packageSource(projectRoot, fnName, source) {
331
+ const root = path.isAbsolute(source) ? source : path.join(projectRoot, source);
332
+ let info;
333
+ try {
334
+ info = await stat(root);
335
+ }
336
+ catch {
337
+ throw new Error(`aws: lambda "${fnName}" has no code at ${source} (looked in ${root}). ` +
338
+ `\`source\` is a path in your repository, relative to its root.`);
339
+ }
340
+ const entries = [];
341
+ if (info.isDirectory()) {
342
+ await collect(root, "", entries);
343
+ if (entries.length === 0) {
344
+ throw new Error(`aws: lambda "${fnName}" has no files in ${source}`);
345
+ }
346
+ }
347
+ else {
348
+ entries.push({ name: path.basename(root), data: await readFile(root) });
349
+ }
350
+ // Sorted so the same source always packages to the same bytes.
351
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
352
+ return buildZip(entries);
353
+ }
354
+ async function collect(dir, prefix, out) {
355
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
356
+ const full = path.join(dir, entry.name);
357
+ const rel = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
358
+ if (entry.isDirectory()) {
359
+ await collect(full, rel, out);
360
+ }
361
+ else if (entry.isFile()) {
362
+ out.push({ name: rel, data: await readFile(full) });
363
+ }
364
+ // Symlinks and everything else are skipped: a deployment package holds
365
+ // regular files.
366
+ }
367
+ }
368
+ function crc32(buf) {
369
+ let crc = 0xffffffff;
370
+ for (let i = 0; i < buf.length; i++) {
371
+ let c = (crc ^ buf[i]) & 0xff;
372
+ for (let k = 0; k < 8; k++)
373
+ c = c & 1 ? (c >>> 1) ^ 0xedb88320 : c >>> 1;
374
+ crc = (crc >>> 8) ^ c;
375
+ }
376
+ return (crc ^ 0xffffffff) >>> 0;
377
+ }
378
+ /**
379
+ * Build a zip archive. Entries are deflated (method 8), or stored (method 0)
380
+ * when deflating makes them no smaller. Timestamps are fixed, so identical
381
+ * sources always produce identical bytes.
382
+ */
383
+ function buildZip(entries) {
384
+ const encoder = new TextEncoder();
385
+ const local = [];
386
+ const central = [];
387
+ let offset = 0;
388
+ for (const entry of entries) {
389
+ const nameBytes = encoder.encode(entry.name);
390
+ const crc = crc32(entry.data);
391
+ const deflated = new Uint8Array(deflateRawSync(entry.data));
392
+ const stored = deflated.length >= entry.data.length;
393
+ const payload = stored ? entry.data : deflated;
394
+ const method = stored ? 0 : 8;
395
+ const header = new DataView(new ArrayBuffer(30));
396
+ header.setUint32(0, 0x04034b50, true); // local file header
397
+ header.setUint16(4, 20, true); // version needed
398
+ header.setUint16(6, 0, true); // flags
399
+ header.setUint16(8, method, true);
400
+ header.setUint16(10, 0, true); // time — fixed
401
+ header.setUint16(12, 0x21, true); // date — fixed (1 Jan 1980)
402
+ header.setUint32(14, crc, true);
403
+ header.setUint32(18, payload.length, true);
404
+ header.setUint32(22, entry.data.length, true);
405
+ header.setUint16(26, nameBytes.length, true);
406
+ header.setUint16(28, 0, true); // extra length
407
+ const headerBytes = new Uint8Array(header.buffer);
408
+ local.push(headerBytes, nameBytes, payload);
409
+ const dirEntry = new DataView(new ArrayBuffer(46));
410
+ dirEntry.setUint32(0, 0x02014b50, true); // central directory header
411
+ dirEntry.setUint16(4, 20, true); // version made by
412
+ dirEntry.setUint16(6, 20, true); // version needed
413
+ dirEntry.setUint16(8, 0, true); // flags
414
+ dirEntry.setUint16(10, method, true);
415
+ dirEntry.setUint16(12, 0, true);
416
+ dirEntry.setUint16(14, 0x21, true);
417
+ dirEntry.setUint32(16, crc, true);
418
+ dirEntry.setUint32(20, payload.length, true);
419
+ dirEntry.setUint32(24, entry.data.length, true);
420
+ dirEntry.setUint16(28, nameBytes.length, true);
421
+ // Permissions in the high half of the external attributes: 0644 for a
422
+ // regular file, which is what a Lambda runtime expects to find.
423
+ dirEntry.setUint32(38, 0o100644 << 16, true);
424
+ dirEntry.setUint32(42, offset, true);
425
+ central.push(new Uint8Array(dirEntry.buffer), nameBytes);
426
+ offset += headerBytes.length + nameBytes.length + payload.length;
427
+ }
428
+ const centralSize = central.reduce((n, part) => n + part.length, 0);
429
+ const end = new DataView(new ArrayBuffer(22));
430
+ end.setUint32(0, 0x06054b50, true); // end of central directory
431
+ end.setUint16(8, entries.length, true);
432
+ end.setUint16(10, entries.length, true);
433
+ end.setUint32(12, centralSize, true);
434
+ end.setUint32(16, offset, true);
435
+ const parts = [...local, ...central, new Uint8Array(end.buffer)];
436
+ const total = parts.reduce((n, part) => n + part.length, 0);
437
+ const zipped = new Uint8Array(total);
438
+ let cursor = 0;
439
+ for (const part of parts) {
440
+ zipped.set(part, cursor);
441
+ cursor += part.length;
442
+ }
443
+ return zipped;
444
+ }
@@ -5,4 +5,5 @@ export { k3s, type K3sOptions, type K3sHelpers, type K3sClient, type TaggedObjec
5
5
  export { expo, type ExpoOptions, type ExpoHelpers, } from "./expo.js";
6
6
  export { supabase, type SupabaseOptions, type SupabaseHelpers, type SupabaseStack, } from "./supabase.js";
7
7
  export { email, type EmailOptions, type EmailHelpers, type EmailMessage, type EmailSummary, type EmailMatch, type EmailAttachment, } from "./email.js";
8
+ export { aws, type AwsOptions, type LambdaOptions, } from "./aws.js";
8
9
  export { replayFake, type ReplayFakeOptions, type ReplayMatch, type InjectRule, type InjectMatch, type StringMatch, type SignConfig, type AwsSigV4Sign, type ReplayHelpers, type ReplaySummary, type Cassette, type CassetteInteraction, type CassetteRequest, type CassetteResponse, type CassetteState, } from "./replayFake.js";
@@ -15,4 +15,5 @@ export { k3s, } from "./k3s.js";
15
15
  export { expo, } from "./expo.js";
16
16
  export { supabase, } from "./supabase.js";
17
17
  export { email, } from "./email.js";
18
+ export { aws, } from "./aws.js";
18
19
  export { replayFake, } from "./replayFake.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@specific.dev/spectest",
3
- "version": "0.33.0",
3
+ "version": "0.35.0",
4
4
  "description": "Spectest SDK for defining test environments in TypeScript.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",