@mevdragon/vidfarm-devcli 0.5.2 → 0.6.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 (113) hide show
  1. package/README.md +3 -3
  2. package/demo/README.md +28 -0
  3. package/demo/dist/app.css +1 -0
  4. package/demo/dist/app.js +1184 -0
  5. package/demo/dist/chunks/chunk-DXB73IDG.js +1 -0
  6. package/demo/dist/chunks/chunk-S7OWAJDS.js +36 -0
  7. package/demo/dist/chunks/chunk-VTIBZ6AN.js +1 -0
  8. package/demo/dist/chunks/dist-ADSJKBVE.js +332 -0
  9. package/demo/dist/chunks/domEditingLayers-VZMLL4AP-SGHWPND4.js +1 -0
  10. package/demo/dist/chunks/hyperframes-player-XB65TCD6.js +425 -0
  11. package/demo/dist/chunks/lib-XAQ37YOE.js +1 -0
  12. package/demo/dist/chunks/src-TJ2QYA4U.js +207 -0
  13. package/demo/dist/favicon.ico +0 -0
  14. package/demo/dist/icons/timeline/audio.svg +7 -0
  15. package/demo/dist/icons/timeline/captions.svg +5 -0
  16. package/demo/dist/icons/timeline/composition.svg +12 -0
  17. package/demo/dist/icons/timeline/image.svg +18 -0
  18. package/demo/dist/icons/timeline/music.svg +10 -0
  19. package/demo/dist/icons/timeline/text.svg +3 -0
  20. package/demo/dist/index.html +15 -0
  21. package/dist/src/account-pages-legacy.js +9396 -0
  22. package/dist/src/account-pages.js +61 -0
  23. package/dist/src/app.js +14378 -0
  24. package/dist/src/cli.js +1 -1
  25. package/dist/src/composition-runtime.js +613 -0
  26. package/dist/src/config.js +166 -0
  27. package/dist/src/context.js +447 -0
  28. package/dist/src/dev-app-legacy.js +739 -0
  29. package/dist/src/dev-app.js +6 -0
  30. package/dist/src/domain.js +2 -0
  31. package/dist/src/editor-chat-history.js +82 -0
  32. package/dist/src/editor-chat.js +449 -0
  33. package/dist/src/editor-dark-theme.js +1128 -0
  34. package/dist/src/frontend/debug.js +71 -0
  35. package/dist/src/frontend/flockposter-cache-store.js +124 -0
  36. package/dist/src/frontend/homepage-client.js +182 -0
  37. package/dist/src/frontend/homepage-shared.js +4 -0
  38. package/dist/src/frontend/homepage-store.js +28 -0
  39. package/dist/src/frontend/homepage-view.js +547 -0
  40. package/dist/src/frontend/page-runtime-client.js +132 -0
  41. package/dist/src/frontend/page-runtime-store.js +9 -0
  42. package/dist/src/frontend/sentry.js +42 -0
  43. package/dist/src/frontend/template-editor-chat.js +3960 -0
  44. package/dist/src/help-page.js +346 -0
  45. package/dist/src/homepage.js +1235 -0
  46. package/dist/src/hyperframes/composition.js +180 -0
  47. package/dist/src/index.js +16 -0
  48. package/dist/src/instrument.js +30 -0
  49. package/dist/src/lib/crypto.js +45 -0
  50. package/dist/src/lib/dev-log.js +54 -0
  51. package/dist/src/lib/display-name.js +11 -0
  52. package/dist/src/lib/ids.js +24 -0
  53. package/dist/src/lib/images.js +19 -0
  54. package/dist/src/lib/json.js +15 -0
  55. package/dist/src/lib/package-root.js +47 -0
  56. package/dist/src/lib/template-paths.js +28 -0
  57. package/dist/src/lib/time.js +7 -0
  58. package/dist/src/lib/url-clean.js +85 -0
  59. package/dist/src/page-runtime.js +2 -0
  60. package/dist/src/page-shell.js +1381 -0
  61. package/dist/src/primitive-context.js +357 -0
  62. package/dist/src/primitive-registry.js +2436 -0
  63. package/dist/src/primitive-sdk.js +4 -0
  64. package/dist/src/primitives/hyperframes-media.js +108 -0
  65. package/dist/src/react-page-shell.js +35 -0
  66. package/dist/src/ready-post-schedule-component.js +1540 -0
  67. package/dist/src/registry.js +296 -0
  68. package/dist/src/runtime.js +35 -0
  69. package/dist/src/services/api-call-history.js +249 -0
  70. package/dist/src/services/auth.js +152 -0
  71. package/dist/src/services/billing-pricing.js +39 -0
  72. package/dist/src/services/billing.js +228 -0
  73. package/dist/src/services/cast.js +127 -0
  74. package/dist/src/services/chat-threads.js +92 -0
  75. package/dist/src/services/composition-sanitize.js +124 -0
  76. package/dist/src/services/composition-watch.js +79 -0
  77. package/dist/src/services/fork-access.js +93 -0
  78. package/dist/src/services/fork-manifest.js +42 -0
  79. package/dist/src/services/ghostcut.js +179 -0
  80. package/dist/src/services/hyperframes.js +2307 -0
  81. package/dist/src/services/job-capacity.js +14 -0
  82. package/dist/src/services/job-logs.js +197 -0
  83. package/dist/src/services/jobs.js +136 -0
  84. package/dist/src/services/local-dynamo.js +0 -0
  85. package/dist/src/services/media-processing.js +766 -0
  86. package/dist/src/services/primitive-media-lambda.js +280 -0
  87. package/dist/src/services/providers.js +2926 -0
  88. package/dist/src/services/rate-limits.js +262 -0
  89. package/dist/src/services/serverless-auth.js +382 -0
  90. package/dist/src/services/serverless-jobs.js +1082 -0
  91. package/dist/src/services/serverless-provider-keys.js +409 -0
  92. package/dist/src/services/serverless-records.js +1385 -0
  93. package/dist/src/services/serverless-template-configs.js +75 -0
  94. package/dist/src/services/storage.js +383 -0
  95. package/dist/src/services/template-certification.js +413 -0
  96. package/dist/src/services/template-loader.js +99 -0
  97. package/dist/src/services/template-runtime-bundles.js +217 -0
  98. package/dist/src/services/template-sources.js +1017 -0
  99. package/dist/src/services/video-normalization.js +2 -0
  100. package/dist/src/services/webhooks.js +62 -0
  101. package/dist/src/template-editor-pages.js +2576 -0
  102. package/dist/src/template-editor-shell.js +2840 -0
  103. package/dist/src/template-sdk.js +4 -0
  104. package/dist/src/worker.js +17 -0
  105. package/package.json +6 -4
  106. package/public/assets/homepage-app.js +54 -0
  107. package/public/assets/homepage-client-app.js +80 -0
  108. package/public/assets/page-runtime-client-app.js +94 -0
  109. package/src/assets/SELLING_AWARENESS_STAGES.md +579 -0
  110. package/src/assets/SELLING_WITH_HOOKS.md +377 -0
  111. package/src/assets/SELLING_WITH_VSLS.md +606 -0
  112. package/src/assets/favicon.ico +0 -0
  113. package/src/assets/logo-vidfarm.png +0 -0
