@ericminassian/platform-engine 0.0.0-stage → 0.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 (90) hide show
  1. package/dist/clients.d.ts +50 -0
  2. package/dist/clients.js +103 -0
  3. package/dist/clients.js.map +1 -0
  4. package/dist/compat.d.ts +19 -0
  5. package/dist/compat.js +63 -0
  6. package/dist/compat.js.map +1 -0
  7. package/dist/drivers/cognito.d.ts +18 -0
  8. package/dist/drivers/cognito.js +113 -0
  9. package/dist/drivers/cognito.js.map +1 -0
  10. package/dist/drivers/dynamodb.d.ts +26 -0
  11. package/dist/drivers/dynamodb.js +151 -0
  12. package/dist/drivers/dynamodb.js.map +1 -0
  13. package/dist/drivers/events.d.ts +21 -0
  14. package/dist/drivers/events.js +62 -0
  15. package/dist/drivers/events.js.map +1 -0
  16. package/dist/drivers/iam.d.ts +20 -0
  17. package/dist/drivers/iam.js +86 -0
  18. package/dist/drivers/iam.js.map +1 -0
  19. package/dist/drivers/index.d.ts +12 -0
  20. package/dist/drivers/index.js +13 -0
  21. package/dist/drivers/index.js.map +1 -0
  22. package/dist/drivers/kvs.d.ts +5 -0
  23. package/dist/drivers/kvs.js +28 -0
  24. package/dist/drivers/kvs.js.map +1 -0
  25. package/dist/drivers/lambda.d.ts +48 -0
  26. package/dist/drivers/lambda.js +158 -0
  27. package/dist/drivers/lambda.js.map +1 -0
  28. package/dist/drivers/logs.d.ts +20 -0
  29. package/dist/drivers/logs.js +62 -0
  30. package/dist/drivers/logs.js.map +1 -0
  31. package/dist/drivers/s3.d.ts +30 -0
  32. package/dist/drivers/s3.js +126 -0
  33. package/dist/drivers/s3.js.map +1 -0
  34. package/dist/drivers/scheduler.d.ts +21 -0
  35. package/dist/drivers/scheduler.js +59 -0
  36. package/dist/drivers/scheduler.js.map +1 -0
  37. package/dist/drivers/sqs.d.ts +18 -0
  38. package/dist/drivers/sqs.js +46 -0
  39. package/dist/drivers/sqs.js.map +1 -0
  40. package/dist/drivers/ssm.d.ts +16 -0
  41. package/dist/drivers/ssm.js +45 -0
  42. package/dist/drivers/ssm.js.map +1 -0
  43. package/dist/drivers/web-function.d.ts +71 -0
  44. package/dist/drivers/web-function.js +227 -0
  45. package/dist/drivers/web-function.js.map +1 -0
  46. package/dist/emulator.d.ts +51 -0
  47. package/dist/emulator.js +142 -0
  48. package/dist/emulator.js.map +1 -0
  49. package/dist/index.d.ts +140 -0
  50. package/dist/index.js +72 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/local.d.ts +12 -0
  53. package/dist/local.js +71 -0
  54. package/dist/local.js.map +1 -0
  55. package/dist/policy.d.ts +41 -0
  56. package/dist/policy.js +316 -0
  57. package/dist/policy.js.map +1 -0
  58. package/dist/stage.d.ts +19 -0
  59. package/dist/stage.js +479 -0
  60. package/dist/stage.js.map +1 -0
  61. package/dist/static.d.ts +9 -0
  62. package/dist/static.js +55 -0
  63. package/dist/static.js.map +1 -0
  64. package/dist/util.d.ts +56 -0
  65. package/dist/util.js +127 -0
  66. package/dist/util.js.map +1 -0
  67. package/package.json +48 -3
  68. package/src/clients.ts +140 -0
  69. package/src/compat.ts +63 -0
  70. package/src/drivers/cognito.ts +147 -0
  71. package/src/drivers/dynamodb.ts +206 -0
  72. package/src/drivers/events.ts +92 -0
  73. package/src/drivers/iam.ts +125 -0
  74. package/src/drivers/index.ts +12 -0
  75. package/src/drivers/kvs.ts +55 -0
  76. package/src/drivers/lambda.ts +283 -0
  77. package/src/drivers/logs.ts +81 -0
  78. package/src/drivers/s3.ts +196 -0
  79. package/src/drivers/scheduler.ts +90 -0
  80. package/src/drivers/sqs.ts +70 -0
  81. package/src/drivers/ssm.ts +65 -0
  82. package/src/drivers/web-function.ts +352 -0
  83. package/src/emulator.ts +203 -0
  84. package/src/index.ts +183 -0
  85. package/src/local.ts +75 -0
  86. package/src/policy.ts +377 -0
  87. package/src/stage.ts +568 -0
  88. package/src/static.ts +56 -0
  89. package/src/util.ts +175 -0
  90. package/README.md +0 -3
