@suss/packs 0.35.1 → 0.37.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,577 @@
1
+ // ../framework/aws-lambda/dist/index.js
2
+ import { z } from "zod";
3
+ import { compile, declarationsIn } from "@suss/recognize";
4
+ import fs from "fs";
5
+ import path from "path";
6
+ import {
7
+ loadServerlessDocument,
8
+ SERVICE_FILE_NAMES,
9
+ translateService
10
+ } from "@suss/contract-serverless";
11
+ import {
12
+ loadTemplateTree,
13
+ qualifiedLogicalId,
14
+ readAppSyncResolvers,
15
+ readServerlessFunctions,
16
+ unfollowedStackMessage
17
+ } from "@suss/manifest-aws";
18
+ import {
19
+ graphqlResolverBinding,
20
+ messageBusBinding,
21
+ unitInvocationBinding
22
+ } from "@suss/behavioral-ir";
23
+ import { constructedFrom, unitInvokes } from "@suss/recognize";
24
+ var TEMPLATE_NAMES = [
25
+ "template.yaml",
26
+ "template.yml",
27
+ "template.json",
28
+ ...SERVICE_FILE_NAMES
29
+ ];
30
+ var isServiceFile = (file) => SERVICE_FILE_NAMES.includes(path.basename(file));
31
+ function manifestTree(manifestPath) {
32
+ if (!isServiceFile(manifestPath)) {
33
+ return loadTemplateTree(manifestPath);
34
+ }
35
+ const translated = translateService(loadServerlessDocument(manifestPath));
36
+ return {
37
+ documents: [
38
+ {
39
+ path: path.resolve(manifestPath),
40
+ stackPath: [],
41
+ template: translated.functions,
42
+ resourceLines: /* @__PURE__ */ new Map(),
43
+ parameterTargets: /* @__PURE__ */ new Map()
44
+ }
45
+ ],
46
+ unfollowed: []
47
+ };
48
+ }
49
+ function modulePathsOf(resolvedModule) {
50
+ const directory = path.dirname(resolvedModule);
51
+ const base = path.basename(resolvedModule);
52
+ if (!base.includes(".")) {
53
+ return [resolvedModule];
54
+ }
55
+ return [resolvedModule, path.join(directory, ...base.split("."))];
56
+ }
57
+ var dirToTemplate = /* @__PURE__ */ new Map();
58
+ var templateToIndex = /* @__PURE__ */ new Map();
59
+ var templateToDocuments = /* @__PURE__ */ new Map();
60
+ function findTemplate(startDir) {
61
+ const chain = [];
62
+ let dir = startDir;
63
+ while (true) {
64
+ const cached = dirToTemplate.get(dir);
65
+ if (cached !== void 0) {
66
+ for (const d of chain) {
67
+ dirToTemplate.set(d, cached);
68
+ }
69
+ return cached;
70
+ }
71
+ chain.push(dir);
72
+ const found = TEMPLATE_NAMES.map((name) => path.join(dir, name)).find(
73
+ (candidate) => fs.existsSync(candidate)
74
+ ) ?? null;
75
+ if (found !== null) {
76
+ for (const d of chain) {
77
+ dirToTemplate.set(d, found);
78
+ }
79
+ return found;
80
+ }
81
+ const parent = path.dirname(dir);
82
+ if (parent === dir) {
83
+ for (const d of chain) {
84
+ dirToTemplate.set(d, null);
85
+ }
86
+ return null;
87
+ }
88
+ dir = parent;
89
+ }
90
+ }
91
+ function indexForTemplate(templatePath) {
92
+ const cached = templateToIndex.get(templatePath);
93
+ if (cached !== void 0) {
94
+ return cached;
95
+ }
96
+ const index = /* @__PURE__ */ new Map();
97
+ const documents = /* @__PURE__ */ new Set([templatePath]);
98
+ try {
99
+ const tree = manifestTree(templatePath);
100
+ for (const document of tree.documents) {
101
+ documents.add(document.path);
102
+ }
103
+ for (const stack of tree.unfollowed) {
104
+ process.stderr.write(
105
+ `[suss] aws-lambda: ${unfollowedStackMessage(stack)}
106
+ `
107
+ );
108
+ if (stack.templatePath !== null) {
109
+ documents.add(stack.templatePath);
110
+ }
111
+ }
112
+ for (const document of tree.documents) {
113
+ const templateDir = path.dirname(document.path);
114
+ const fieldsByFunction = groupFieldsByFunction(
115
+ readAppSyncResolvers(document.template)
116
+ );
117
+ for (const fn of readServerlessFunctions(document.template)) {
118
+ const resolvedModule = path.resolve(
119
+ templateDir,
120
+ fn.codeUri,
121
+ fn.modulePath
122
+ );
123
+ const entry = {
124
+ functionLogicalId: qualifiedLogicalId(
125
+ document.stackPath,
126
+ fn.logicalId
127
+ ),
128
+ graphqlFields: fieldsByFunction.get(fn.logicalId) ?? [],
129
+ handler: fn.handler,
130
+ exportName: fn.exportName,
131
+ httpRoutes: fn.httpRoutes,
132
+ nonHttpEvents: fn.nonHttpEvents
133
+ };
134
+ for (const modulePath of modulePathsOf(resolvedModule)) {
135
+ index.set(modulePath, [...index.get(modulePath) ?? [], entry]);
136
+ }
137
+ }
138
+ }
139
+ } catch (err) {
140
+ process.stderr.write(
141
+ `[suss] aws-lambda: failed to read ${templatePath}: ${err instanceof Error ? err.message : String(err)}
142
+ `
143
+ );
144
+ }
145
+ templateToIndex.set(templatePath, index);
146
+ templateToDocuments.set(templatePath, [...documents]);
147
+ return index;
148
+ }
149
+ function toModulePath(filePath) {
150
+ const resolved = path.resolve(filePath);
151
+ const ext = path.extname(resolved);
152
+ return ext === "" ? resolved : resolved.slice(0, -ext.length);
153
+ }
154
+ function groupFieldsByFunction(bindings) {
155
+ const out = /* @__PURE__ */ new Map();
156
+ for (const binding of bindings) {
157
+ for (const logicalId of binding.lambdaFunctionLogicalIds) {
158
+ const fields = out.get(logicalId) ?? [];
159
+ fields.push({ typeName: binding.typeName, fieldName: binding.fieldName });
160
+ out.set(logicalId, fields);
161
+ }
162
+ }
163
+ return out;
164
+ }
165
+ function handlersForFile(filePath) {
166
+ const templatePath = findTemplate(path.dirname(path.resolve(filePath)));
167
+ if (templatePath === null) {
168
+ return [];
169
+ }
170
+ const index = indexForTemplate(templatePath);
171
+ return index.get(toModulePath(filePath)) ?? [];
172
+ }
173
+ function templatesForFiles(files) {
174
+ const roots = /* @__PURE__ */ new Set();
175
+ for (const file of files) {
176
+ const templatePath = findTemplate(path.dirname(path.resolve(file)));
177
+ if (templatePath !== null) {
178
+ roots.add(templatePath);
179
+ }
180
+ }
181
+ const documents = /* @__PURE__ */ new Set();
182
+ for (const root of roots) {
183
+ indexForTemplate(root);
184
+ for (const document of templateToDocuments.get(root) ?? [root]) {
185
+ documents.add(document);
186
+ }
187
+ }
188
+ return [...documents];
189
+ }
190
+ var HTTP_TERMINALS = [
191
+ {
192
+ // `return { statusCode, body, headers? }`, at the return or in a helper
193
+ // the adapter follows. `body` contains the serialized payload, so
194
+ // `JSON.stringify(x)` is unwrapped to the shape of `x`.
195
+ kind: "response",
196
+ match: { type: "returnShape", requiredProperties: ["statusCode"] },
197
+ extraction: {
198
+ statusCode: { from: "property", name: "statusCode" },
199
+ body: { from: "property", name: "body", unwrapJsonStringify: true }
200
+ }
201
+ },
202
+ {
203
+ // `return { batchItemFailures }` makes Lambda retry the records it
204
+ // lists. Lambda defines this shape, so the pack can match on it the
205
+ // same way it matches the envelope above.
206
+ kind: "return",
207
+ match: {
208
+ type: "returnShape",
209
+ requiredProperties: ["batchItemFailures"]
210
+ },
211
+ extraction: {}
212
+ },
213
+ {
214
+ // An uncaught throw becomes a throw-output transition. API Gateway
215
+ // turns it into a 5xx, and the platform picks which one.
216
+ kind: "throw",
217
+ match: { type: "throwExpression" },
218
+ extraction: {}
219
+ }
220
+ ];
221
+ var NON_HTTP_TERMINALS = [
222
+ ...HTTP_TERMINALS,
223
+ {
224
+ kind: "return",
225
+ match: { type: "returnShape" },
226
+ extraction: {}
227
+ },
228
+ {
229
+ // A queue consumer acknowledges a batch by returning without an error.
230
+ // Without this pattern the handler has no terminal, so it gets no
231
+ // transition and everything it does is lost with it.
232
+ kind: "return",
233
+ match: { type: "functionFallthrough" },
234
+ extraction: {}
235
+ }
236
+ ];
237
+ var METADATA_NAMESPACE = "awsLambda";
238
+ function deployableUnit(entry) {
239
+ return { deploymentTarget: "lambda", instanceName: entry.functionLogicalId };
240
+ }
241
+ function httpRouteUnits(entry, func) {
242
+ const units = [];
243
+ for (const route of entry.httpRoutes) {
244
+ if (route.method === "ANY") {
245
+ continue;
246
+ }
247
+ units.push({
248
+ func,
249
+ kind: "handler",
250
+ name: `${entry.functionLogicalId}.${entry.exportName}`,
251
+ routeInfo: { method: route.method, path: route.path },
252
+ deployableUnit: deployableUnit(entry),
253
+ metadata: {
254
+ [METADATA_NAMESPACE]: {
255
+ handler: entry.handler,
256
+ eventId: route.eventId,
257
+ apiEventType: route.eventType
258
+ }
259
+ }
260
+ });
261
+ }
262
+ return units;
263
+ }
264
+ var OPERATION_ROOT_TYPES = ["Query", "Mutation", "Subscription"];
265
+ function operationFields(entry) {
266
+ return entry.graphqlFields.filter(
267
+ (f) => OPERATION_ROOT_TYPES.includes(f.typeName)
268
+ );
269
+ }
270
+ function typeFields(entry) {
271
+ return entry.graphqlFields.filter(
272
+ (f) => !OPERATION_ROOT_TYPES.includes(f.typeName)
273
+ );
274
+ }
275
+ function graphqlResolverUnits(entry, func) {
276
+ return operationFields(entry).map((field) => ({
277
+ func,
278
+ kind: "handler",
279
+ name: `${entry.functionLogicalId}.${entry.exportName}`,
280
+ resolverInfo: { typeName: field.typeName, fieldName: field.fieldName },
281
+ deployableUnit: deployableUnit(entry),
282
+ metadata: {
283
+ [METADATA_NAMESPACE]: {
284
+ handler: entry.handler,
285
+ recognition: "appsync-resolver"
286
+ }
287
+ }
288
+ }));
289
+ }
290
+ function accountingUnit(entry, func) {
291
+ const eventTypes = accountedEventTypes(entry);
292
+ const backs = typeFields(entry);
293
+ const wire = messageBusWire(eventTypes);
294
+ const unit = deployableUnit(entry);
295
+ return {
296
+ func,
297
+ kind: "handler",
298
+ name: `${entry.functionLogicalId}.${entry.exportName}`,
299
+ terminals: NON_HTTP_TERMINALS,
300
+ ...wire !== null ? { channelInfo: { messageBus: wire, channel: null } } : { invocationInfo: unit },
301
+ deployableUnit: unit,
302
+ metadata: {
303
+ [METADATA_NAMESPACE]: {
304
+ handler: entry.handler,
305
+ recognition: "recognized-not-http",
306
+ eventTypes,
307
+ ...backs.length > 0 ? { graphqlTypeFields: backs } : {}
308
+ }
309
+ }
310
+ };
311
+ }
312
+ var EVENT_WIRES = {
313
+ SQS: "aws_sqs",
314
+ SNS: "aws.sns",
315
+ S3: "s3",
316
+ Schedule: "eventbridge",
317
+ ScheduleV2: "eventbridge",
318
+ EventBridgeRule: "eventbridge",
319
+ CloudWatchEvent: "eventbridge"
320
+ };
321
+ function messageBusWire(eventTypes) {
322
+ const wires = new Set(
323
+ eventTypes.map((type) => EVENT_WIRES[type] ?? null)
324
+ );
325
+ if (wires.size !== 1) {
326
+ return null;
327
+ }
328
+ const [wire] = wires;
329
+ return wire ?? null;
330
+ }
331
+ function accountedEventTypes(entry) {
332
+ return [
333
+ ...entry.nonHttpEvents.map((e) => e.eventType),
334
+ ...entry.httpRoutes.filter((r) => r.method === "ANY").map((r) => r.eventType)
335
+ ];
336
+ }
337
+ function hasBindableRoute(entry) {
338
+ return entry.httpRoutes.some((r) => r.method !== "ANY");
339
+ }
340
+ function awsLambdaDiscovery() {
341
+ return (sourceFile, ctx) => {
342
+ const sf = sourceFile;
343
+ const tsCtx = ctx;
344
+ const filePath = tsCtx.getFilePath(sf);
345
+ const entries = handlersForFile(filePath);
346
+ if (entries.length === 0) {
347
+ return [];
348
+ }
349
+ const exported = /* @__PURE__ */ new Map();
350
+ for (const { name, func } of tsCtx.exportedFunctions(sf)) {
351
+ exported.set(name, func);
352
+ }
353
+ const units = [];
354
+ for (const entry of entries) {
355
+ const func = exported.get(entry.exportName);
356
+ if (func === void 0) {
357
+ continue;
358
+ }
359
+ units.push(...httpRouteUnits(entry, func));
360
+ units.push(...graphqlResolverUnits(entry, func));
361
+ const unaccountedEvents = accountedEventTypes(entry);
362
+ const boundToNothing = !hasBindableRoute(entry) && operationFields(entry).length === 0;
363
+ if (unaccountedEvents.length > 0 || boundToNothing) {
364
+ units.push(accountingUnit(entry, func));
365
+ }
366
+ }
367
+ return units;
368
+ };
369
+ }
370
+ function lambdaEntryPoints(recognition) {
371
+ return (filePath) => handlersForFile(filePath).map((entry) => ({
372
+ name: entry.exportName,
373
+ units: entryUnits(entry, recognition)
374
+ }));
375
+ }
376
+ function entryUnits(entry, recognition) {
377
+ const operations = operationFields(entry);
378
+ const fields = operations.map(
379
+ (field) => resolverUnit(entry, field, recognition)
380
+ );
381
+ const reachedOtherwise = entry.httpRoutes.length > 0 || entry.nonHttpEvents.length > 0 || entry.graphqlFields.length > operations.length;
382
+ return fields.length > 0 && !reachedOtherwise ? fields : [...fields, handlerUnit(entry, recognition)];
383
+ }
384
+ function resolverUnit(entry, field, recognition) {
385
+ return {
386
+ kind: "handler",
387
+ name: `${entry.functionLogicalId}.${entry.exportName}`,
388
+ binding: graphqlResolverBinding({
389
+ transport: "aws-https",
390
+ recognition,
391
+ typeName: field.typeName,
392
+ fieldName: field.fieldName
393
+ }),
394
+ deployableUnit: deployableUnit(entry),
395
+ metadata: {
396
+ [METADATA_NAMESPACE]: {
397
+ handler: entry.handler,
398
+ recognition: "appsync-resolver"
399
+ }
400
+ }
401
+ };
402
+ }
403
+ function handlerUnit(entry, recognition) {
404
+ const eventTypes = [
405
+ ...entry.httpRoutes.map((route) => route.eventType),
406
+ ...entry.nonHttpEvents.map((event) => event.eventType)
407
+ ];
408
+ return {
409
+ kind: "handler",
410
+ name: `${entry.functionLogicalId}.${entry.exportName}`,
411
+ binding: handlerBinding(entry, eventTypes, recognition),
412
+ deployableUnit: deployableUnit(entry),
413
+ metadata: {
414
+ [METADATA_NAMESPACE]: {
415
+ handler: entry.handler,
416
+ recognition: "handler-entry",
417
+ eventTypes,
418
+ ...entry.graphqlFields.length > 0 ? { graphqlTypeFields: entry.graphqlFields } : {}
419
+ }
420
+ }
421
+ };
422
+ }
423
+ function handlerBinding(entry, eventTypes, recognition) {
424
+ const wire = entry.graphqlFields.length > 0 ? null : messageBusWire(eventTypes);
425
+ if (wire !== null) {
426
+ return messageBusBinding({ recognition, messageBus: wire, channel: null });
427
+ }
428
+ return unitInvocationBinding({ recognition, ...deployableUnit(entry) });
429
+ }
430
+ var LAMBDA = "@aws-sdk/client-lambda";
431
+ var INSIDE_THE_COMMAND = (named) => ({
432
+ send: {
433
+ input: {
434
+ at: 0,
435
+ of: [
436
+ {
437
+ to: "argument",
438
+ at: 0,
439
+ origin: constructedFrom({ from: [LAMBDA], named })
440
+ }
441
+ ]
442
+ }
443
+ }
444
+ });
445
+ function invokeDeclarations() {
446
+ return [
447
+ unitInvokes({
448
+ platform: "lambda",
449
+ client: constructedFrom(LAMBDA),
450
+ named: ["FunctionName"],
451
+ payload: "Payload"
452
+ }).methods(INSIDE_THE_COMMAND(["InvokeCommand"])).example(
453
+ 'client.send(new InvokeCommand({ FunctionName: "Worker", Payload: "{}" }))'
454
+ ),
455
+ unitInvokes({
456
+ platform: "lambda",
457
+ client: constructedFrom(LAMBDA),
458
+ named: ["FunctionName"],
459
+ payload: "InvokeArgs"
460
+ }).methods(INSIDE_THE_COMMAND(["InvokeAsyncCommand"])).example(
461
+ 'client.send(new InvokeAsyncCommand({ FunctionName: "Worker", InvokeArgs: "{}" }))'
462
+ )
463
+ ];
464
+ }
465
+ var optionsSchema = z.object({}).strict();
466
+ function awsLambdaFramework(_options = {}) {
467
+ const invokes = invokeDeclarations();
468
+ return {
469
+ name: "aws-lambda",
470
+ protocol: "http",
471
+ // The adapter cannot read Sentry's wrapper inside the library, so the
472
+ // pack declares that the handler is argument 0. A wrapper written in
473
+ // the project needs no entry, because the adapter reads its body.
474
+ transparentWrappers: [
475
+ { module: "@sentry/aws-serverless", name: "wrapHandler", argument: 0 }
476
+ ],
477
+ languages: ["typescript", "javascript"],
478
+ // The routing is in the template, so the callback finds handlers
479
+ // there and the pattern list stays empty.
480
+ discovery: [],
481
+ discoverUnits: awsLambdaDiscovery(),
482
+ // Discovery reads the templates, so they go into the cache key and an
483
+ // edited template makes the next run read the project again.
484
+ discoveryInputs: templatesForFiles,
485
+ // No import gate: a JavaScript handler imports nothing from
486
+ // `aws-lambda`, so the template acts as the gate. See the README.
487
+ // A unit that is not HTTP gets a longer list from the discovery
488
+ // callback in place of this one.
489
+ terminals: HTTP_TERMINALS,
490
+ inputMapping: {
491
+ type: "positionalParams",
492
+ params: [
493
+ { position: 0, role: "event" },
494
+ { position: 1, role: "context" }
495
+ ]
496
+ },
497
+ // A proxy integration passes the handler API Gateway's event, with the
498
+ // body as a string the handler parses. A read of the body records that
499
+ // the handler took all of it, with no field name.
500
+ requestSpelling: {
501
+ headers: { path: ["event", "headers"], saysWhichField: true },
502
+ query: {
503
+ path: ["event", "queryStringParameters"],
504
+ saysWhichField: true
505
+ },
506
+ params: { path: ["event", "pathParameters"], saysWhichField: true },
507
+ body: { path: ["event", "body"], saysWhichField: false }
508
+ },
509
+ // Powertools reads these variables from inside node_modules, where no
510
+ // walk over the project goes, so without this entry they look unread.
511
+ libraryEnvVars: [
512
+ {
513
+ module: "@aws-lambda-powertools/",
514
+ prefixes: ["POWERTOOLS_"]
515
+ }
516
+ ],
517
+ // A pack-level `requiresImport` would gate `discoverUnits` too. Each
518
+ // declaration already checks which SDK its command class came from.
519
+ invocationRecognizers: invokes.map(
520
+ (match) => compile(match.declared, "@suss/framework-aws-lambda")
521
+ ),
522
+ declarations: declarationsIn(invokes)
523
+ };
524
+ }
525
+ var declares = {
526
+ kind: "framework",
527
+ package: "@suss/framework-aws-lambda",
528
+ dependencies: [{ ecosystem: "npm", name: "@types/aws-lambda" }],
529
+ reads: "AWS Lambda HTTP handlers, paired with the routes a SAM template or serverless.yml declares."
530
+ };
531
+ function awsLambdaPython() {
532
+ const name = "aws-lambda-python";
533
+ return {
534
+ name,
535
+ protocol: "http",
536
+ discovery: [],
537
+ discoveryInputs: templatesForFiles,
538
+ entryPoints: lambdaEntryPoints(name),
539
+ // Powertools reads these from its own installed package.
540
+ libraryEnvVars: [
541
+ { module: "aws_lambda_powertools", prefixes: ["POWERTOOLS_"] }
542
+ ]
543
+ };
544
+ }
545
+ var declaresPython = {
546
+ kind: "framework",
547
+ package: "@suss/framework-aws-lambda",
548
+ dependencies: [],
549
+ reads: "AWS Lambda handlers written in Python, found from the Handler a SAM template or serverless.yml gives each function."
550
+ };
551
+ function awsLambdaRuby() {
552
+ const name = "aws-lambda-ruby";
553
+ return {
554
+ name,
555
+ protocol: "http",
556
+ discovery: [],
557
+ discoveryInputs: templatesForFiles,
558
+ entryPoints: lambdaEntryPoints(name)
559
+ };
560
+ }
561
+ var declaresRuby = {
562
+ kind: "framework",
563
+ package: "@suss/framework-aws-lambda",
564
+ dependencies: [],
565
+ reads: "AWS Lambda handlers written in Ruby, found from the Handler a SAM template or serverless.yml gives each function, including a class method written `file.Module::Class.method`."
566
+ };
567
+ var index_default = awsLambdaFramework;
568
+
569
+ export {
570
+ optionsSchema,
571
+ declares,
572
+ awsLambdaPython,
573
+ declaresPython,
574
+ awsLambdaRuby,
575
+ declaresRuby,
576
+ index_default
577
+ };