@@ -0,0 +1,1082 @@
1
+ import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
2
+ import { DynamoDBDocumentClient, GetCommand, PutCommand, QueryCommand, ScanCommand, TransactWriteCommand, UpdateCommand } from "@aws-sdk/lib-dynamodb";
3
+ import { SFNClient, StartExecutionCommand } from "@aws-sdk/client-sfn";
4
+ import { config } from "../config.js";
5
+ import { createId } from "../lib/ids.js";
6
+ import { devLog } from "../lib/dev-log.js";
7
+ import { nowIso } from "../lib/time.js";
8
+ import { ActiveJobLimitExceededError } from "./job-capacity.js";
9
+ import { createLocalDynamoClient } from "./local-dynamo.js";
10
+ // `vidfarm serve` (RECORDS_DRIVER=local) swaps in the disk-backed shim so jobs
11
+ // queue/execute fully locally; deployed environments keep the real client.
12
+ const dynamodb = config.RECORDS_DRIVER === "local"
13
+ ? createLocalDynamoClient()
14
+ : DynamoDBDocumentClient.from(new DynamoDBClient({}), {
15
+ marshallOptions: {
16
+ removeUndefinedValues: true
17
+ }
18
+ });
19
+ const sfn = new SFNClient({});
20
+ const ACTIVE_ROOT_JOB_STATUSES = ["queued", "running", "waiting_for_provider", "waiting_for_child", "waiting_for_human"];
21
+ const ACTIVE_JOB_STATUSES = new Set(ACTIVE_ROOT_JOB_STATUSES);
22
+ export class ServerlessJobsService {
23
+ async createRootJob(input) {
24
+ const tableName = requireMainTableName();
25
+ const createdAt = nowIso();
26
+ const job = {
27
+ id: createId("job"),
28
+ templateId: input.templateId,
29
+ operationName: input.operationName,
30
+ workflowName: input.workflowName,
31
+ tracer: input.tracer,
32
+ status: "queued",
33
+ customerId: input.customer.id,
34
+ payload: {
35
+ ...input.payload,
36
+ _providerHint: input.providerHint ?? null
37
+ },
38
+ result: null,
39
+ error: null,
40
+ progress: 0,
41
+ webhookUrl: normalizeWebhookUrl(input.webhookUrl) ?? normalizeWebhookUrl(input.customer.defaultWebhookUrl),
42
+ parentJobId: null,
43
+ priority: 100,
44
+ attemptCount: 0,
45
+ maxAttempts: 6,
46
+ runAfter: createdAt,
47
+ createdAt,
48
+ updatedAt: createdAt,
49
+ startedAt: null,
50
+ completedAt: null
51
+ };
52
+ await this.persistRootAndStart(tableName, job);
53
+ devLog("jobs.root.created", {
54
+ job_id: job.id,
55
+ customer_id: job.customerId,
56
+ template_id: job.templateId,
57
+ operation_name: job.operationName,
58
+ workflow_name: job.workflowName,
59
+ tracer: job.tracer
60
+ });
61
+ return job;
62
+ }
63
+ async createChildJob(input) {
64
+ const createdAt = nowIso();
65
+ const job = {
66
+ id: createId("job"),
67
+ templateId: input.templateId,
68
+ operationName: input.operationName,
69
+ workflowName: input.workflowName,
70
+ tracer: input.tracer,
71
+ status: "queued",
72
+ customerId: input.customerId,
73
+ payload: {
74
+ ...input.payload,
75
+ _providerHint: input.providerHint ?? null
76
+ },
77
+ result: null,
78
+ error: null,
79
+ progress: 0,
80
+ webhookUrl: null,
81
+ parentJobId: input.parentJobId,
82
+ priority: 110,
83
+ attemptCount: 0,
84
+ maxAttempts: 6,
85
+ runAfter: createdAt,
86
+ createdAt,
87
+ updatedAt: createdAt,
88
+ startedAt: null,
89
+ completedAt: null
90
+ };
91
+ await dynamodb.send(new PutCommand({
92
+ TableName: requireMainTableName(),
93
+ Item: {
94
+ ...jobToItem(job),
95
+ parent_job_id: input.parentJobId
96
+ },
97
+ ConditionExpression: "attribute_not_exists(pk)"
98
+ }));
99
+ await dynamodb.send(new PutCommand({
100
+ TableName: requireMainTableName(),
101
+ Item: {
102
+ pk: jobPk(input.parentJobId),
103
+ sk: `CHILD#${createdAt}#${job.id}`,
104
+ entity_type: "JobChildPointer",
105
+ child_job_id: job.id,
106
+ job_id: input.parentJobId,
107
+ customer_id: input.customerId,
108
+ created_at: createdAt
109
+ }
110
+ }));
111
+ try {
112
+ const executionArn = await this.startWorkflow(job);
113
+ if (executionArn) {
114
+ await dynamodb.send(new UpdateCommand({
115
+ TableName: requireMainTableName(),
116
+ Key: jobKey(job.id),
117
+ UpdateExpression: "set step_execution_arn = :arn, updated_at = :updated",
118
+ ExpressionAttributeValues: {
119
+ ":arn": executionArn,
120
+ ":updated": nowIso()
121
+ }
122
+ }));
123
+ }
124
+ }
125
+ catch (error) {
126
+ devLog("jobs.child.workflow_start_failed", {
127
+ job_id: job.id,
128
+ parent_job_id: input.parentJobId,
129
+ error: error instanceof Error ? error.message : String(error)
130
+ }, "error");
131
+ }
132
+ devLog("jobs.child.created", {
133
+ job_id: job.id,
134
+ parent_job_id: input.parentJobId,
135
+ customer_id: job.customerId,
136
+ template_id: job.templateId,
137
+ operation_name: job.operationName,
138
+ workflow_name: job.workflowName,
139
+ tracer: job.tracer
140
+ });
141
+ return job;
142
+ }
143
+ async getJob(jobId) {
144
+ const tableName = requireMainTableName();
145
+ const response = await dynamodb.send(new GetCommand({
146
+ TableName: tableName,
147
+ Key: jobKey(jobId)
148
+ }));
149
+ const job = response.Item ? itemToJob(response.Item) : null;
150
+ devLog("jobs.get", {
151
+ job_id: jobId,
152
+ found: Boolean(job),
153
+ customer_id: job?.customerId ?? null,
154
+ status: job?.status ?? null
155
+ });
156
+ return job;
157
+ }
158
+ async listChildJobs(parentJobId) {
159
+ const response = await dynamodb.send(new QueryCommand({
160
+ TableName: requireMainTableName(),
161
+ KeyConditionExpression: "pk = :pk and begins_with(sk, :prefix)",
162
+ ExpressionAttributeValues: {
163
+ ":pk": jobPk(parentJobId),
164
+ ":prefix": "CHILD#"
165
+ },
166
+ ScanIndexForward: false,
167
+ Limit: 500
168
+ }));
169
+ const childIds = (response.Items ?? [])
170
+ .map((item) => typeof item.child_job_id === "string" ? item.child_job_id : null)
171
+ .filter((id) => Boolean(id));
172
+ const jobs = [];
173
+ for (const childId of childIds) {
174
+ const child = await this.getJob(childId);
175
+ if (child) {
176
+ jobs.push(child);
177
+ }
178
+ }
179
+ return jobs;
180
+ }
181
+ async listJobs(input) {
182
+ const tableName = requireMainTableName();
183
+ const limit = Math.max(1, Math.min(input.limit ?? 100, 500));
184
+ const index = input.templateId ? "gsi2" : input.tracer ? "gsi3" : "gsi1";
185
+ const partition = input.templateId
186
+ ? customerTemplatePk(input.customerId, input.templateId)
187
+ : input.tracer
188
+ ? customerTracerPk(input.customerId, input.tracer)
189
+ : customerPk(input.customerId);
190
+ const response = await dynamodb.send(new QueryCommand({
191
+ TableName: tableName,
192
+ IndexName: index,
193
+ KeyConditionExpression: `${index}pk = :pk`,
194
+ ExpressionAttributeValues: {
195
+ ":pk": partition
196
+ },
197
+ ScanIndexForward: false,
198
+ Limit: limit,
199
+ ExclusiveStartKey: input.cursor ? cursorToStartKey(input, index) : undefined
200
+ }));
201
+ const jobs = (response.Items ?? []).map(itemToJob);
202
+ const filtered = jobs.filter((job) => {
203
+ if (input.tracer && job.tracer !== input.tracer) {
204
+ return false;
205
+ }
206
+ if (input.startTime && job.createdAt < input.startTime) {
207
+ return false;
208
+ }
209
+ if (input.endTime && job.createdAt > input.endTime) {
210
+ return false;
211
+ }
212
+ return true;
213
+ });
214
+ devLog("jobs.list", {
215
+ customer_id: input.customerId,
216
+ template_id: input.templateId ?? null,
217
+ tracer: input.tracer ?? null,
218
+ count: filtered.length,
219
+ limit
220
+ });
221
+ return filtered;
222
+ }
223
+ async cancelJob(jobId) {
224
+ const now = nowIso();
225
+ await this.addLogEvent({
226
+ id: createId("evt"),
227
+ jobId,
228
+ level: "warn",
229
+ message: "Job cancelled",
230
+ metadata: { reason: "user_request" },
231
+ progress: null,
232
+ artifactKey: null,
233
+ createdAt: now
234
+ });
235
+ await this.updateJobStatus({
236
+ id: jobId,
237
+ status: "cancelled",
238
+ error: { message: "Cancelled by user request." },
239
+ completedAt: now
240
+ });
241
+ devLog("jobs.cancelled", {
242
+ job_id: jobId
243
+ }, "warn");
244
+ }
245
+ async updateJobStatus(input) {
246
+ const current = await this.getJob(input.id);
247
+ const timestamp = nowIso();
248
+ const isTerminalStatus = input.status === "succeeded" || input.status === "failed" || input.status === "cancelled";
249
+ const shouldReleaseRootCapacity = Boolean(isTerminalStatus
250
+ && current
251
+ && current.parentJobId === null
252
+ && ACTIVE_ROOT_JOB_STATUSES.includes(current.status));
253
+ if (isTerminalStatus && current && !ACTIVE_ROOT_JOB_STATUSES.includes(current.status)) {
254
+ devLog("jobs.status.terminal_update_skipped", {
255
+ job_id: input.id,
256
+ current_status: current.status,
257
+ attempted_status: input.status
258
+ }, "warn");
259
+ return;
260
+ }
261
+ const nextCompletedAt = input.completedAt
262
+ ?? (isTerminalStatus ? timestamp : current?.completedAt ?? null);
263
+ const nextStartedAt = input.startedAt !== undefined
264
+ ? input.startedAt
265
+ : input.status === "running"
266
+ ? current?.startedAt ?? timestamp
267
+ : input.status === "queued"
268
+ ? null
269
+ : current?.startedAt ?? null;
270
+ const expressionAttributeValues = {
271
+ ":status": input.status,
272
+ ":progress": input.progress ?? current?.progress ?? 0,
273
+ ":result": input.result === undefined ? current?.result ?? null : input.result,
274
+ ":error": input.error === undefined ? current?.error ?? null : input.error,
275
+ ":runAfter": input.runAfter ?? current?.runAfter ?? timestamp,
276
+ ":startedAt": nextStartedAt,
277
+ ":completedAt": nextCompletedAt,
278
+ ":updatedAt": timestamp
279
+ };
280
+ const conditionExpression = isTerminalStatus
281
+ ? [
282
+ "#status = :queuedStatus",
283
+ "#status = :runningStatus",
284
+ "#status = :waitingForProviderStatus",
285
+ "#status = :waitingForChildStatus",
286
+ "#status = :waitingForHumanStatus"
287
+ ].join(" OR ")
288
+ : [
289
+ "attribute_not_exists(#status)",
290
+ "(#status <> :succeededStatus AND #status <> :failedStatus AND #status <> :cancelledStatus)"
291
+ ].join(" OR ");
292
+ if (isTerminalStatus) {
293
+ expressionAttributeValues[":queuedStatus"] = "queued";
294
+ expressionAttributeValues[":runningStatus"] = "running";
295
+ expressionAttributeValues[":waitingForProviderStatus"] = "waiting_for_provider";
296
+ expressionAttributeValues[":waitingForChildStatus"] = "waiting_for_child";
297
+ expressionAttributeValues[":waitingForHumanStatus"] = "waiting_for_human";
298
+ }
299
+ else {
300
+ expressionAttributeValues[":succeededStatus"] = "succeeded";
301
+ expressionAttributeValues[":failedStatus"] = "failed";
302
+ expressionAttributeValues[":cancelledStatus"] = "cancelled";
303
+ }
304
+ try {
305
+ await dynamodb.send(new UpdateCommand({
306
+ TableName: requireMainTableName(),
307
+ Key: jobKey(input.id),
308
+ UpdateExpression: [
309
+ "set #status = :status",
310
+ "progress = :progress",
311
+ "result_json = :result",
312
+ "error_json = :error",
313
+ "run_after = :runAfter",
314
+ "started_at = :startedAt",
315
+ "completed_at = :completedAt",
316
+ "updated_at = :updatedAt"
317
+ ].join(", "),
318
+ ConditionExpression: conditionExpression,
319
+ ExpressionAttributeNames: {
320
+ "#status": "status"
321
+ },
322
+ ExpressionAttributeValues: expressionAttributeValues
323
+ }));
324
+ }
325
+ catch (error) {
326
+ if (isConditionalCheckFailed(error)) {
327
+ if (isTerminalStatus) {
328
+ devLog("jobs.status.terminal_update_condition_failed", {
329
+ job_id: input.id,
330
+ attempted_status: input.status
331
+ }, "warn");
332
+ return;
333
+ }
334
+ devLog("jobs.status.non_terminal_update_skipped", {
335
+ job_id: input.id,
336
+ attempted_status: input.status,
337
+ progress: input.progress ?? current?.progress ?? 0
338
+ }, "warn");
339
+ return;
340
+ }
341
+ throw error;
342
+ }
343
+ if (shouldReleaseRootCapacity && current) {
344
+ await this.decrementRootCapacity(current.customerId, current.id);
345
+ }
346
+ devLog("jobs.status.updated", {
347
+ job_id: input.id,
348
+ status: input.status,
349
+ progress: input.progress ?? current?.progress ?? 0,
350
+ completed_at: nextCompletedAt
351
+ }, input.status === "failed" ? "error" : input.status === "cancelled" ? "warn" : "info");
352
+ }
353
+ async insertArtifact(record) {
354
+ const createdAt = nowIso();
355
+ await dynamodb.send(new PutCommand({
356
+ TableName: requireMainTableName(),
357
+ Item: artifactToItem({
358
+ id: record.id,
359
+ jobId: record.jobId,
360
+ customerId: record.customerId,
361
+ templateId: record.templateId,
362
+ kind: record.kind,
363
+ storageKey: record.storageKey,
364
+ publicUrl: record.publicUrl ?? null,
365
+ metadata: record.metadata ?? {},
366
+ createdAt
367
+ })
368
+ }));
369
+ devLog("jobs.artifact.inserted", {
370
+ artifact_id: record.id,
371
+ job_id: record.jobId,
372
+ customer_id: record.customerId,
373
+ template_id: record.templateId,
374
+ kind: record.kind,
375
+ storage_key: record.storageKey,
376
+ has_public_url: Boolean(record.publicUrl)
377
+ });
378
+ }
379
+ async sweepStaleActiveJobs(input = {}) {
380
+ const customerIds = input.customerId
381
+ ? [input.customerId]
382
+ : await this.listCapacityCustomerIds(input.maxCustomers ?? 100);
383
+ let swept = 0;
384
+ let scanned = 0;
385
+ for (const customerId of customerIds) {
386
+ const result = await this.sweepStaleActiveJobsForCustomer(customerId, {
387
+ maxJobs: input.maxJobsPerCustomer ?? 1000
388
+ });
389
+ swept += result.swept;
390
+ scanned += result.scanned;
391
+ }
392
+ return {
393
+ customers: customerIds.length,
394
+ scanned,
395
+ swept
396
+ };
397
+ }
398
+ async listArtifactsForJob(input) {
399
+ const response = await dynamodb.send(new QueryCommand({
400
+ TableName: requireMainTableName(),
401
+ KeyConditionExpression: "pk = :pk and begins_with(sk, :prefix)",
402
+ ExpressionAttributeValues: {
403
+ ":pk": jobPk(input.jobId),
404
+ ":prefix": "ARTIFACT#"
405
+ },
406
+ ScanIndexForward: false,
407
+ Limit: Math.max(1, Math.min(input.limit ?? 100, 501))
408
+ }));
409
+ const artifacts = (response.Items ?? [])
410
+ .map(itemToArtifact)
411
+ .filter((artifact) => {
412
+ if (artifact.customerId !== input.customerId) {
413
+ return false;
414
+ }
415
+ if (input.templateId && artifact.templateId !== input.templateId) {
416
+ return false;
417
+ }
418
+ if (input.cursor && (artifact.createdAt > input.cursor.createdAt || (artifact.createdAt === input.cursor.createdAt && artifact.id >= input.cursor.id))) {
419
+ return false;
420
+ }
421
+ return true;
422
+ });
423
+ devLog("jobs.artifacts.list", {
424
+ job_id: input.jobId,
425
+ customer_id: input.customerId,
426
+ template_id: input.templateId ?? null,
427
+ count: artifacts.length,
428
+ limit: input.limit ?? 100
429
+ });
430
+ return artifacts;
431
+ }
432
+ async listLogs(input) {
433
+ const response = await dynamodb.send(new QueryCommand({
434
+ TableName: requireMainTableName(),
435
+ KeyConditionExpression: "pk = :pk and begins_with(sk, :prefix)",
436
+ ExpressionAttributeValues: {
437
+ ":pk": jobPk(input.jobId),
438
+ ":prefix": "LOG#"
439
+ },
440
+ ScanIndexForward: false,
441
+ Limit: Math.max(1, Math.min(input.limit ?? 100, 500))
442
+ }));
443
+ return (response.Items ?? [])
444
+ .map(itemToLog)
445
+ .filter((event) => {
446
+ if (input.startTime && event.createdAt < input.startTime) {
447
+ return false;
448
+ }
449
+ if (input.endTime && event.createdAt > input.endTime) {
450
+ return false;
451
+ }
452
+ if (input.cursor && (event.createdAt > input.cursor.createdAt || (event.createdAt === input.cursor.createdAt && event.id >= input.cursor.id))) {
453
+ return false;
454
+ }
455
+ return true;
456
+ });
457
+ }
458
+ async listLogStorageKeys() {
459
+ return [];
460
+ }
461
+ async getRootQueueCapacityStatus(customer) {
462
+ await this.sweepStaleActiveJobsForCustomer(customer.id);
463
+ await this.ensureRootCapacityCounter(customer.id);
464
+ const response = await dynamodb.send(new GetCommand({
465
+ TableName: requireMainTableName(),
466
+ Key: customerJobCapacityKey(customer.id)
467
+ }));
468
+ const activeCount = typeof response.Item?.active_count === "number" ? response.Item.active_count : 0;
469
+ const limit = config.MAX_ACTIVE_JOBS_PER_CUSTOMER;
470
+ return {
471
+ plan_tier: customer.planTier,
472
+ scope: "root_jobs",
473
+ customer: {
474
+ limit,
475
+ pending_count: activeCount,
476
+ active_count: activeCount,
477
+ remaining: Math.max(0, limit - activeCount),
478
+ enabled: true
479
+ },
480
+ pending_statuses: ACTIVE_ROOT_JOB_STATUSES,
481
+ retry_after_seconds: 30
482
+ };
483
+ }
484
+ async persistRootAndStart(tableName, job) {
485
+ await this.sweepStaleActiveJobsForCustomer(job.customerId);
486
+ await this.ensureRootCapacityCounter(job.customerId);
487
+ const queuedLogId = createId("evt");
488
+ for (let attempt = 0; attempt < 2; attempt += 1) {
489
+ try {
490
+ await this.writeRootJobTransaction(tableName, job, queuedLogId);
491
+ break;
492
+ }
493
+ catch (error) {
494
+ if (!isTransactionCancelledForCapacity(error)) {
495
+ throw error;
496
+ }
497
+ const activeCount = await this.reconcileRootCapacityCounter(job.customerId);
498
+ if (attempt === 0 && activeCount < config.MAX_ACTIVE_JOBS_PER_CUSTOMER) {
499
+ devLog("jobs.capacity.reconciled_retry", {
500
+ job_id: job.id,
501
+ customer_id: job.customerId,
502
+ active_count: activeCount,
503
+ limit: config.MAX_ACTIVE_JOBS_PER_CUSTOMER
504
+ }, "warn");
505
+ continue;
506
+ }
507
+ throw new ActiveJobLimitExceededError(`Customer has reached the active job limit of ${config.MAX_ACTIVE_JOBS_PER_CUSTOMER}.`, config.MAX_ACTIVE_JOBS_PER_CUSTOMER, activeCount, ACTIVE_ROOT_JOB_STATUSES, 30);
508
+ }
509
+ }
510
+ try {
511
+ const executionArn = await this.startWorkflow(job);
512
+ if (executionArn) {
513
+ await dynamodb.send(new UpdateCommand({
514
+ TableName: tableName,
515
+ Key: jobKey(job.id),
516
+ UpdateExpression: "set step_execution_arn = :arn, updated_at = :updated",
517
+ ExpressionAttributeValues: {
518
+ ":arn": executionArn,
519
+ ":updated": nowIso()
520
+ }
521
+ }));
522
+ }
523
+ }
524
+ catch (error) {
525
+ await this.updateJobStatus({
526
+ id: job.id,
527
+ status: "failed",
528
+ error: {
529
+ message: error instanceof Error ? error.message : "Unable to start job workflow.",
530
+ type: "job_workflow_start_failed"
531
+ }
532
+ });
533
+ throw error;
534
+ }
535
+ }
536
+ async writeRootJobTransaction(tableName, job, queuedLogId) {
537
+ await dynamodb.send(new TransactWriteCommand({
538
+ TransactItems: [
539
+ {
540
+ Update: {
541
+ TableName: tableName,
542
+ Key: customerJobCapacityKey(job.customerId),
543
+ UpdateExpression: [
544
+ "set active_count = if_not_exists(active_count, :zero) + :one",
545
+ "updated_at = :updated",
546
+ "capacity_limit = :limit",
547
+ "entity_type = :entityType"
548
+ ].join(", "),
549
+ ConditionExpression: "attribute_not_exists(active_count) OR active_count < :limit",
550
+ ExpressionAttributeValues: {
551
+ ":zero": 0,
552
+ ":one": 1,
553
+ ":limit": config.MAX_ACTIVE_JOBS_PER_CUSTOMER,
554
+ ":updated": job.createdAt,
555
+ ":entityType": "CustomerJobCapacity"
556
+ }
557
+ }
558
+ },
559
+ {
560
+ Put: {
561
+ TableName: tableName,
562
+ Item: jobToItem(job),
563
+ ConditionExpression: "attribute_not_exists(pk)"
564
+ }
565
+ },
566
+ {
567
+ Put: {
568
+ TableName: tableName,
569
+ Item: {
570
+ pk: jobPk(job.id),
571
+ sk: `LOG#${job.createdAt}#${queuedLogId}`,
572
+ entity_type: "JobLogEvent",
573
+ id: queuedLogId,
574
+ job_id: job.id,
575
+ level: "info",
576
+ message: "Job queued",
577
+ metadata_json: {
578
+ runtime: "serverless",
579
+ template_id: job.templateId,
580
+ operation_name: job.operationName
581
+ },
582
+ progress: 0,
583
+ artifact_key: null,
584
+ created_at: job.createdAt
585
+ }
586
+ }
587
+ }
588
+ ]
589
+ }));
590
+ }
591
+ async ensureRootCapacityCounter(customerId) {
592
+ const tableName = requireMainTableName();
593
+ const response = await dynamodb.send(new GetCommand({
594
+ TableName: tableName,
595
+ Key: customerJobCapacityKey(customerId)
596
+ }));
597
+ if (response.Item) {
598
+ return;
599
+ }
600
+ const activeCount = await this.countActiveRootJobs(customerId);
601
+ try {
602
+ await dynamodb.send(new PutCommand({
603
+ TableName: tableName,
604
+ Item: {
605
+ ...customerJobCapacityKey(customerId),
606
+ entity_type: "CustomerJobCapacity",
607
+ customer_id: customerId,
608
+ active_count: activeCount,
609
+ capacity_limit: config.MAX_ACTIVE_JOBS_PER_CUSTOMER,
610
+ updated_at: nowIso()
611
+ },
612
+ ConditionExpression: "attribute_not_exists(pk)"
613
+ }));
614
+ }
615
+ catch (error) {
616
+ if (isConditionalCheckFailed(error)) {
617
+ return;
618
+ }
619
+ throw error;
620
+ }
621
+ }
622
+ async reconcileRootCapacityCounter(customerId) {
623
+ await this.sweepStaleActiveJobsForCustomer(customerId);
624
+ const activeCount = await this.countActiveRootJobs(customerId);
625
+ await dynamodb.send(new UpdateCommand({
626
+ TableName: requireMainTableName(),
627
+ Key: customerJobCapacityKey(customerId),
628
+ UpdateExpression: "set active_count = :activeCount, capacity_limit = :limit, updated_at = :updated, entity_type = :entityType",
629
+ ExpressionAttributeValues: {
630
+ ":activeCount": activeCount,
631
+ ":limit": config.MAX_ACTIVE_JOBS_PER_CUSTOMER,
632
+ ":updated": nowIso(),
633
+ ":entityType": "CustomerJobCapacity"
634
+ }
635
+ }));
636
+ return activeCount;
637
+ }
638
+ async getRootCapacityCount(customerId) {
639
+ const response = await dynamodb.send(new GetCommand({
640
+ TableName: requireMainTableName(),
641
+ Key: customerJobCapacityKey(customerId)
642
+ }));
643
+ return typeof response.Item?.active_count === "number" ? response.Item.active_count : null;
644
+ }
645
+ async countActiveRootJobs(customerId) {
646
+ let count = 0;
647
+ let exclusiveStartKey;
648
+ do {
649
+ const response = await dynamodb.send(new QueryCommand({
650
+ TableName: requireMainTableName(),
651
+ IndexName: "gsi1",
652
+ KeyConditionExpression: "gsi1pk = :pk",
653
+ ExpressionAttributeValues: {
654
+ ":pk": customerPk(customerId)
655
+ },
656
+ ScanIndexForward: false,
657
+ Limit: 500,
658
+ ExclusiveStartKey: exclusiveStartKey
659
+ }));
660
+ for (const item of response.Items ?? []) {
661
+ const job = itemToJob(item);
662
+ if (job.parentJobId === null && ACTIVE_ROOT_JOB_STATUSES.includes(job.status)) {
663
+ count += 1;
664
+ }
665
+ }
666
+ exclusiveStartKey = response.LastEvaluatedKey;
667
+ } while (exclusiveStartKey);
668
+ return count;
669
+ }
670
+ async listCapacityCustomerIds(limit) {
671
+ const customerIds = [];
672
+ let exclusiveStartKey;
673
+ do {
674
+ const response = await dynamodb.send(new ScanCommand({
675
+ TableName: requireMainTableName(),
676
+ FilterExpression: "entity_type = :entityType",
677
+ ExpressionAttributeValues: {
678
+ ":entityType": "CustomerJobCapacity"
679
+ },
680
+ Limit: Math.max(1, Math.min(limit - customerIds.length, 100)),
681
+ ExclusiveStartKey: exclusiveStartKey
682
+ }));
683
+ for (const item of response.Items ?? []) {
684
+ const customerId = typeof item.customer_id === "string"
685
+ ? item.customer_id
686
+ : parseCustomerIdFromCapacityPk(item.pk);
687
+ if (customerId) {
688
+ customerIds.push(customerId);
689
+ }
690
+ if (customerIds.length >= limit) {
691
+ break;
692
+ }
693
+ }
694
+ exclusiveStartKey = customerIds.length >= limit
695
+ ? undefined
696
+ : response.LastEvaluatedKey;
697
+ } while (exclusiveStartKey);
698
+ return customerIds;
699
+ }
700
+ async sweepStaleActiveJobsForCustomer(customerId, input = {}) {
701
+ const maxJobs = Math.max(1, input.maxJobs ?? 1000);
702
+ let scanned = 0;
703
+ let swept = 0;
704
+ let exclusiveStartKey;
705
+ do {
706
+ const response = await dynamodb.send(new QueryCommand({
707
+ TableName: requireMainTableName(),
708
+ IndexName: "gsi1",
709
+ KeyConditionExpression: "gsi1pk = :pk",
710
+ ExpressionAttributeValues: {
711
+ ":pk": customerPk(customerId)
712
+ },
713
+ ScanIndexForward: false,
714
+ Limit: Math.min(500, maxJobs - scanned),
715
+ ExclusiveStartKey: exclusiveStartKey
716
+ }));
717
+ for (const item of response.Items ?? []) {
718
+ scanned += 1;
719
+ const job = itemToJob(item);
720
+ const stale = describeStaleActiveJob(job);
721
+ if (!stale) {
722
+ continue;
723
+ }
724
+ await this.failStaleActiveJob(job, stale);
725
+ swept += 1;
726
+ }
727
+ exclusiveStartKey = scanned >= maxJobs
728
+ ? undefined
729
+ : response.LastEvaluatedKey;
730
+ } while (exclusiveStartKey);
731
+ if (swept > 0) {
732
+ await this.reconcileRootCapacityCounterAfterSweep(customerId);
733
+ }
734
+ return { scanned, swept };
735
+ }
736
+ async failStaleActiveJob(job, stale) {
737
+ const now = nowIso();
738
+ await this.addLogEvent({
739
+ id: createId("evt"),
740
+ jobId: job.id,
741
+ level: "error",
742
+ message: "Job marked failed by stale-job sweeper",
743
+ metadata: {
744
+ type: "stale_job_swept",
745
+ stale_reason: stale.reason,
746
+ stale_threshold_seconds: stale.thresholdSeconds,
747
+ stale_age_seconds: stale.ageSeconds,
748
+ previous_status: job.status,
749
+ started_at: job.startedAt,
750
+ updated_at: job.updatedAt,
751
+ created_at: job.createdAt
752
+ },
753
+ progress: job.progress,
754
+ artifactKey: null,
755
+ createdAt: now
756
+ });
757
+ await this.updateJobStatus({
758
+ id: job.id,
759
+ status: "failed",
760
+ error: {
761
+ message: `Job was marked failed because it became stale: ${stale.reason}.`,
762
+ type: "stale_job_swept",
763
+ stale_reason: stale.reason,
764
+ stale_threshold_seconds: stale.thresholdSeconds,
765
+ stale_age_seconds: stale.ageSeconds
766
+ },
767
+ completedAt: now
768
+ });
769
+ }
770
+ async reconcileRootCapacityCounterAfterSweep(customerId) {
771
+ const activeCount = await this.countActiveRootJobs(customerId);
772
+ await dynamodb.send(new UpdateCommand({
773
+ TableName: requireMainTableName(),
774
+ Key: customerJobCapacityKey(customerId),
775
+ UpdateExpression: "set active_count = :activeCount, capacity_limit = :limit, updated_at = :updated, entity_type = :entityType",
776
+ ExpressionAttributeValues: {
777
+ ":activeCount": activeCount,
778
+ ":limit": config.MAX_ACTIVE_JOBS_PER_CUSTOMER,
779
+ ":updated": nowIso(),
780
+ ":entityType": "CustomerJobCapacity"
781
+ }
782
+ }));
783
+ }
784
+ async decrementRootCapacity(customerId, jobId) {
785
+ try {
786
+ await dynamodb.send(new UpdateCommand({
787
+ TableName: requireMainTableName(),
788
+ Key: customerJobCapacityKey(customerId),
789
+ UpdateExpression: "set active_count = active_count - :one, updated_at = :updated",
790
+ ConditionExpression: "active_count >= :one",
791
+ ExpressionAttributeValues: {
792
+ ":one": 1,
793
+ ":updated": nowIso()
794
+ }
795
+ }));
796
+ devLog("jobs.capacity.decremented", {
797
+ job_id: jobId,
798
+ customer_id: customerId
799
+ });
800
+ }
801
+ catch (error) {
802
+ if (isConditionalCheckFailed(error)) {
803
+ devLog("jobs.capacity.decrement_skipped", {
804
+ job_id: jobId,
805
+ customer_id: customerId
806
+ }, "warn");
807
+ return;
808
+ }
809
+ throw error;
810
+ }
811
+ }
812
+ async startWorkflow(job) {
813
+ if (!config.VIDFARM_JOB_STATE_MACHINE_ARN) {
814
+ return null;
815
+ }
816
+ const response = await sfn.send(new StartExecutionCommand({
817
+ stateMachineArn: config.VIDFARM_JOB_STATE_MACHINE_ARN,
818
+ name: job.id.replace(/[^A-Za-z0-9-_]/g, "-").slice(0, 80),
819
+ input: JSON.stringify({
820
+ job_id: job.id,
821
+ customer_id: job.customerId,
822
+ template_id: job.templateId,
823
+ operation_name: job.operationName,
824
+ workflow_name: job.workflowName,
825
+ stage: "run",
826
+ attempt: 1
827
+ })
828
+ }));
829
+ devLog("jobs.workflow.started", {
830
+ job_id: job.id,
831
+ execution_arn: response.executionArn ?? null,
832
+ state_machine_arn: config.VIDFARM_JOB_STATE_MACHINE_ARN
833
+ });
834
+ return response.executionArn ?? null;
835
+ }
836
+ async addLogEvent(event) {
837
+ await dynamodb.send(new PutCommand({
838
+ TableName: requireMainTableName(),
839
+ Item: {
840
+ pk: jobPk(event.jobId),
841
+ sk: `LOG#${event.createdAt}#${event.id}`,
842
+ entity_type: "JobLogEvent",
843
+ id: event.id,
844
+ job_id: event.jobId,
845
+ level: event.level,
846
+ message: event.message,
847
+ metadata_json: event.metadata,
848
+ progress: event.progress,
849
+ artifact_key: event.artifactKey,
850
+ created_at: event.createdAt
851
+ }
852
+ }));
853
+ }
854
+ }
855
+ function isConditionalCheckFailed(error) {
856
+ return Boolean(error
857
+ && typeof error === "object"
858
+ && "name" in error
859
+ && error.name === "ConditionalCheckFailedException");
860
+ }
861
+ function isTransactionCancelledForCapacity(error) {
862
+ if (!error || typeof error !== "object" || !("name" in error) || error.name !== "TransactionCanceledException") {
863
+ return false;
864
+ }
865
+ const reasons = "CancellationReasons" in error ? error.CancellationReasons : null;
866
+ return Array.isArray(reasons) && reasons.some((reason) => {
867
+ return reason && typeof reason === "object" && "Code" in reason && reason.Code === "ConditionalCheckFailed";
868
+ });
869
+ }
870
+ function requireMainTableName() {
871
+ if (config.RECORDS_DRIVER === "local") {
872
+ return config.VIDFARM_SERVERLESS_MAIN_TABLE_NAME || "vidfarm-local-main";
873
+ }
874
+ if (!config.VIDFARM_SERVERLESS_MAIN_TABLE_NAME) {
875
+ throw new Error("Serverless job store requires VIDFARM_SERVERLESS_MAIN_TABLE_NAME.");
876
+ }
877
+ return config.VIDFARM_SERVERLESS_MAIN_TABLE_NAME;
878
+ }
879
+ function normalizeWebhookUrl(value) {
880
+ if (typeof value !== "string") {
881
+ return null;
882
+ }
883
+ const trimmed = value.trim();
884
+ return trimmed ? trimmed : null;
885
+ }
886
+ function jobPk(jobId) {
887
+ return `JOB#${jobId}`;
888
+ }
889
+ function jobKey(jobId) {
890
+ return {
891
+ pk: jobPk(jobId),
892
+ sk: "META"
893
+ };
894
+ }
895
+ function customerPk(customerId) {
896
+ return `CUSTOMER#${customerId}`;
897
+ }
898
+ function customerJobCapacityKey(customerId) {
899
+ return {
900
+ pk: customerPk(customerId),
901
+ sk: "JOB_CAPACITY"
902
+ };
903
+ }
904
+ function parseCustomerIdFromCapacityPk(value) {
905
+ if (typeof value !== "string" || !value.startsWith("CUSTOMER#")) {
906
+ return null;
907
+ }
908
+ return value.slice("CUSTOMER#".length) || null;
909
+ }
910
+ function describeStaleActiveJob(job) {
911
+ if (!ACTIVE_JOB_STATUSES.has(job.status)) {
912
+ return null;
913
+ }
914
+ const wallClockAgeSeconds = secondsSince(job.createdAt);
915
+ if (wallClockAgeSeconds >= config.MAX_JOB_WALL_CLOCK_SECONDS) {
916
+ return {
917
+ reason: "wall_clock_timeout",
918
+ thresholdSeconds: config.MAX_JOB_WALL_CLOCK_SECONDS,
919
+ ageSeconds: wallClockAgeSeconds
920
+ };
921
+ }
922
+ if (job.status === "running") {
923
+ const heartbeatAt = job.updatedAt || job.startedAt || job.createdAt;
924
+ const heartbeatAgeSeconds = secondsSince(heartbeatAt);
925
+ if (heartbeatAgeSeconds >= config.STALE_RUNNING_JOB_SECONDS) {
926
+ return {
927
+ reason: "running_heartbeat_timeout",
928
+ thresholdSeconds: config.STALE_RUNNING_JOB_SECONDS,
929
+ ageSeconds: heartbeatAgeSeconds
930
+ };
931
+ }
932
+ }
933
+ if (job.status === "queued") {
934
+ const runAfterAgeSeconds = secondsSince(job.runAfter);
935
+ if (runAfterAgeSeconds >= config.MAX_JOB_WALL_CLOCK_SECONDS) {
936
+ return {
937
+ reason: "queued_run_after_timeout",
938
+ thresholdSeconds: config.MAX_JOB_WALL_CLOCK_SECONDS,
939
+ ageSeconds: runAfterAgeSeconds
940
+ };
941
+ }
942
+ }
943
+ return null;
944
+ }
945
+ function secondsSince(value) {
946
+ const timestamp = value ? Date.parse(value) : Number.NaN;
947
+ const effectiveTimestamp = Number.isFinite(timestamp) ? timestamp : Date.now();
948
+ return Math.max(0, Math.floor((Date.now() - effectiveTimestamp) / 1000));
949
+ }
950
+ function customerTemplatePk(customerId, templateId) {
951
+ return `CUSTOMER#${customerId}#TEMPLATE#${templateId}`;
952
+ }
953
+ function customerTracerPk(customerId, tracer) {
954
+ return `CUSTOMER#${customerId}#TRACER#${tracer}`;
955
+ }
956
+ function jobSortKey(job) {
957
+ return `JOB#${job.createdAt}#${job.id}`;
958
+ }
959
+ function jobToItem(job) {
960
+ return {
961
+ pk: jobPk(job.id),
962
+ sk: "META",
963
+ entity_type: "Job",
964
+ gsi1pk: customerPk(job.customerId),
965
+ gsi1sk: jobSortKey(job),
966
+ gsi2pk: customerTemplatePk(job.customerId, job.templateId),
967
+ gsi2sk: jobSortKey(job),
968
+ gsi3pk: customerTracerPk(job.customerId, job.tracer),
969
+ gsi3sk: jobSortKey(job),
970
+ job_id: job.id,
971
+ template_id: job.templateId,
972
+ operation_name: job.operationName,
973
+ workflow_name: job.workflowName,
974
+ tracer: job.tracer,
975
+ status: job.status,
976
+ customer_id: job.customerId,
977
+ payload_json: job.payload,
978
+ result_json: job.result,
979
+ error_json: job.error,
980
+ progress: job.progress,
981
+ webhook_url: job.webhookUrl,
982
+ parent_job_id: job.parentJobId,
983
+ priority: job.priority,
984
+ attempt_count: job.attemptCount,
985
+ max_attempts: job.maxAttempts,
986
+ run_after: job.runAfter,
987
+ created_at: job.createdAt,
988
+ updated_at: job.updatedAt,
989
+ started_at: job.startedAt,
990
+ completed_at: job.completedAt
991
+ };
992
+ }
993
+ function itemToJob(item) {
994
+ return {
995
+ id: String(item.job_id),
996
+ templateId: String(item.template_id),
997
+ operationName: String(item.operation_name),
998
+ workflowName: String(item.workflow_name),
999
+ tracer: String(item.tracer),
1000
+ status: item.status,
1001
+ customerId: String(item.customer_id),
1002
+ payload: asRecord(item.payload_json),
1003
+ result: item.result_json == null ? null : asRecord(item.result_json),
1004
+ error: item.error_json == null ? null : asRecord(item.error_json),
1005
+ progress: typeof item.progress === "number" ? item.progress : 0,
1006
+ webhookUrl: typeof item.webhook_url === "string" ? item.webhook_url : null,
1007
+ parentJobId: typeof item.parent_job_id === "string" ? item.parent_job_id : null,
1008
+ priority: typeof item.priority === "number" ? item.priority : 100,
1009
+ attemptCount: typeof item.attempt_count === "number" ? item.attempt_count : 0,
1010
+ maxAttempts: typeof item.max_attempts === "number" ? item.max_attempts : 6,
1011
+ runAfter: String(item.run_after),
1012
+ createdAt: String(item.created_at),
1013
+ updatedAt: String(item.updated_at),
1014
+ startedAt: typeof item.started_at === "string" ? item.started_at : null,
1015
+ completedAt: typeof item.completed_at === "string" ? item.completed_at : null
1016
+ };
1017
+ }
1018
+ function itemToLog(item) {
1019
+ return {
1020
+ id: String(item.id),
1021
+ jobId: String(item.job_id),
1022
+ level: item.level,
1023
+ message: String(item.message),
1024
+ metadata: asRecord(item.metadata_json),
1025
+ progress: typeof item.progress === "number" ? item.progress : null,
1026
+ artifactKey: typeof item.artifact_key === "string" ? item.artifact_key : null,
1027
+ createdAt: String(item.created_at)
1028
+ };
1029
+ }
1030
+ function artifactToItem(artifact) {
1031
+ return {
1032
+ pk: jobPk(artifact.jobId),
1033
+ sk: `ARTIFACT#${artifact.createdAt}#${artifact.id}`,
1034
+ entity_type: "Artifact",
1035
+ id: artifact.id,
1036
+ artifact_id: artifact.id,
1037
+ job_id: artifact.jobId,
1038
+ customer_id: artifact.customerId,
1039
+ template_id: artifact.templateId,
1040
+ kind: artifact.kind,
1041
+ storage_key: artifact.storageKey,
1042
+ public_url: artifact.publicUrl,
1043
+ metadata_json: artifact.metadata,
1044
+ created_at: artifact.createdAt
1045
+ };
1046
+ }
1047
+ function itemToArtifact(item) {
1048
+ return {
1049
+ id: String(item.artifact_id ?? item.id),
1050
+ jobId: String(item.job_id),
1051
+ customerId: String(item.customer_id),
1052
+ templateId: String(item.template_id),
1053
+ kind: String(item.kind),
1054
+ storageKey: String(item.storage_key),
1055
+ publicUrl: typeof item.public_url === "string" ? item.public_url : null,
1056
+ metadata: asRecord(item.metadata_json),
1057
+ createdAt: String(item.created_at)
1058
+ };
1059
+ }
1060
+ function asRecord(value) {
1061
+ return value && typeof value === "object" && !Array.isArray(value)
1062
+ ? value
1063
+ : {};
1064
+ }
1065
+ function cursorToStartKey(input, index) {
1066
+ const cursor = input.cursor;
1067
+ if (!cursor) {
1068
+ return undefined;
1069
+ }
1070
+ const syntheticJob = { id: cursor.id, createdAt: cursor.createdAt };
1071
+ return {
1072
+ pk: jobPk(cursor.id),
1073
+ sk: "META",
1074
+ [`${index}pk`]: input.templateId
1075
+ ? customerTemplatePk(input.customerId, input.templateId)
1076
+ : input.tracer
1077
+ ? customerTracerPk(input.customerId, input.tracer)
1078
+ : customerPk(input.customerId),
1079
+ [`${index}sk`]: jobSortKey(syntheticJob)
1080
+ };
1081
+ }
1082
+ //# sourceMappingURL=serverless-jobs.js.map