@@ -0,0 +1,70 @@
1
+ import {
2
+ CreateQueueCommand,
3
+ DeleteQueueCommand,
4
+ GetQueueAttributesCommand,
5
+ GetQueueUrlCommand,
6
+ ListQueuesCommand,
7
+ SetQueueAttributesCommand,
8
+ TagQueueCommand,
9
+ } from '@aws-sdk/client-sqs';
10
+ import { type EngineContext, ignoreNotFound } from '../util.ts';
11
+
12
+ export interface QueueState {
13
+ name: string;
14
+ url: string;
15
+ arn: string;
16
+ created: boolean;
17
+ }
18
+
19
+ export async function getQueueUrl(ctx: EngineContext, name: string): Promise<string | undefined> {
20
+ const res = await ignoreNotFound(ctx.clients.sqs.send(new GetQueueUrlCommand({ QueueName: name })));
21
+ return res?.QueueUrl;
22
+ }
23
+
24
+ export async function ensureQueue(
25
+ ctx: EngineContext,
26
+ spec: { name: string; attributes?: Record<string, string>; tags?: Record<string, string> },
27
+ ): Promise<QueueState> {
28
+ const sqs = ctx.clients.sqs;
29
+ let url = await getQueueUrl(ctx, spec.name);
30
+ let created = false;
31
+ if (!url) {
32
+ const res = await sqs.send(
33
+ new CreateQueueCommand({ QueueName: spec.name, Attributes: spec.attributes, tags: spec.tags }),
34
+ );
35
+ url = res.QueueUrl!;
36
+ created = true;
37
+ ctx.log('info', 'created queue', `queue ${spec.name}`);
38
+ } else {
39
+ if (spec.attributes && Object.keys(spec.attributes).length) {
40
+ await sqs.send(new SetQueueAttributesCommand({ QueueUrl: url, Attributes: spec.attributes }));
41
+ }
42
+ if (spec.tags) await sqs.send(new TagQueueCommand({ QueueUrl: url, Tags: spec.tags }));
43
+ }
44
+ const attrs = await sqs.send(
45
+ new GetQueueAttributesCommand({ QueueUrl: url, AttributeNames: ['QueueArn'] }),
46
+ );
47
+ return { name: spec.name, url, arn: attrs.Attributes!.QueueArn!, created };
48
+ }
49
+
50
+ export async function deleteQueue(ctx: EngineContext, name: string): Promise<boolean> {
51
+ const url = await getQueueUrl(ctx, name);
52
+ if (!url) return false;
53
+ await ignoreNotFound(ctx.clients.sqs.send(new DeleteQueueCommand({ QueueUrl: url })));
54
+ ctx.log('info', 'deleted queue', `queue ${name}`);
55
+ return true;
56
+ }
57
+
58
+ export async function listQueues(
59
+ ctx: EngineContext,
60
+ prefix: string,
61
+ ): Promise<Array<{ name: string; url: string }>> {
62
+ const out: Array<{ name: string; url: string }> = [];
63
+ let NextToken: string | undefined;
64
+ do {
65
+ const res = await ctx.clients.sqs.send(new ListQueuesCommand({ QueueNamePrefix: prefix, NextToken }));
66
+ for (const url of res.QueueUrls ?? []) out.push({ url, name: url.slice(url.lastIndexOf('/') + 1) });
67
+ NextToken = res.NextToken;
68
+ } while (NextToken);
69
+ return out;
70
+ }
@@ -0,0 +1,65 @@
1
+ import {
2
+ DeleteParametersCommand,
3
+ GetParameterCommand,
4
+ GetParametersByPathCommand,
5
+ PutParameterCommand,
6
+ } from '@aws-sdk/client-ssm';
7
+ import { type EngineContext, ignoreNotFound } from '../util.ts';
8
+
9
+ export async function getParameter(
10
+ ctx: EngineContext,
11
+ name: string,
12
+ decrypt = true,
13
+ ): Promise<string | undefined> {
14
+ const res = await ignoreNotFound(
15
+ ctx.clients.ssm.send(new GetParameterCommand({ Name: name, WithDecryption: decrypt })),
16
+ );
17
+ return res?.Parameter?.Value;
18
+ }
19
+
20
+ export async function putParameter(
21
+ ctx: EngineContext,
22
+ spec: { name: string; value: string; secure?: boolean; description?: string },
23
+ ): Promise<void> {
24
+ await ctx.clients.ssm.send(
25
+ new PutParameterCommand({
26
+ Name: spec.name,
27
+ Value: spec.value,
28
+ Type: spec.secure ? 'SecureString' : 'String',
29
+ Description: spec.description,
30
+ Overwrite: true,
31
+ Tier: Buffer.byteLength(spec.value) > 4096 ? 'Advanced' : 'Standard',
32
+ }),
33
+ );
34
+ }
35
+
36
+ /** Create the parameter only if it doesn't exist (e.g. a generated key). Returns the current value. */
37
+ export async function ensureParameterOnce(
38
+ ctx: EngineContext,
39
+ spec: { name: string; secure?: boolean; description?: string; generate: () => string },
40
+ ): Promise<string> {
41
+ const current = await getParameter(ctx, spec.name);
42
+ if (current !== undefined) return current;
43
+ const value = spec.generate();
44
+ await putParameter(ctx, { name: spec.name, value, secure: spec.secure, description: spec.description });
45
+ ctx.log('info', 'created parameter', `parameter ${spec.name}`);
46
+ return value;
47
+ }
48
+
49
+ export async function deleteParametersByPath(ctx: EngineContext, path: string): Promise<number> {
50
+ const ssm = ctx.clients.ssm;
51
+ const names: string[] = [];
52
+ let NextToken: string | undefined;
53
+ do {
54
+ const res = await ignoreNotFound(
55
+ ssm.send(new GetParametersByPathCommand({ Path: path, Recursive: true, NextToken })),
56
+ );
57
+ if (!res) break;
58
+ for (const p of res.Parameters ?? []) if (p.Name) names.push(p.Name);
59
+ NextToken = res.NextToken;
60
+ } while (NextToken);
61
+ for (let i = 0; i < names.length; i += 10) {
62
+ await ssm.send(new DeleteParametersCommand({ Names: names.slice(i, i + 10) }));
63
+ }
64
+ return names.length;
65
+ }
@@ -0,0 +1,352 @@
1
+ import {
2
+ CreateWebFunctionCommand,
3
+ CreateWebFunctionEndpointCommand,
4
+ CreateWebFunctionRevisionCommand,
5
+ DeleteResourcePolicyCommand,
6
+ DeleteWebFunctionCommand,
7
+ DeleteWebFunctionEndpointCommand,
8
+ DeleteWebFunctionRevisionCommand,
9
+ GetResourcePolicyCommand,
10
+ GetWebFunctionCommand,
11
+ GetWebFunctionEndpointCommand,
12
+ GetWebFunctionRevisionCommand,
13
+ ListWebFunctionEndpointsCommand,
14
+ ListWebFunctionRevisionsCommand,
15
+ PutResourcePolicyCommand,
16
+ UpdateWebFunctionEndpointCommand,
17
+ } from '@aws-sdk/client-lambda-web';
18
+ import type { S3Location } from '../index.ts';
19
+ import {
20
+ type EngineContext,
21
+ errorMessage,
22
+ errorName,
23
+ ignoreNotFound,
24
+ isNotImplemented,
25
+ retry,
26
+ waitFor,
27
+ } from '../util.ts';
28
+
29
+ /**
30
+ * Lambda Web Functions (launched 2026-10): a function holds immutable
31
+ * revisions; an endpoint routes traffic to up to two revisions by weight.
32
+ * The engine always routes 100% to the newest revision and keeps the
33
+ * previous one around for instant rollback.
34
+ */
35
+
36
+ export interface RevisionSpec {
37
+ functionName: string;
38
+ code: S3Location;
39
+ runtime: string;
40
+ roleArn: string;
41
+ env: Record<string, string>;
42
+ timeoutSeconds: number;
43
+ maxConcurrency: number;
44
+ logGroup: string;
45
+ description?: string;
46
+ }
47
+
48
+ function revisionConfig(spec: RevisionSpec) {
49
+ return {
50
+ description: spec.description,
51
+ buildConfig: {
52
+ codeConfig: {
53
+ s3Object: { bucket: spec.code.bucket, key: spec.code.key, versionId: spec.code.versionId },
54
+ },
55
+ runtimeConfig: { runtime: spec.runtime },
56
+ },
57
+ serviceConfig: {
58
+ executionRoleArn: spec.roleArn,
59
+ timeoutSeconds: spec.timeoutSeconds,
60
+ maxConcurrencyPerEnvironment: spec.maxConcurrency,
61
+ environmentVariables: spec.env,
62
+ telemetryConfig: { loggingConfig: { logGroup: spec.logGroup } },
63
+ },
64
+ };
65
+ }
66
+
67
+ /** A just-created execution role isn't assumable yet (IAM eventual consistency). */
68
+ const rolePropagating = (e: unknown) =>
69
+ /role|assume/i.test(errorMessage(e)) && errorName(e).includes('Validation');
70
+
71
+ /**
72
+ * Ensure the function exists. AWS only creates a Web Function together with
73
+ * its first revision and endpoint, so a missing function is created from
74
+ * `initial`; the returned `initialRevisionId` is then the revision to route
75
+ * to (no separate CreateWebFunctionRevision needed).
76
+ */
77
+ export async function ensureWebFunction(
78
+ ctx: EngineContext,
79
+ spec: {
80
+ name: string;
81
+ tags?: Record<string, string>;
82
+ initial: { revision: RevisionSpec; endpointName: string };
83
+ },
84
+ ): Promise<{ arn: string; initialRevisionId?: string }> {
85
+ const lw = ctx.clients.lambdaWeb;
86
+ const existing = await ignoreNotFound(lw.send(new GetWebFunctionCommand({ functionName: spec.name })));
87
+ if (existing?.functionArn) return { arn: existing.functionArn };
88
+ const res = await retry(
89
+ () =>
90
+ lw.send(
91
+ new CreateWebFunctionCommand({
92
+ functionName: spec.name,
93
+ tags: spec.tags,
94
+ revisionConfig: revisionConfig(spec.initial.revision),
95
+ endpointConfig: {
96
+ endpointName: spec.initial.endpointName,
97
+ endpointType: 'HomeRegion',
98
+ authType: 'IamAuth',
99
+ // Traffic moves only when the engine sets weights, so rollback stays explicit.
100
+ autoDeploymentMode: 'Disabled',
101
+ },
102
+ }),
103
+ ),
104
+ { when: rolePropagating, attempts: 15, delayMs: 2_000 },
105
+ );
106
+ ctx.log('info', 'created web function', `web-function ${spec.name}`);
107
+ const revisionId = res.revision?.revisionId;
108
+ if (revisionId) await waitRevisionActive(ctx, spec.name, revisionId);
109
+ return { arn: res.functionArn!, ...(revisionId ? { initialRevisionId: revisionId } : {}) };
110
+ }
111
+
112
+ export async function createRevision(ctx: EngineContext, spec: RevisionSpec): Promise<string> {
113
+ const lw = ctx.clients.lambdaWeb;
114
+ const res = await retry(
115
+ () =>
116
+ lw.send(
117
+ new CreateWebFunctionRevisionCommand({ functionName: spec.functionName, ...revisionConfig(spec) }),
118
+ ),
119
+ { when: rolePropagating, attempts: 15, delayMs: 2_000 },
120
+ );
121
+ await waitRevisionActive(ctx, spec.functionName, res.revisionId!);
122
+ return res.revisionId!;
123
+ }
124
+
125
+ async function waitRevisionActive(
126
+ ctx: EngineContext,
127
+ functionName: string,
128
+ revisionId: string,
129
+ ): Promise<void> {
130
+ const lw = ctx.clients.lambdaWeb;
131
+ const final = await waitFor(
132
+ `web function revision ${revisionId}`,
133
+ async () => {
134
+ const r = await lw.send(new GetWebFunctionRevisionCommand({ functionName, revisionId }));
135
+ return r.state === 'Pending' ? false : r;
136
+ },
137
+ { timeoutMs: 300_000 },
138
+ );
139
+ if (final.state !== 'Active') {
140
+ const details = (final.errors ?? []).map((e) => `${e.attribute}: ${e.errorMessage}`).join('; ');
141
+ throw new Error(
142
+ `web function revision ${revisionId} ${final.state}: ${final.stateReason ?? ''} ${details}`.trim(),
143
+ );
144
+ }
145
+ ctx.log('info', `revision ${revisionId} active`, `web-function ${functionName}`);
146
+ }
147
+
148
+ export interface EndpointState {
149
+ arn: string;
150
+ domainName: string;
151
+ revisionIds: string[];
152
+ }
153
+
154
+ /** Ensure the endpoint exists and routes 100% to `revisionId`. */
155
+ export async function ensureEndpoint(
156
+ ctx: EngineContext,
157
+ spec: { functionName: string; endpointName: string; revisionId: string },
158
+ ): Promise<EndpointState> {
159
+ const lw = ctx.clients.lambdaWeb;
160
+ const weights = [{ revisionId: spec.revisionId, weight: 100 }];
161
+ // Endpoints only accept updates while Active (a new one starts Pending).
162
+ const existing = await waitEndpointSettled(ctx, spec.functionName, spec.endpointName);
163
+ const routed =
164
+ existing?.revisionWeights?.length === 1 &&
165
+ existing.revisionWeights[0]?.revisionId === spec.revisionId &&
166
+ existing.revisionWeights[0]?.weight === 100;
167
+ if (!existing) {
168
+ await lw.send(
169
+ new CreateWebFunctionEndpointCommand({
170
+ functionName: spec.functionName,
171
+ endpointName: spec.endpointName,
172
+ endpointType: 'HomeRegion',
173
+ authType: 'IamAuth',
174
+ autoDeploymentMode: 'Disabled',
175
+ revisionWeights: weights,
176
+ }),
177
+ );
178
+ ctx.log(
179
+ 'info',
180
+ 'created web function endpoint',
181
+ `web-function ${spec.functionName}/${spec.endpointName}`,
182
+ );
183
+ } else if (!routed) {
184
+ await lw.send(
185
+ new UpdateWebFunctionEndpointCommand({
186
+ functionName: spec.functionName,
187
+ endpointName: spec.endpointName,
188
+ revisionWeights: weights,
189
+ }),
190
+ );
191
+ }
192
+ const ready = await waitFor(
193
+ `endpoint ${spec.functionName}/${spec.endpointName}`,
194
+ async () => {
195
+ const e = await getEndpoint(ctx, spec.functionName, spec.endpointName);
196
+ if (!e) return false;
197
+ if (e.state === 'Failed') throw new Error(`endpoint failed: ${e.stateReason}`);
198
+ if (e.updateStatus === 'Failed') throw new Error(`endpoint update failed: ${e.updateStatusReason}`);
199
+ return e.state === 'Active' && e.updateStatus !== 'InProgress' ? e : false;
200
+ },
201
+ { timeoutMs: 300_000 },
202
+ );
203
+ return {
204
+ arn: ready.endpointArn!,
205
+ domainName: ready.domainName!,
206
+ revisionIds: (ready.revisionWeights ?? []).map((w) => w.revisionId!),
207
+ };
208
+ }
209
+
210
+ /** The endpoint once it is no longer Pending or mid-update (undefined if it doesn't exist). */
211
+ async function waitEndpointSettled(ctx: EngineContext, functionName: string, endpointName: string) {
212
+ const first = await getEndpoint(ctx, functionName, endpointName);
213
+ if (!first) return undefined;
214
+ const settled = (e: NonNullable<typeof first>) => e.state !== 'Pending' && e.updateStatus !== 'InProgress';
215
+ if (settled(first)) return first;
216
+ ctx.log('info', 'waiting for the web function endpoint to become active', `web-function ${functionName}`);
217
+ return waitFor(
218
+ `endpoint ${functionName}/${endpointName}`,
219
+ async () => {
220
+ const e = await getEndpoint(ctx, functionName, endpointName);
221
+ if (!e) return false;
222
+ if (e.state === 'Failed') throw new Error(`endpoint failed: ${e.stateReason}`);
223
+ return settled(e) ? e : false;
224
+ },
225
+ { timeoutMs: 600_000 },
226
+ );
227
+ }
228
+
229
+ export async function getEndpoint(ctx: EngineContext, functionName: string, endpointName: string) {
230
+ return ignoreNotFound(
231
+ ctx.clients.lambdaWeb.send(new GetWebFunctionEndpointCommand({ functionName, endpointName })),
232
+ );
233
+ }
234
+
235
+ /** Route 100% of an existing endpoint to `revisionId` (rollback). */
236
+ export async function setEndpointRevision(
237
+ ctx: EngineContext,
238
+ spec: { functionName: string; endpointName: string; revisionId: string },
239
+ ): Promise<void> {
240
+ await ensureEndpoint(ctx, spec);
241
+ }
242
+
243
+ /**
244
+ * Allow only the platform's CloudFront distribution to invoke the endpoint
245
+ * (OAC signs origin requests). A function has one resource policy, so this
246
+ * is read-modify-write guarded by the policy revision id.
247
+ */
248
+ export async function ensureRouterAccess(
249
+ ctx: EngineContext,
250
+ spec: { functionArn: string; endpointArn: string; distributionArn: string },
251
+ ): Promise<void> {
252
+ const lw = ctx.clients.lambdaWeb;
253
+ const sid = 'AllowPlatformRouter';
254
+ const statement = {
255
+ Sid: sid,
256
+ Effect: 'Allow',
257
+ Principal: { Service: 'cloudfront.amazonaws.com' },
258
+ Action: 'lambda:InvokeWebFunctionEndpoint',
259
+ Resource: spec.endpointArn,
260
+ Condition: { StringEquals: { 'aws:SourceArn': spec.distributionArn } },
261
+ };
262
+ await retry(
263
+ async () => {
264
+ const current = await ignoreNotFound(
265
+ lw.send(new GetResourcePolicyCommand({ resourceArn: spec.functionArn })),
266
+ );
267
+ const doc = current?.policy
268
+ ? (JSON.parse(current.policy) as { Version: string; Statement: Array<{ Sid?: string }> })
269
+ : { Version: '2012-10-17', Statement: [] };
270
+ const others = doc.Statement.filter((s) => s.Sid !== sid);
271
+ const next = { Version: '2012-10-17', Statement: [...others, statement] };
272
+ if (
273
+ current?.policy &&
274
+ JSON.stringify(doc.Statement.find((s) => s.Sid === sid)) === JSON.stringify(statement)
275
+ ) {
276
+ return;
277
+ }
278
+ await lw.send(
279
+ new PutResourcePolicyCommand({
280
+ resourceArn: spec.functionArn,
281
+ policy: JSON.stringify(next),
282
+ revisionId: current?.revisionId,
283
+ }),
284
+ );
285
+ },
286
+ { when: (e) => /PreconditionFailed|Conflict/.test(errorName(e)), attempts: 5 },
287
+ );
288
+ }
289
+
290
+ /** Delete revisions beyond the `keepNewest` most recent, never touching `keep`. */
291
+ export async function pruneRevisions(
292
+ ctx: EngineContext,
293
+ functionName: string,
294
+ opts: { keepNewest: number; keep: string[] },
295
+ ): Promise<void> {
296
+ const lw = ctx.clients.lambdaWeb;
297
+ const all: Array<{ id: string; createdAt: number }> = [];
298
+ let nextToken: string | undefined;
299
+ do {
300
+ const res = await lw.send(new ListWebFunctionRevisionsCommand({ functionName, nextToken }));
301
+ for (const r of res.revisions ?? []) {
302
+ if (r.revisionId) all.push({ id: r.revisionId, createdAt: r.createdAt?.getTime() ?? 0 });
303
+ }
304
+ nextToken = res.nextToken;
305
+ } while (nextToken);
306
+ all.sort((a, b) => b.createdAt - a.createdAt);
307
+ for (const r of all.slice(opts.keepNewest)) {
308
+ if (opts.keep.includes(r.id)) continue;
309
+ try {
310
+ await ignoreNotFound(lw.send(new DeleteWebFunctionRevisionCommand({ functionName, revisionId: r.id })));
311
+ } catch (e) {
312
+ // AWS Emulator v1.0.385 doesn't implement revision deletion; old revisions are harmless there.
313
+ if (isNotImplemented(e)) return;
314
+ throw e;
315
+ }
316
+ ctx.log('info', `deleted old revision ${r.id}`, `web-function ${functionName}`);
317
+ }
318
+ }
319
+
320
+ export async function deleteWebFunction(ctx: EngineContext, name: string): Promise<boolean> {
321
+ const lw = ctx.clients.lambdaWeb;
322
+ const fn = await ignoreNotFound(lw.send(new GetWebFunctionCommand({ functionName: name })));
323
+ if (!fn) return false;
324
+ const endpoints = await ignoreNotFound(
325
+ lw.send(new ListWebFunctionEndpointsCommand({ functionName: name })),
326
+ );
327
+ for (const e of endpoints?.endpoints ?? []) {
328
+ if (e.endpointName) {
329
+ await ignoreNotFound(
330
+ lw.send(new DeleteWebFunctionEndpointCommand({ functionName: name, endpointName: e.endpointName })),
331
+ );
332
+ }
333
+ }
334
+ if (fn.functionArn)
335
+ await ignoreNotFound(lw.send(new DeleteResourcePolicyCommand({ resourceArn: fn.functionArn })));
336
+ const revisions = await ignoreNotFound(
337
+ lw.send(new ListWebFunctionRevisionsCommand({ functionName: name })),
338
+ );
339
+ for (const r of revisions?.revisions ?? []) {
340
+ if (r.revisionId) {
341
+ await ignoreNotFound(
342
+ lw.send(new DeleteWebFunctionRevisionCommand({ functionName: name, revisionId: r.revisionId })),
343
+ );
344
+ }
345
+ }
346
+ await retry(() => ignoreNotFound(lw.send(new DeleteWebFunctionCommand({ functionName: name }))), {
347
+ when: (e) => errorName(e).includes('Conflict'),
348
+ attempts: 10,
349
+ });
350
+ ctx.log('info', 'deleted web function', `web-function ${name}`);
351
+ return true;
352
+ }
@@ -0,0 +1,203 @@
1
+ import { type ChildProcess, spawn, spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs';
3
+ import { homedir, tmpdir } from 'node:os';
4
+ import { delimiter, join } from 'node:path';
5
+ import { createInterface } from 'node:readline';
6
+
7
+ /**
8
+ * Thin wrapper around the AWS Emulator (https://docs.aws.amazon.com/emulator/):
9
+ * one local HTTPS endpoint for many AWS APIs, state in memory. Used by
10
+ * `plat dev`, `plat test` and the engine's own integration tests.
11
+ *
12
+ * Install once per machine (Linux): see docs/SETUP.md, or the AWS docs. On
13
+ * macOS/Windows run it in Docker and point `PLAT_EMULATOR_ENDPOINT` at it.
14
+ */
15
+ export interface EmulatorConnection {
16
+ endpoint: string;
17
+ /** PEM bundle for the emulator's self-signed TLS certificate. */
18
+ caFile: string;
19
+ credentials: { accessKeyId: string; secretAccessKey: string };
20
+ region: string;
21
+ /** Fixed by the emulator. */
22
+ accountId: '000000000000';
23
+ /**
24
+ * Environment for child processes (web server, tests) so the AWS SDK and CLI
25
+ * talk to the emulator: endpoint, CA bundle, credentials, region.
26
+ */
27
+ env: Record<string, string>;
28
+ /** Variables to delete from a child environment (a developer's real AWS profile/session). */
29
+ unsetEnv: readonly string[];
30
+ /** Stops the emulator (state is discarded). No-op for an external emulator. */
31
+ stop(): Promise<void>;
32
+ }
33
+
34
+ export interface StartEmulatorOptions {
35
+ /** Path to the `aws-emulator` binary. Default: `$PLAT_EMULATOR_BIN`, then `PATH`. */
36
+ bin?: string;
37
+ /** 0 picks a free port. */
38
+ port?: number;
39
+ region?: string;
40
+ /** Exit after this many idle seconds (safety net for crashed parents). */
41
+ idleTimeoutSeconds?: number;
42
+ /** Isolated HOME for the emulator's generated credentials. Default: a temp dir. */
43
+ home?: string;
44
+ /** Forward emulator log lines. */
45
+ onLog?: (line: string) => void;
46
+ startupTimeoutMs?: number;
47
+ }
48
+
49
+ export const EMULATOR_INSTALL_HINT = `AWS Emulator not found. Install it once (Debian/Ubuntu):
50
+ curl -fsSLo aws-emulator.deb https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/aws-emulator_amd64.deb
51
+ sudo apt-get install -y ./aws-emulator.deb
52
+ RPM, arm64 and Docker (macOS/Windows) instructions: https://docs.aws.amazon.com/emulator/latest/userguide/getting-started.html
53
+ Or set PLAT_EMULATOR_BIN to the binary, or PLAT_EMULATOR_ENDPOINT (+ PLAT_EMULATOR_HOME) to a running emulator.`;
54
+
55
+ export function findEmulatorBinary(explicit?: string): string | null {
56
+ const candidates = [explicit, process.env.PLAT_EMULATOR_BIN].filter(Boolean) as string[];
57
+ for (const c of candidates) if (existsSync(c)) return c;
58
+ for (const dir of (process.env.PATH ?? '').split(delimiter)) {
59
+ const p = join(dir, 'aws-emulator');
60
+ if (dir && existsSync(p)) return p;
61
+ }
62
+ const opt = '/opt/aws-emulator/bin/aws-emulator';
63
+ return existsSync(opt) ? opt : null;
64
+ }
65
+
66
+ export function emulatorVersion(bin: string): string | null {
67
+ const r = spawnSync(bin, ['-v'], { encoding: 'utf8' });
68
+ const m = /Version:\s*(\S+)/.exec(r.stdout ?? '');
69
+ return m?.[1] ?? null;
70
+ }
71
+
72
+ export async function startEmulator(opts: StartEmulatorOptions = {}): Promise<EmulatorConnection> {
73
+ const region = opts.region ?? 'us-east-1';
74
+ const external = process.env.PLAT_EMULATOR_ENDPOINT;
75
+ if (external) return connectExternal(external, region, process.env.PLAT_EMULATOR_HOME ?? homedir());
76
+
77
+ const bin = findEmulatorBinary(opts.bin);
78
+ if (!bin) throw new Error(EMULATOR_INSTALL_HINT);
79
+ const home = opts.home ?? join(tmpdir(), `plat-emulator-${process.pid}-${Date.now()}`);
80
+ mkdirSync(home, { recursive: true });
81
+ const args = ['-p', String(opts.port ?? 0), '-t', 'off'];
82
+ if (opts.idleTimeoutSeconds) args.push('--idle-timeout', String(opts.idleTimeoutSeconds));
83
+ const child = spawn(bin, args, {
84
+ env: { ...process.env, HOME: home, EMULATOR_TELEMETRY: 'off' },
85
+ stdio: ['ignore', 'pipe', 'pipe'],
86
+ });
87
+
88
+ const info = await new Promise<{ endpoint: string; caFile: string; credentialsFile: string }>(
89
+ (resolve, reject) => {
90
+ let credentialsFile = '';
91
+ const timer = setTimeout(
92
+ () => reject(new Error('AWS Emulator did not start within the timeout')),
93
+ opts.startupTimeoutMs ?? 20_000,
94
+ );
95
+ const onLine = (line: string) => {
96
+ opts.onLog?.(line);
97
+ let parsed: { fields?: Record<string, string> } | undefined;
98
+ try {
99
+ parsed = JSON.parse(line);
100
+ } catch {
101
+ return;
102
+ }
103
+ const f = parsed?.fields ?? {};
104
+ if (f.credentials_file) credentialsFile = f.credentials_file;
105
+ if (f.message === 'emulator server information' && f.endpoint_url && f.ca_file) {
106
+ clearTimeout(timer);
107
+ resolve({ endpoint: f.endpoint_url, caFile: f.ca_file, credentialsFile });
108
+ }
109
+ };
110
+ createInterface({ input: child.stdout! }).on('line', onLine);
111
+ createInterface({ input: child.stderr! }).on('line', onLine);
112
+ child.once('exit', (code) => {
113
+ clearTimeout(timer);
114
+ reject(new Error(`AWS Emulator exited during startup (code ${code})`));
115
+ });
116
+ },
117
+ );
118
+
119
+ return {
120
+ ...buildConnection(info.endpoint, info.caFile, readCredentials(info.credentialsFile), region),
121
+ stop: () => stopChild(child),
122
+ };
123
+ }
124
+
125
+ function connectExternal(endpoint: string, region: string, home: string): EmulatorConnection {
126
+ const port = new URL(endpoint).port || '9297';
127
+ const dir = join(home, '.aws', 'emulator', port);
128
+ return {
129
+ ...buildConnection(
130
+ endpoint,
131
+ join(dir, 'ca.pem'),
132
+ readCredentials(join(dir, 'emulator_credentials')),
133
+ region,
134
+ ),
135
+ stop: async () => {},
136
+ };
137
+ }
138
+
139
+ function buildConnection(
140
+ endpoint: string,
141
+ caFile: string,
142
+ credentials: EmulatorConnection['credentials'],
143
+ region: string,
144
+ ): Omit<EmulatorConnection, 'stop'> {
145
+ return {
146
+ endpoint,
147
+ caFile,
148
+ credentials,
149
+ region,
150
+ accountId: '000000000000',
151
+ env: {
152
+ AWS_ENDPOINT_URL: endpoint,
153
+ AWS_CA_BUNDLE: caFile,
154
+ NODE_EXTRA_CA_CERTS: caFile,
155
+ AWS_ACCESS_KEY_ID: credentials.accessKeyId,
156
+ AWS_SECRET_ACCESS_KEY: credentials.secretAccessKey,
157
+ AWS_REGION: region,
158
+ AWS_DEFAULT_REGION: region,
159
+ AWS_EC2_METADATA_DISABLED: 'true',
160
+ AWS_DISABLE_HOST_PREFIX_INJECTION: 'true',
161
+ },
162
+ unsetEnv: EMULATOR_UNSET_ENV,
163
+ };
164
+ }
165
+
166
+ /** A developer's real AWS identity must never leak into emulator runs. */
167
+ export const EMULATOR_UNSET_ENV = [
168
+ 'AWS_PROFILE',
169
+ 'AWS_SESSION_TOKEN',
170
+ 'AWS_CONFIG_FILE',
171
+ 'AWS_SHARED_CREDENTIALS_FILE',
172
+ ] as const;
173
+
174
+ /** `process.env` + emulator connection env, minus a developer's real AWS identity. */
175
+ export function emulatorChildEnv(
176
+ conn: Pick<EmulatorConnection, 'env' | 'unsetEnv'>,
177
+ base: NodeJS.ProcessEnv = process.env,
178
+ ): NodeJS.ProcessEnv {
179
+ const env = { ...base, ...conn.env };
180
+ for (const k of conn.unsetEnv) delete env[k];
181
+ return env;
182
+ }
183
+
184
+ function readCredentials(file: string): EmulatorConnection['credentials'] {
185
+ const text = readFileSync(file, 'utf8');
186
+ const get = (k: string) => new RegExp(`^\\s*${k}\\s*=\\s*(\\S+)`, 'm').exec(text)?.[1];
187
+ const accessKeyId = get('aws_access_key_id');
188
+ const secretAccessKey = get('aws_secret_access_key');
189
+ if (!accessKeyId || !secretAccessKey) throw new Error(`Could not read emulator credentials from ${file}`);
190
+ return { accessKeyId, secretAccessKey };
191
+ }
192
+
193
+ function stopChild(child: ChildProcess): Promise<void> {
194
+ if (child.exitCode !== null) return Promise.resolve();
195
+ return new Promise((resolve) => {
196
+ const t = setTimeout(() => child.kill('SIGKILL'), 5_000);
197
+ child.once('exit', () => {
198
+ clearTimeout(t);
199
+ resolve();
200
+ });
201
+ child.kill('SIGTERM');
202
+ });
203
+ }