@ericminassian/platform-core 0.2.0 → 0.4.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 (89) hide show
  1. package/dist/api.d.ts +1847 -212
  2. package/dist/api.js +694 -1
  3. package/dist/api.js.map +1 -1
  4. package/dist/auth.d.ts +19 -0
  5. package/dist/auth.js +32 -0
  6. package/dist/auth.js.map +1 -1
  7. package/dist/base64url.d.ts +3 -0
  8. package/dist/base64url.js +15 -0
  9. package/dist/base64url.js.map +1 -0
  10. package/dist/bindings.d.ts +69 -13
  11. package/dist/bindings.js +1 -1
  12. package/dist/bindings.js.map +1 -1
  13. package/dist/cloudfront-function.d.ts +5 -1
  14. package/dist/cloudfront-function.js +70 -2
  15. package/dist/cloudfront-function.js.map +1 -1
  16. package/dist/compute.d.ts +52 -0
  17. package/dist/compute.js +65 -0
  18. package/dist/compute.js.map +1 -0
  19. package/dist/config.d.ts +21 -1
  20. package/dist/config.js +16 -0
  21. package/dist/config.js.map +1 -1
  22. package/dist/constants.d.ts +67 -1
  23. package/dist/constants.js +56 -1
  24. package/dist/constants.js.map +1 -1
  25. package/dist/email.d.ts +84 -0
  26. package/dist/email.js +111 -0
  27. package/dist/email.js.map +1 -0
  28. package/dist/fingerprint.d.ts +9 -0
  29. package/dist/fingerprint.js +19 -0
  30. package/dist/fingerprint.js.map +1 -0
  31. package/dist/index.d.ts +6 -0
  32. package/dist/index.js +6 -0
  33. package/dist/index.js.map +1 -1
  34. package/dist/jobs.d.ts +111 -0
  35. package/dist/jobs.js +214 -0
  36. package/dist/jobs.js.map +1 -0
  37. package/dist/manifest.d.ts +357 -112
  38. package/dist/manifest.js +270 -72
  39. package/dist/manifest.js.map +1 -1
  40. package/dist/naming.d.ts +93 -6
  41. package/dist/naming.js +98 -6
  42. package/dist/naming.js.map +1 -1
  43. package/dist/platform-api.d.ts +7792 -0
  44. package/dist/platform-api.js +455 -0
  45. package/dist/platform-api.js.map +1 -0
  46. package/dist/realtime.d.ts +139 -0
  47. package/dist/realtime.js +201 -0
  48. package/dist/realtime.js.map +1 -0
  49. package/dist/router/decide.d.ts +7 -1
  50. package/dist/router/decide.js +42 -5
  51. package/dist/router.d.ts +35 -13
  52. package/dist/router.js +36 -0
  53. package/dist/router.js.map +1 -1
  54. package/dist/runtime-config.d.ts +57 -0
  55. package/dist/runtime-config.js +12 -0
  56. package/dist/runtime-config.js.map +1 -1
  57. package/dist/storage.d.ts +55 -0
  58. package/dist/storage.js +112 -0
  59. package/dist/storage.js.map +1 -0
  60. package/dist/telemetry.d.ts +350 -83
  61. package/dist/telemetry.js +188 -15
  62. package/dist/telemetry.js.map +1 -1
  63. package/dist/web-compute.d.ts +191 -0
  64. package/dist/web-compute.js +257 -0
  65. package/dist/web-compute.js.map +1 -0
  66. package/package.json +28 -8
  67. package/src/api.ts +864 -238
  68. package/src/auth.ts +37 -0
  69. package/src/base64url.ts +13 -0
  70. package/src/bindings.ts +74 -7
  71. package/src/cloudfront-function.ts +70 -2
  72. package/src/compute.ts +86 -0
  73. package/src/config.ts +34 -2
  74. package/src/constants.ts +76 -1
  75. package/src/email.ts +168 -0
  76. package/src/fingerprint.ts +20 -0
  77. package/src/index.ts +6 -0
  78. package/src/jobs.ts +281 -0
  79. package/src/manifest.ts +542 -114
  80. package/src/naming.ts +103 -8
  81. package/src/platform-api.ts +630 -0
  82. package/src/realtime.ts +298 -0
  83. package/src/router/decide.d.ts +7 -1
  84. package/src/router/decide.js +42 -5
  85. package/src/router.ts +33 -13
  86. package/src/runtime-config.ts +70 -0
  87. package/src/storage.ts +120 -0
  88. package/src/telemetry.ts +198 -93
  89. package/src/web-compute.ts +342 -0
package/src/email.ts ADDED
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Email: transactional mail on Amazon SES.
3
+ *
4
+ * - The foundation verifies one domain, `mail.<zone>` (`emailDomain`), with
5
+ * DKIM, a custom MAIL FROM and DMARC. Every app sends from it.
6
+ * - Each stage that declares `email` is an SES tenant with its own
7
+ * configuration set (both `names.emailTenant`). SES keeps the tenant's
8
+ * suppression list, reports its metrics and pauses it on its own when its
9
+ * bounces or complaints get bad, so one app can't spoil mail for the rest.
10
+ * - The stage role may send only as its tenant and from its own address.
11
+ * - The SDK counts recipients per UTC day against the stage's limit, in the
12
+ * platform's telemetry table (`telemetryKeys.email`).
13
+ * - Under `plat dev` and `plat test` nothing is sent: the SDK posts each
14
+ * message to the CLI, which shows it at `EMAIL_INBOX_PATH`.
15
+ *
16
+ * Isomorphic: the SDK, the engine, the CLI and the control plane share it.
17
+ */
18
+ import { PROD_STAGE } from './constants.ts';
19
+
20
+ /** `plat dev`'s local inbox on every app host (served by the local router, never deployed). */
21
+ export const EMAIL_INBOX_PATH = '/__platform/mail';
22
+ /** Environment variable with the URL the SDK posts captured mail to (`plat dev`, `plat test`). */
23
+ export const LOCAL_MAIL_URL_ENV = 'PLATFORM_LOCAL_MAIL_URL';
24
+
25
+ /** Recipients per UTC day when `email.dailyLimit` isn't set. */
26
+ export const EMAIL_DEFAULT_DAILY_LIMIT = 200;
27
+ /** Previews and local stages get at most this many recipients a day, whatever the app declares. */
28
+ export const EMAIL_NON_PROD_DAILY_LIMIT = 50;
29
+ /** SES accepts at most 50 recipients per message. */
30
+ export const EMAIL_MAX_RECIPIENTS = 50;
31
+ /** Usage rows outlive their day by this much, so the console can show yesterday. */
32
+ export const EMAIL_USAGE_TTL_SECONDS = 3 * 24 * 3600;
33
+ /**
34
+ * Local part of the user pool's sender. `login` is a reserved app name, so no
35
+ * app's address can ever be the same.
36
+ */
37
+ export const EMAIL_LOGIN_LOCAL_PART = 'login';
38
+
39
+ /** A display name for `email.name`: no quotes, angle brackets, backslashes or line breaks. */
40
+ export const EMAIL_NAME_PATTERN = /^[^"<>\\\r\n]{1,64}$/;
41
+ export const EMAIL_NAME_MESSAGE =
42
+ 'must be 1-64 characters without quotes, angle brackets, backslashes or line breaks';
43
+
44
+ /** The domain every app sends from: `mail.<zone>` (`mail.platform.ericminassian.com`). */
45
+ export function emailDomain(zone: string): string {
46
+ return `mail.${zone}`;
47
+ }
48
+
49
+ /** The custom MAIL FROM (bounce) domain under `domain`, for SPF alignment. */
50
+ export function emailMailFromDomain(domain: string): string {
51
+ return `bounce.${domain}`;
52
+ }
53
+
54
+ /** A stage's sender: `todo@<domain>` in prod, `todo--pr-12@<domain>` elsewhere. */
55
+ export function emailFromAddress(app: string, stage: string, domain: string): string {
56
+ return stage === PROD_STAGE ? `${app}@${domain}` : `${app}--${stage}@${domain}`;
57
+ }
58
+
59
+ /** Recipients a stage may send to per UTC day: the declared limit, capped outside prod. */
60
+ export function emailDailyLimit(stage: string, declared: number): number {
61
+ return stage === PROD_STAGE ? declared : Math.min(declared, EMAIL_NON_PROD_DAILY_LIMIT);
62
+ }
63
+
64
+ /** The UTC day a send counts against (`YYYY-MM-DD`): the usage row's sort key. */
65
+ export function emailUsageDay(now: number): string {
66
+ return new Date(now).toISOString().slice(0, 10);
67
+ }
68
+
69
+ /** `"Name" <address>`, or the bare address. */
70
+ export function formatMailbox(address: string, name?: string): string {
71
+ return name ? `"${name}" <${address}>` : address;
72
+ }
73
+
74
+ // ---------------------------------------------------------------- recipients
75
+
76
+ /**
77
+ * A pragmatic address check: one `@`, no whitespace, quotes, angle brackets,
78
+ * commas or semicolons, a dotted domain, and SMTP's length limits. SES checks
79
+ * the rest.
80
+ */
81
+ const ADDRESS =
82
+ /^[^\s@"<>(),;:\\[\]]{1,64}@(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+$/;
83
+
84
+ export function isEmailAddress(value: string): boolean {
85
+ return ADDRESS.test(value);
86
+ }
87
+
88
+ /** Domains that can never receive mail (RFC 2606 and RFC 6761). */
89
+ const RESERVED_DOMAINS = ['example.com', 'example.net', 'example.org'];
90
+ const RESERVED_TLDS = new Set(['test', 'example', 'invalid', 'localhost']);
91
+
92
+ /**
93
+ * True for addresses at reserved domains (`alice@example.com`, `bob@app.test`).
94
+ * Deployed stages log these instead of sending them: they always bounce, and
95
+ * bounces from test data would count against the app's reputation.
96
+ */
97
+ export function isReservedEmailDomain(address: string): boolean {
98
+ const domain = address.slice(address.lastIndexOf('@') + 1).toLowerCase();
99
+ if (RESERVED_DOMAINS.some((d) => domain === d || domain.endsWith(`.${d}`))) return true;
100
+ const tld = domain.slice(domain.lastIndexOf('.') + 1);
101
+ return RESERVED_TLDS.has(tld) || domain === 'localhost';
102
+ }
103
+
104
+ // ---------------------------------------------------------------- the message
105
+
106
+ /** What `Email.send` takes. */
107
+ export interface EmailMessage {
108
+ /** One address or up to 50. Each counts once against the daily limit. */
109
+ readonly to: string | readonly string[];
110
+ readonly subject: string;
111
+ /** Plain-text body. */
112
+ readonly text: string;
113
+ /** HTML body, shown by clients that render HTML (they fall back to `text`). */
114
+ readonly html?: string;
115
+ /** Where replies go; the sending address takes no mail. */
116
+ readonly replyTo?: string | readonly string[];
117
+ }
118
+
119
+ /** Why a message wasn't sent. */
120
+ export type EmailNotSentReason =
121
+ /** The stage's recipients for today would pass `email.dailyLimit`. */
122
+ | 'daily-limit'
123
+ /** SES paused the app's sending (its reputation policy, the owner, or AWS). */
124
+ | 'paused'
125
+ /** The message is invalid, or SES refused it. */
126
+ | 'rejected';
127
+
128
+ const asList = (v: string | readonly string[] | undefined): string[] =>
129
+ v === undefined ? [] : typeof v === 'string' ? [v] : [...v];
130
+
131
+ /** The message's recipients and reply-to addresses, normalized, or why it can't be sent. */
132
+ export function checkEmailMessage(
133
+ m: EmailMessage,
134
+ ): { ok: true; to: string[]; replyTo: string[] } | { ok: false; message: string } {
135
+ const to = asList(m.to).map((a) => a.trim());
136
+ const replyTo = asList(m.replyTo).map((a) => a.trim());
137
+ if (to.length === 0) return { ok: false, message: 'email.send needs at least one recipient in `to`' };
138
+ if (to.length > EMAIL_MAX_RECIPIENTS)
139
+ return {
140
+ ok: false,
141
+ message: `email.send takes at most ${EMAIL_MAX_RECIPIENTS} recipients (got ${to.length}); send several messages`,
142
+ };
143
+ const bad = [...to, ...replyTo].find((a) => !isEmailAddress(a));
144
+ if (bad !== undefined) return { ok: false, message: `email.send: "${bad}" is not an email address` };
145
+ if (!m.subject.trim()) return { ok: false, message: 'email.send needs a subject' };
146
+ if (/[\r\n]/.test(m.subject)) return { ok: false, message: 'email.send: the subject must be one line' };
147
+ if (!m.text && !m.html) return { ok: false, message: 'email.send needs a `text` body' };
148
+ return { ok: true, to, replyTo };
149
+ }
150
+
151
+ // ---------------------------------------------------------------- plat dev / plat test
152
+
153
+ /** One message as the CLI's local inbox keeps it (what the SDK posts to `LOCAL_MAIL_URL_ENV`). */
154
+ export interface CapturedEmail {
155
+ /** Message id, as `Email.send` returned it. */
156
+ id: string;
157
+ /** ISO time it was captured. */
158
+ at: string;
159
+ app: string;
160
+ stage: string;
161
+ /** `"Name" <address>`. */
162
+ from: string;
163
+ to: readonly string[];
164
+ replyTo: readonly string[];
165
+ subject: string;
166
+ text: string;
167
+ html?: string;
168
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Stable short hashes (FNV-1a 32-bit): no crypto dependency so the SDK stays
3
+ * tiny. Their own module so naming (and the `./naming` subpath) doesn't pull
4
+ * in Effect through telemetry.
5
+ */
6
+
7
+ /** FNV-1a of `s`'s code points, as an unsigned 32-bit integer. */
8
+ export function fnv1a(s: string): number {
9
+ let h = 0x811c9dc5;
10
+ for (const ch of s) {
11
+ h ^= ch.codePointAt(0)!;
12
+ h = Math.imul(h, 0x01000193) >>> 0;
13
+ }
14
+ return h;
15
+ }
16
+
17
+ /** `fnv1a` of the parts joined with `|`, as 8 hex digits. */
18
+ export function fingerprint(parts: readonly string[]): string {
19
+ return fnv1a(parts.join('|')).toString(16).padStart(8, '0');
20
+ }
package/src/index.ts CHANGED
@@ -1,12 +1,18 @@
1
1
  export * from './api.ts';
2
2
  export * from './auth.ts';
3
3
  export * from './bindings.ts';
4
+ export * from './compute.ts';
4
5
  export * from './config.ts';
5
6
  export * from './constants.ts';
6
7
  export * from './cron.ts';
8
+ export * from './email.ts';
7
9
  export * from './ids.ts';
10
+ export * from './jobs.ts';
8
11
  export * from './manifest.ts';
9
12
  export * from './naming.ts';
13
+ export * from './realtime.ts';
10
14
  export * from './router.ts';
11
15
  export * from './runtime-config.ts';
16
+ export * from './storage.ts';
12
17
  export * from './telemetry.ts';
18
+ export * from './web-compute.ts';
package/src/jobs.ts ADDED
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Jobs: queue messages, events and cron runs. They are pushed, never polled:
3
+ * a queue send is an async Lambda invoke of the function its handler runs in,
4
+ * events arrive from EventBridge and crons from EventBridge Scheduler, and a
5
+ * failed run is retried through a one-shot Scheduler schedule. A stage with
6
+ * jobs costs nothing until one runs (an SQS queue with a Lambda event source
7
+ * mapping costs ~$0.26 a month in empty polls).
8
+ *
9
+ * After its last attempt a job goes to the stage's dead-letter queue, an SQS
10
+ * queue nothing polls. Four writers share it: the SDK (a handler that failed
11
+ * every attempt, `DeadLetter`), Lambda's on-failure destination (a crash or
12
+ * timeout retried twice, or an event older than six hours), Scheduler's
13
+ * dead-letter queue (a retry or cron it couldn't deliver) and EventBridge's (an
14
+ * event it couldn't deliver). `readDeadLetter` reads all four.
15
+ */
16
+ import { fingerprint } from './fingerprint.ts';
17
+ import type { HandlerKind } from './manifest.ts';
18
+
19
+ /** Marker on every job payload the platform sends to a worker function. */
20
+ export const JOB_MARKER = 'job';
21
+
22
+ /** What a worker function receives for a queue message, a retry, or a delayed send. */
23
+ export interface JobPayload {
24
+ __platform: typeof JOB_MARKER;
25
+ kind: HandlerKind;
26
+ /** Queue or cron key, or event type. */
27
+ name: string;
28
+ /** Stable across retries: the message's id, the event's id, or the cron run's. */
29
+ id: string;
30
+ /** Which delivery this is, from 1. */
31
+ attempt: number;
32
+ /** Epoch ms when the message was sent, the event published or the cron fired. */
33
+ sentAt: number;
34
+ /** A queue message's body. */
35
+ body?: unknown;
36
+ /** An event's detail. */
37
+ detail?: unknown;
38
+ trace?: string;
39
+ }
40
+
41
+ /**
42
+ * The largest job payload, in bytes of JSON. Retries and delayed sends go
43
+ * through a Scheduler schedule, whose input is capped at 256 KB, and a dead
44
+ * letter wraps the payload with its error, so this leaves room for both.
45
+ */
46
+ export const JOB_PAYLOAD_MAX_BYTES = 240 * 1024;
47
+
48
+ /** Attempts per kind when a handler sets none. Lambda retried events and crons twice before. */
49
+ export const DEFAULT_ATTEMPTS: Readonly<Record<HandlerKind, number>> = { queue: 5, event: 3, cron: 3 };
50
+ export const MAX_ATTEMPTS = 100;
51
+
52
+ /** The longest delay `send` takes: a one-shot schedule can be any time ahead, a year is plenty. */
53
+ export const MAX_JOB_DELAY_SECONDS = 365 * 86_400;
54
+
55
+ /**
56
+ * Scheduler fires a one-shot schedule within about a minute of its time, and
57
+ * refuses times in the past, so a delayed send or retry is scheduled at least
58
+ * this far ahead.
59
+ */
60
+ export const MIN_SCHEDULE_LEAD_SECONDS = 60;
61
+
62
+ /** Seconds before attempt `failed + 1`: 1, 2, 4 … minutes, at most an hour. */
63
+ export function retryDelaySeconds(failed: number): number {
64
+ return Math.min(60 * 2 ** Math.max(0, failed - 1), 3600);
65
+ }
66
+
67
+ /** `kind:name`, the key bindings use for a handler. */
68
+ export const handlerKey = (kind: HandlerKind, name: string): string => `${kind}:${name}`;
69
+
70
+ /**
71
+ * Name of the one-shot schedule for a retry or delayed send (≤ 64 chars of
72
+ * Scheduler's alphabet). It leads with `_`, which no cron key (a cron's own
73
+ * schedule) or service stop schedule (`<key>--stop`) starts with, then the
74
+ * kind and queue or cron key, so the console can count what's waiting per
75
+ * queue with a name prefix. Event types can be long and contain `:`, so they
76
+ * are hashed.
77
+ */
78
+ export function jobScheduleName(kind: HandlerKind, name: string, id: string): string {
79
+ return `${jobSchedulePrefix(kind, name)}${id}`.slice(0, 64);
80
+ }
81
+
82
+ export function jobSchedulePrefix(kind: HandlerKind, name: string): string {
83
+ if (kind === 'queue') return `_q-${name}-`;
84
+ if (kind === 'cron') return `_c-${name}-`;
85
+ return `_e-${fingerprint([name])}-`;
86
+ }
87
+
88
+ export const isJobSchedule = (name: string): boolean => name.startsWith('_');
89
+
90
+ /** One-shot schedule expression for `at` (UTC, whole seconds). */
91
+ export function atExpression(at: Date): string {
92
+ return `at(${at.toISOString().slice(0, 19)})`;
93
+ }
94
+
95
+ /** What the SDK writes to the dead-letter queue when a handler failed its last attempt. */
96
+ export interface DeadLetter {
97
+ v: 1;
98
+ job: JobPayload;
99
+ /** Epoch ms. */
100
+ failedAt: number;
101
+ error: { name: string; message: string };
102
+ }
103
+
104
+ /** A dead-letter queue message, whoever wrote it, in the terms the console shows. */
105
+ export interface DeadLetterView {
106
+ /** `invoke` is a direct `invokeJob` call that crashed or timed out. */
107
+ kind: HandlerKind | 'invoke';
108
+ name: string;
109
+ /** Deliveries made, when known. */
110
+ attempts: number | null;
111
+ error: { name: string; message: string };
112
+ /** Epoch ms. */
113
+ failedAt: number | null;
114
+ /** Who gave up: the SDK, Lambda (crash, timeout, too old), Scheduler or EventBridge (couldn't deliver). */
115
+ source: 'sdk' | 'lambda' | 'scheduler' | 'eventbridge';
116
+ /** What redriving sends, to the function the job's handler runs in now. */
117
+ redrive: JobPayload | { __platform: 'invoke'; name: string; payload: unknown; trace?: string };
118
+ }
119
+
120
+ /** SQS message attributes as the SDK returns them. */
121
+ type Attributes = Record<string, { StringValue?: string } | undefined>;
122
+
123
+ const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null;
124
+
125
+ /**
126
+ * Normalizes anything a worker function can receive into the job it stands
127
+ * for: a job payload as is, an EventBridge event, or a cron firing. `id` is
128
+ * used when the input carries none (a cron firing). Undefined for anything
129
+ * else, such as a direct `invoke`.
130
+ */
131
+ export function toJob(input: unknown, id: string, now: number): JobPayload | undefined {
132
+ if (!isObject(input)) return undefined;
133
+ if (input.__platform === JOB_MARKER && typeof input.kind === 'string' && typeof input.name === 'string') {
134
+ return input as unknown as JobPayload;
135
+ }
136
+ if (input.__platform === 'cron' && typeof input.name === 'string') {
137
+ return {
138
+ __platform: JOB_MARKER,
139
+ kind: 'cron',
140
+ name: input.name,
141
+ id,
142
+ attempt: 1,
143
+ sentAt: now,
144
+ ...(typeof input.trace === 'string' ? { trace: input.trace } : {}),
145
+ };
146
+ }
147
+ if (typeof input['detail-type'] === 'string') {
148
+ // The SDK publishes `{ data, trace }` as an event's detail; events from elsewhere are bare.
149
+ const detail = input.detail;
150
+ const envelope = isObject(detail) && 'data' in detail ? detail : undefined;
151
+ return {
152
+ __platform: JOB_MARKER,
153
+ kind: 'event',
154
+ name: input['detail-type'],
155
+ id: typeof input.id === 'string' ? input.id : id,
156
+ attempt: 1,
157
+ sentAt: typeof input.time === 'string' ? Date.parse(input.time) || now : now,
158
+ detail: envelope ? envelope.data : detail,
159
+ ...(envelope && typeof envelope.trace === 'string' ? { trace: envelope.trace } : {}),
160
+ };
161
+ }
162
+ return undefined;
163
+ }
164
+
165
+ /** Reads a dead-letter queue message; null for one the platform didn't write. */
166
+ export function readDeadLetter(body: string, attributes: Attributes = {}): DeadLetterView | null {
167
+ let parsed: unknown;
168
+ try {
169
+ parsed = JSON.parse(body);
170
+ } catch {
171
+ return null;
172
+ }
173
+ if (!isObject(parsed)) return null;
174
+ const attr = (name: string) => attributes[name]?.StringValue;
175
+
176
+ // The SDK's own.
177
+ if (parsed.v === 1 && isObject(parsed.job) && isObject(parsed.error)) {
178
+ const d = parsed as unknown as DeadLetter;
179
+ return {
180
+ kind: d.job.kind,
181
+ name: d.job.name,
182
+ attempts: d.job.attempt,
183
+ error: d.error,
184
+ failedAt: d.failedAt,
185
+ source: 'sdk',
186
+ redrive: { ...d.job, attempt: 1 },
187
+ };
188
+ }
189
+
190
+ // Lambda's on-failure destination record.
191
+ if (isObject(parsed.requestContext) && 'requestPayload' in parsed) {
192
+ const ctx = parsed.requestContext;
193
+ const response = isObject(parsed.responsePayload) ? parsed.responsePayload : {};
194
+ const condition = typeof ctx.condition === 'string' ? ctx.condition : 'RetriesExhausted';
195
+ const error = {
196
+ name:
197
+ typeof response.errorType === 'string'
198
+ ? response.errorType
199
+ : condition === 'EventAgeExceeded'
200
+ ? 'EventAgeExceeded'
201
+ : 'FunctionError',
202
+ message:
203
+ typeof response.errorMessage === 'string'
204
+ ? response.errorMessage
205
+ : condition === 'EventAgeExceeded'
206
+ ? 'the event waited longer than six hours (throttled)'
207
+ : condition,
208
+ };
209
+ const failedAt = typeof parsed.timestamp === 'string' ? Date.parse(parsed.timestamp) || null : null;
210
+ const attempts = typeof ctx.approximateInvokeCount === 'number' ? ctx.approximateInvokeCount : null;
211
+ return fromPayload(parsed.requestPayload, error, failedAt, 'lambda', attempts);
212
+ }
213
+
214
+ // Scheduler (a retry, delayed send or cron it couldn't deliver) and EventBridge (an event it
215
+ // couldn't deliver) put the input they meant to deliver in the body and the error in attributes.
216
+ const error = {
217
+ name: attr('ERROR_CODE') ?? 'DeliveryFailed',
218
+ message: attr('ERROR_MESSAGE') ?? 'the target could not be invoked',
219
+ };
220
+ const source = attr('RULE_ARN') ? 'eventbridge' : 'scheduler';
221
+ return fromPayload(parsed, error, null, source, null);
222
+ }
223
+
224
+ function fromPayload(
225
+ payload: unknown,
226
+ error: DeadLetterView['error'],
227
+ failedAt: number | null,
228
+ source: DeadLetterView['source'],
229
+ attempts: number | null,
230
+ ): DeadLetterView | null {
231
+ const job = toJob(payload, `r${fingerprint([JSON.stringify(payload ?? null)])}`, failedAt ?? Date.now());
232
+ if (job) {
233
+ return {
234
+ kind: job.kind,
235
+ name: job.name,
236
+ attempts: attempts ?? job.attempt,
237
+ error,
238
+ failedAt,
239
+ source,
240
+ redrive: { ...job, attempt: 1 },
241
+ };
242
+ }
243
+ if (isObject(payload) && payload.__platform === 'invoke' && typeof payload.name === 'string') {
244
+ return {
245
+ kind: 'invoke',
246
+ name: payload.name,
247
+ attempts,
248
+ error,
249
+ failedAt,
250
+ source,
251
+ redrive: {
252
+ __platform: 'invoke',
253
+ name: payload.name,
254
+ payload: payload.payload,
255
+ ...(typeof payload.trace === 'string' ? { trace: payload.trace } : {}),
256
+ },
257
+ };
258
+ }
259
+ return null;
260
+ }
261
+
262
+ /**
263
+ * The oldest `@ericminassian/platform` whose bundles this platform deploys:
264
+ * jobs became pushed (bindings v2) in 0.4.0, and an older worker can't read
265
+ * them.
266
+ */
267
+ export const MIN_SDK_VERSION = '0.4.0';
268
+
269
+ /** Whether bundles built with SDK `version` can be deployed (undefined: a CLI older than 0.4.0 sent none). */
270
+ export function sdkSupported(version: string | undefined): boolean {
271
+ if (!version) return false;
272
+ const parse = (v: string) =>
273
+ v
274
+ .split('-')[0]!
275
+ .split('.')
276
+ .map((n) => Number(n));
277
+ const [a, b] = [parse(version), parse(MIN_SDK_VERSION)];
278
+ if (a.length !== 3 || a.some((n) => !Number.isInteger(n))) return false;
279
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i]! > b[i]!;
280
+ return true;
281
+ }