alepha 0.20.1 → 0.20.2

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 (232) hide show
  1. package/dist/api/files/index.js +2 -1
  2. package/dist/api/files/index.js.map +1 -1
  3. package/dist/api/jobs/index.browser.js +64 -148
  4. package/dist/api/jobs/index.browser.js.map +1 -1
  5. package/dist/api/jobs/index.d.ts +371 -573
  6. package/dist/api/jobs/index.d.ts.map +1 -1
  7. package/dist/api/jobs/index.js +605 -1012
  8. package/dist/api/jobs/index.js.map +1 -1
  9. package/dist/api/notifications/index.d.ts +78 -17
  10. package/dist/api/notifications/index.d.ts.map +1 -1
  11. package/dist/api/notifications/index.js +90 -23
  12. package/dist/api/notifications/index.js.map +1 -1
  13. package/dist/api/payments/index.d.ts +2 -1
  14. package/dist/api/payments/index.d.ts.map +1 -1
  15. package/dist/api/payments/index.js +4 -2
  16. package/dist/api/payments/index.js.map +1 -1
  17. package/dist/api/users/index.d.ts +34 -31
  18. package/dist/api/users/index.d.ts.map +1 -1
  19. package/dist/api/users/index.js +13 -7
  20. package/dist/api/users/index.js.map +1 -1
  21. package/dist/api/verifications/index.js +2 -1
  22. package/dist/api/verifications/index.js.map +1 -1
  23. package/dist/cli/core/index.d.ts +8 -34
  24. package/dist/cli/core/index.d.ts.map +1 -1
  25. package/dist/cli/core/index.js +43 -232
  26. package/dist/cli/core/index.js.map +1 -1
  27. package/dist/cli/platform/index.d.ts +36 -11
  28. package/dist/cli/platform/index.d.ts.map +1 -1
  29. package/dist/cli/platform/index.js +93 -27
  30. package/dist/cli/platform/index.js.map +1 -1
  31. package/dist/command/index.d.ts +1 -1
  32. package/dist/core/index.browser.js +6 -0
  33. package/dist/core/index.browser.js.map +1 -1
  34. package/dist/core/index.d.ts +6 -0
  35. package/dist/core/index.d.ts.map +1 -1
  36. package/dist/core/index.js +6 -0
  37. package/dist/core/index.js.map +1 -1
  38. package/dist/core/index.native.js +6 -0
  39. package/dist/core/index.native.js.map +1 -1
  40. package/dist/core/index.workerd.js +6 -0
  41. package/dist/core/index.workerd.js.map +1 -1
  42. package/dist/react/form/index.d.ts +60 -1
  43. package/dist/react/form/index.d.ts.map +1 -1
  44. package/dist/react/form/index.js +86 -1
  45. package/dist/react/form/index.js.map +1 -1
  46. package/dist/react/head/index.browser.js +16 -1
  47. package/dist/react/head/index.browser.js.map +1 -1
  48. package/dist/react/head/index.d.ts +6 -0
  49. package/dist/react/head/index.d.ts.map +1 -1
  50. package/dist/react/head/index.js +16 -1
  51. package/dist/react/head/index.js.map +1 -1
  52. package/dist/react/router/index.browser.js +0 -10
  53. package/dist/react/router/index.browser.js.map +1 -1
  54. package/dist/react/router/index.d.ts +35 -12
  55. package/dist/react/router/index.d.ts.map +1 -1
  56. package/dist/react/router/index.js +0 -10
  57. package/dist/react/router/index.js.map +1 -1
  58. package/dist/react/ui/index.d.ts +124 -0
  59. package/dist/react/ui/index.d.ts.map +1 -0
  60. package/dist/react/ui/index.js +206 -0
  61. package/dist/react/ui/index.js.map +1 -0
  62. package/dist/router/index.d.ts +13 -13
  63. package/dist/router/index.d.ts.map +1 -1
  64. package/dist/router/index.js +45 -32
  65. package/dist/router/index.js.map +1 -1
  66. package/dist/system/index.d.ts.map +1 -1
  67. package/dist/system/index.js +1 -0
  68. package/dist/system/index.js.map +1 -1
  69. package/dist/topic/core/index.js +1 -1
  70. package/dist/topic/core/index.js.map +1 -1
  71. package/package.json +6 -23
  72. package/src/api/files/jobs/FileJobs.ts +2 -1
  73. package/src/api/jobs/__tests__/$job.spec.ts +316 -2867
  74. package/src/api/jobs/controllers/AdminJobController.ts +29 -138
  75. package/src/api/jobs/entities/jobExecutionEntity.ts +27 -19
  76. package/src/api/jobs/index.browser.ts +5 -7
  77. package/src/api/jobs/index.ts +23 -51
  78. package/src/api/jobs/primitives/$job.ts +66 -58
  79. package/src/api/jobs/providers/JobProvider.ts +561 -566
  80. package/src/api/jobs/providers/JobQueueProvider.ts +18 -19
  81. package/src/api/jobs/schemas/jobConfigAtom.ts +20 -23
  82. package/src/api/jobs/schemas/jobExecutionQuerySchema.ts +3 -27
  83. package/src/api/jobs/schemas/jobExecutionResourceSchema.ts +5 -7
  84. package/src/api/jobs/schemas/jobRegistrationSchema.ts +7 -4
  85. package/src/api/jobs/schemas/triggerJobSchema.ts +0 -1
  86. package/src/api/jobs/services/JobService.ts +90 -483
  87. package/src/api/notifications/controllers/AdminNotificationController.ts +19 -12
  88. package/src/api/notifications/index.ts +7 -4
  89. package/src/api/notifications/jobs/NotificationJobs.ts +83 -12
  90. package/src/api/payments/services/PaymentService.ts +4 -2
  91. package/src/api/users/__tests__/UserJobs.spec.ts +10 -49
  92. package/src/api/users/audits/UserAudits.ts +3 -1
  93. package/src/api/users/buckets/UserBuckets.ts +2 -1
  94. package/src/api/users/index.ts +1 -4
  95. package/src/api/users/jobs/UserJobs.ts +5 -4
  96. package/src/api/verifications/jobs/VerificationJobs.ts +2 -1
  97. package/src/cli/core/__tests__/init.spec.ts +1 -1
  98. package/src/cli/core/commands/init.ts +0 -12
  99. package/src/cli/core/services/PackageManagerUtils.ts +2 -9
  100. package/src/cli/core/services/ProjectScaffolder.ts +17 -65
  101. package/src/cli/core/templates/agentMd.ts +2 -8
  102. package/src/cli/core/templates/apiIndexTs.ts +4 -18
  103. package/src/cli/core/templates/mainCss.ts +1 -36
  104. package/src/cli/core/templates/vitestConfigTs.ts +17 -0
  105. package/src/cli/core/templates/webAppRouterTs.ts +2 -85
  106. package/src/cli/platform/__tests__/CloudflareAdapter.spec.ts +22 -71
  107. package/src/cli/platform/adapters/CloudflareAdapter.ts +12 -11
  108. package/src/cli/platform/atoms/platformOptions.ts +9 -0
  109. package/src/cli/platform/schemas/cloudflare.ts +3 -2
  110. package/src/cli/platform/services/CloudflareApi.ts +164 -25
  111. package/src/cli/platform/services/WranglerApi.ts +0 -17
  112. package/src/core/Alepha.ts +9 -0
  113. package/src/react/form/index.ts +2 -0
  114. package/src/react/form/services/parseField.ts +163 -0
  115. package/src/react/form/services/prettyName.ts +19 -0
  116. package/src/react/head/providers/BrowserHeadProvider.ts +31 -10
  117. package/src/react/router/primitives/$page.ts +35 -12
  118. package/src/react/ui/atoms/uiAtom.ts +28 -0
  119. package/src/react/ui/components/ColorScheme.tsx +36 -0
  120. package/src/react/ui/hooks/useColorMode.ts +49 -0
  121. package/src/react/ui/hooks/useSidebarState.ts +26 -0
  122. package/src/react/ui/hooks/useTheme.ts +22 -0
  123. package/src/react/ui/index.ts +35 -0
  124. package/src/react/ui/services/UiPersistence.ts +41 -0
  125. package/src/router/TemplatedPathParser.ts +50 -51
  126. package/src/router/__tests__/RouterProvider.spec.ts +62 -0
  127. package/src/router/__tests__/TemplatedPathParser.spec.ts +18 -0
  128. package/src/router/providers/RouterProvider.ts +10 -5
  129. package/src/system/providers/NodeShellProvider.ts +1 -0
  130. package/src/topic/core/providers/TopicProvider.ts +1 -1
  131. package/dist/api/invitations/index.d.ts +0 -790
  132. package/dist/api/invitations/index.d.ts.map +0 -1
  133. package/dist/api/invitations/index.js +0 -662
  134. package/dist/api/invitations/index.js.map +0 -1
  135. package/dist/api/issues/index.d.ts +0 -810
  136. package/dist/api/issues/index.d.ts.map +0 -1
  137. package/dist/api/issues/index.js +0 -444
  138. package/dist/api/issues/index.js.map +0 -1
  139. package/dist/api/subscriptions/index.d.ts +0 -1692
  140. package/dist/api/subscriptions/index.d.ts.map +0 -1
  141. package/dist/api/subscriptions/index.js +0 -1867
  142. package/dist/api/subscriptions/index.js.map +0 -1
  143. package/dist/api/workflows/index.browser.js +0 -246
  144. package/dist/api/workflows/index.browser.js.map +0 -1
  145. package/dist/api/workflows/index.d.ts +0 -1618
  146. package/dist/api/workflows/index.d.ts.map +0 -1
  147. package/dist/api/workflows/index.js +0 -1495
  148. package/dist/api/workflows/index.js.map +0 -1
  149. package/src/api/invitations/__tests__/InvitationService.spec.ts +0 -439
  150. package/src/api/invitations/controllers/AdminInvitationController.ts +0 -86
  151. package/src/api/invitations/controllers/InvitationController.ts +0 -84
  152. package/src/api/invitations/entities/invitations.ts +0 -33
  153. package/src/api/invitations/index.ts +0 -58
  154. package/src/api/invitations/jobs/InvitationJobs.ts +0 -37
  155. package/src/api/invitations/providers/InvitationProvider.ts +0 -45
  156. package/src/api/invitations/schemas/createInvitationSchema.ts +0 -12
  157. package/src/api/invitations/schemas/invitationConfigAtom.ts +0 -20
  158. package/src/api/invitations/schemas/invitationQuerySchema.ts +0 -15
  159. package/src/api/invitations/schemas/invitationResourceSchema.ts +0 -6
  160. package/src/api/invitations/schemas/invitationWithResourceInfoSchema.ts +0 -22
  161. package/src/api/invitations/schemas/myInvitationsQuerySchema.ts +0 -10
  162. package/src/api/invitations/services/InvitationService.ts +0 -556
  163. package/src/api/issues/__tests__/IssueService.spec.ts +0 -263
  164. package/src/api/issues/controllers/AdminIssueController.ts +0 -149
  165. package/src/api/issues/controllers/IssueController.ts +0 -44
  166. package/src/api/issues/entities/issues.ts +0 -49
  167. package/src/api/issues/index.ts +0 -50
  168. package/src/api/issues/schemas/createIssueSchema.ts +0 -13
  169. package/src/api/issues/schemas/issueConfigAtom.ts +0 -13
  170. package/src/api/issues/schemas/issueQuerySchema.ts +0 -18
  171. package/src/api/issues/schemas/issueResourceSchema.ts +0 -6
  172. package/src/api/issues/schemas/myIssueQuerySchema.ts +0 -10
  173. package/src/api/issues/schemas/updateIssueSchema.ts +0 -13
  174. package/src/api/issues/services/IssueService.ts +0 -264
  175. package/src/api/jobs/__tests__/$job-middleware.spec.ts +0 -126
  176. package/src/api/jobs/__tests__/JobService.spec.ts +0 -31
  177. package/src/api/jobs/entities/jobExecutionLogEntity.ts +0 -13
  178. package/src/api/jobs/schemas/jobActivitySchema.ts +0 -15
  179. package/src/api/jobs/schemas/jobCronInfoSchema.ts +0 -22
  180. package/src/api/jobs/schemas/jobExecutionDetailResourceSchema.ts +0 -20
  181. package/src/api/jobs/schemas/jobFailureSchema.ts +0 -9
  182. package/src/api/jobs/schemas/jobQueueDepthSchema.ts +0 -14
  183. package/src/api/jobs/schemas/jobStatsSchema.ts +0 -14
  184. package/src/api/jobs/services/JobService-tests.ts +0 -157
  185. package/src/api/subscriptions/__tests__/BillingService.spec.ts +0 -218
  186. package/src/api/subscriptions/__tests__/SubscriptionService.spec.ts +0 -278
  187. package/src/api/subscriptions/controllers/AdminSubscriptionController.ts +0 -212
  188. package/src/api/subscriptions/controllers/SubscriptionController.ts +0 -189
  189. package/src/api/subscriptions/entities/subscriptionEvents.ts +0 -54
  190. package/src/api/subscriptions/entities/subscriptions.ts +0 -68
  191. package/src/api/subscriptions/index.ts +0 -133
  192. package/src/api/subscriptions/jobs/SubscriptionJobs.ts +0 -382
  193. package/src/api/subscriptions/middleware/$requireLimit.ts +0 -50
  194. package/src/api/subscriptions/middleware/$requirePlan.ts +0 -49
  195. package/src/api/subscriptions/notifications/SubscriptionNotifications.ts +0 -110
  196. package/src/api/subscriptions/schemas/cancelSubscriptionSchema.ts +0 -8
  197. package/src/api/subscriptions/schemas/changePlanSchema.ts +0 -9
  198. package/src/api/subscriptions/schemas/createSubscriptionSchema.ts +0 -11
  199. package/src/api/subscriptions/schemas/entitlementsSchema.ts +0 -21
  200. package/src/api/subscriptions/schemas/mrrSchema.ts +0 -13
  201. package/src/api/subscriptions/schemas/planDefinitionSchema.ts +0 -71
  202. package/src/api/subscriptions/schemas/planResourceSchema.ts +0 -25
  203. package/src/api/subscriptions/schemas/subscriptionEventResourceSchema.ts +0 -8
  204. package/src/api/subscriptions/schemas/subscriptionQuerySchema.ts +0 -19
  205. package/src/api/subscriptions/schemas/subscriptionResourceSchema.ts +0 -6
  206. package/src/api/subscriptions/schemas/subscriptionSettingsSchema.ts +0 -32
  207. package/src/api/subscriptions/schemas/subscriptionStatsSchema.ts +0 -23
  208. package/src/api/subscriptions/services/BillingService.ts +0 -437
  209. package/src/api/subscriptions/services/SubscriptionConfig.ts +0 -56
  210. package/src/api/subscriptions/services/SubscriptionService.ts +0 -867
  211. package/src/api/subscriptions/services/UsageService.ts +0 -118
  212. package/src/api/workflows/__tests__/$workflow.spec.ts +0 -616
  213. package/src/api/workflows/controllers/AdminWorkflowController.ts +0 -191
  214. package/src/api/workflows/entities/workflowExecutions.ts +0 -74
  215. package/src/api/workflows/entities/workflowStepExecutions.ts +0 -74
  216. package/src/api/workflows/entities/workflowStepLogs.ts +0 -13
  217. package/src/api/workflows/index.browser.ts +0 -22
  218. package/src/api/workflows/index.ts +0 -115
  219. package/src/api/workflows/jobs/WorkflowJobs.ts +0 -77
  220. package/src/api/workflows/primitives/$workflow.ts +0 -202
  221. package/src/api/workflows/providers/WorkflowProvider.ts +0 -1284
  222. package/src/api/workflows/schemas/workflowActivitySchema.ts +0 -15
  223. package/src/api/workflows/schemas/workflowConfigAtom.ts +0 -51
  224. package/src/api/workflows/schemas/workflowExecutionDetailSchema.ts +0 -18
  225. package/src/api/workflows/schemas/workflowExecutionQuerySchema.ts +0 -26
  226. package/src/api/workflows/schemas/workflowExecutionResourceSchema.ts +0 -30
  227. package/src/api/workflows/schemas/workflowRegistrationSchema.ts +0 -26
  228. package/src/api/workflows/schemas/workflowStatsSchema.ts +0 -16
  229. package/src/api/workflows/schemas/workflowStepExecutionResourceSchema.ts +0 -15
  230. package/src/api/workflows/services/WorkflowService.ts +0 -382
  231. package/src/cli/core/templates/apiAppSecurityTs.ts +0 -43
  232. package/src/cli/core/templates/webAdminDashboardTsx.ts +0 -17
@@ -469,8 +469,9 @@ var FileController = class {
469
469
  var FileJobs = class {
470
470
  fileService = $inject(FileService);
471
471
  purgeFiles = $scheduler({
472
+ name: "api:files:purgeFiles",
472
473
  description: "Purge files that are marked for deletion",
473
- cron: "0 0 * * *",
474
+ cron: "0 * * * *",
474
475
  handler: async () => {
475
476
  const files = await this.fileService.findExpiredFiles();
476
477
  await Promise.all(files.map((file) => this.fileService.deleteFile(file.id)));
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/api/files/schemas/storageStatsSchema.ts","../../../src/api/files/entities/files.ts","../../../src/api/files/services/FileService.ts","../../../src/api/files/controllers/AdminFileStatsController.ts","../../../src/api/files/schemas/fileQuerySchema.ts","../../../src/api/files/schemas/fileResourceSchema.ts","../../../src/api/files/controllers/FileController.ts","../../../src/api/files/jobs/FileJobs.ts","../../../src/api/files/index.ts"],"sourcesContent":["import type { Static } from \"alepha\";\nimport { t } from \"alepha\";\n\nexport const bucketStatsSchema = t.object({\n bucket: t.string(),\n totalSize: t.number(),\n fileCount: t.number(),\n});\n\nexport const mimeTypeStatsSchema = t.object({\n mimeType: t.string(),\n fileCount: t.number(),\n});\n\nexport const storageStatsSchema = t.object({\n totalSize: t.number(),\n totalFiles: t.number(),\n byBucket: t.array(bucketStatsSchema),\n byMimeType: t.array(mimeTypeStatsSchema),\n});\n\nexport type BucketStats = Static<typeof bucketStatsSchema>;\nexport type MimeTypeStats = Static<typeof mimeTypeStatsSchema>;\nexport type StorageStats = Static<typeof storageStatsSchema>;\n","import { type Static, t } from \"alepha\";\nimport { $entity, db } from \"alepha/orm\";\n\nexport const files = $entity({\n name: \"files\",\n schema: t.object({\n id: db.primaryKey(t.uuid()),\n version: db.version(),\n createdAt: db.createdAt(),\n updatedAt: db.updatedAt(),\n blobId: t.text(),\n creator: t.optional(t.uuid()),\n creatorRealm: t.optional(t.string()),\n creatorName: t.optional(t.string()),\n bucket: t.text(),\n expirationDate: t.optional(t.datetime()),\n name: t.text(),\n size: t.number(),\n mimeType: t.string(),\n tags: t.optional(t.array(t.text())),\n checksum: t.optional(t.string()),\n }),\n indexes: [\n \"expirationDate\",\n \"bucket\",\n \"creator\",\n \"createdAt\",\n \"mimeType\",\n {\n columns: [\"bucket\", \"createdAt\"],\n },\n ],\n});\n\nexport type FileEntity = Static<typeof files.schema>;\n","import { createHash } from \"node:crypto\";\nimport { $hook, $inject, Alepha, type FileLike } from \"alepha\";\nimport {\n $bucket,\n type BucketPrimitive,\n FileNotFoundError,\n} from \"alepha/bucket\";\nimport {\n type DateTime,\n DateTimeProvider,\n type DurationLike,\n} from \"alepha/datetime\";\nimport { $logger } from \"alepha/logger\";\nimport { $repository, type Page } from \"alepha/orm\";\nimport type { UserAccountToken } from \"alepha/security\";\nimport type { Ok } from \"alepha/server\";\nimport { NotFoundError } from \"alepha/server\";\nimport { type FileEntity, files } from \"../entities/files.ts\";\nimport type { FileQuery } from \"../schemas/fileQuerySchema.ts\";\nimport type { FileResource } from \"../schemas/fileResourceSchema.ts\";\nimport type { StorageStats } from \"../schemas/storageStatsSchema.ts\";\n\nexport class FileService {\n protected readonly alepha = $inject(Alepha);\n protected readonly log = $logger();\n protected readonly dateTimeProvider = $inject(DateTimeProvider);\n protected readonly defaultBucket = $bucket({ name: \"default\" });\n public readonly fileRepository = $repository(files);\n\n protected onUploadFile = $hook({\n on: \"bucket:file:uploaded\",\n handler: async ({ file, bucket, options, id }) => {\n if (options.persist === false) {\n return;\n }\n\n const checksum = await this.calculateChecksum(file);\n\n await this.fileRepository.create({\n blobId: id,\n mimeType: file.type,\n name: file.name,\n size: file.size,\n creator: options.user?.id,\n creatorRealm: options.user?.realm,\n expirationDate: this.getExpirationDate(options.ttl),\n bucket: bucket.name,\n checksum,\n });\n },\n });\n\n protected onDeleteBucketFile = $hook({\n on: \"bucket:file:deleted\",\n handler: async ({ bucket, id }) => {\n await this.fileRepository.deleteMany({\n blobId: { eq: id },\n bucket: { eq: bucket.name },\n });\n },\n });\n\n // -------------------------------------------------------------------------------------------------------------------\n\n /**\n * Calculates SHA-256 checksum of a file.\n *\n * @param file - The file to calculate checksum for\n * @returns Hexadecimal string representation of the SHA-256 hash\n * @protected\n */\n protected async calculateChecksum(file: FileLike): Promise<string> {\n const buffer = await file.arrayBuffer();\n const hash = createHash(\"sha256\");\n hash.update(Buffer.from(buffer));\n return hash.digest(\"hex\");\n }\n\n /**\n * Gets a bucket primitive by name.\n *\n * @param bucketName - The name of the bucket to retrieve (defaults to \"default\")\n * @returns The bucket primitive\n * @throws {NotFoundError} If the bucket is not found\n */\n public bucket(bucketName: string = this.defaultBucket.name): BucketPrimitive {\n const bucket = this.alepha\n .primitives($bucket)\n .find((it) => it.name === bucketName);\n\n if (!bucket) {\n throw new NotFoundError(`Bucket '${bucketName}' not found.`);\n }\n\n return bucket;\n }\n\n // -------------------------------------------------------------------------------------------------------------------\n\n /**\n * Finds files matching the given query criteria with pagination support.\n * Supports filtering by bucket, tags, name, mimeType, creator, and date range.\n *\n * @param q - Query parameters including bucket, tags, name, mimeType, creator, date range, pagination, and sorting\n * @returns Paginated list of file entities\n */\n public async findFiles(q: FileQuery = {}): Promise<Page<FileEntity>> {\n q.sort ??= \"-createdAt\";\n\n const where = this.fileRepository.createQueryWhere();\n\n if (q.bucket) {\n where.bucket = { eq: q.bucket };\n }\n\n if (q.tags) {\n where.tags = { arrayContains: q.tags };\n }\n\n if (q.name) {\n where.name = { ilike: `%${q.name}%` };\n }\n\n if (q.mimeType) {\n where.mimeType = { eq: q.mimeType };\n }\n\n if (q.creator) {\n where.creator = { eq: q.creator };\n }\n\n if (q.createdAfter && q.createdBefore) {\n where.createdAt = {\n gte: q.createdAfter,\n lte: q.createdBefore,\n };\n } else if (q.createdAfter) {\n where.createdAt = { gte: q.createdAfter };\n } else if (q.createdBefore) {\n where.createdAt = { lte: q.createdBefore };\n }\n\n return await this.fileRepository\n .paginate(q, { where }, { count: true })\n .then((page) => {\n return {\n ...page,\n content: page.content.map((it) => this.entityToResource(it)),\n };\n });\n }\n\n /**\n * Finds files that have expired based on their expiration date.\n * Limited to 1000 files per call to prevent memory issues.\n *\n * @returns Array of expired file entities\n */\n public async findExpiredFiles(): Promise<FileEntity[]> {\n return await this.fileRepository.findMany({\n limit: 1000,\n where: {\n expirationDate: { lte: this.dateTimeProvider.nowISOString() },\n },\n });\n }\n\n /**\n * Calculates an expiration date based on a TTL (time to live) duration.\n *\n * @param ttl - Duration like \"1 day\", \"2 hours\", etc.\n * @returns DateTime representation of the expiration date, or undefined if no TTL provided\n * @protected\n */\n protected getExpirationDate(ttl?: DurationLike): string | undefined {\n return ttl\n ? this.dateTimeProvider\n .now()\n .add(this.dateTimeProvider.duration(ttl))\n .toISOString()\n : undefined;\n }\n\n /**\n * Uploads a file to a bucket and creates a database record with metadata.\n * Automatically calculates and stores the file checksum (SHA-256).\n *\n * @param file - The file to upload\n * @param options - Upload options including bucket, expiration, user, and tags\n * @param options.bucket - Target bucket name (defaults to \"default\")\n * @param options.expirationDate - When the file should expire\n * @param options.user - User performing the upload (for audit trail)\n * @param options.tags - Tags to associate with the file\n * @returns The created file entity with all metadata\n * @throws {NotFoundError} If the specified bucket doesn't exist\n */\n public async uploadFile(\n file: FileLike,\n options: {\n expirationDate?: string | DateTime;\n bucket?: string;\n user?: UserAccountToken;\n tags?: string[];\n } = {},\n ): Promise<FileEntity> {\n const bucket = this.bucket(options.bucket);\n\n const checksum = await this.calculateChecksum(file);\n const blobId = await bucket.upload(file, { persist: false });\n\n let expirationDate: string | undefined;\n if (options.expirationDate) {\n expirationDate = this.dateTimeProvider\n .of(options.expirationDate)\n .toISOString();\n } else if (bucket.options.ttl) {\n expirationDate = this.getExpirationDate(bucket.options.ttl);\n }\n\n return await this.fileRepository.create({\n blobId: blobId,\n mimeType: file.type,\n name: file.name,\n size: file.size,\n creator: options.user?.id,\n creatorRealm: options.user?.realm,\n creatorName: options.user?.name,\n expirationDate,\n bucket: bucket.name,\n tags: options.tags,\n checksum,\n });\n }\n\n /**\n * Streams a file from storage by its database ID.\n *\n * @param id - The database ID (UUID) of the file to stream\n * @returns The file object ready for streaming/downloading\n * @throws {NotFoundError} If the file doesn't exist in the database\n * @throws {FileNotFoundError} If the file exists in database but not in storage\n */\n public async streamFile(id: string): Promise<FileLike> {\n const entity = await this.getFileById(id);\n const bucket = this.bucket(entity.bucket);\n\n return await bucket.download(entity.blobId);\n }\n\n /**\n * Updates file metadata (name, tags, expiration date).\n * Does not modify the actual file content in storage.\n *\n * @param id - The database ID (UUID) of the file to update\n * @param data - Partial file data to update\n * @param data.name - New file name\n * @param data.tags - New tags array\n * @param data.expirationDate - New expiration date\n * @returns The updated file entity\n * @throws {NotFoundError} If the file doesn't exist in the database\n */\n public async updateFile(\n id: string,\n data: {\n name?: string;\n tags?: string[];\n expirationDate?: DateTime | string;\n },\n ): Promise<FileEntity> {\n const file = await this.getFileById(id);\n\n const updateData: Partial<FileEntity> = {};\n\n if (data.name !== undefined) {\n updateData.name = data.name;\n }\n\n if (data.tags !== undefined) {\n updateData.tags = data.tags;\n }\n\n if (data.expirationDate !== undefined) {\n updateData.expirationDate = this.dateTimeProvider\n .of(data.expirationDate)\n .toISOString();\n }\n\n return await this.fileRepository.updateById(file.id, updateData);\n }\n\n /**\n * Deletes a file from both storage and database.\n * Handles cases where file is already deleted from storage gracefully.\n * Always ensures database record is removed even if storage deletion fails.\n *\n * @param id - The database ID (UUID) of the file to delete\n * @returns Success response with the deleted file ID\n * @throws {NotFoundError} If the file doesn't exist in the database\n */\n public async deleteFile(id: string): Promise<Ok> {\n const file = await this.getFileById(id);\n const bucket = this.bucket(file.bucket);\n\n // Always delete the database record\n await this.fileRepository.deleteById(file.id);\n\n try {\n await bucket.delete(file.blobId, true);\n } catch (e) {\n if (e instanceof FileNotFoundError) {\n // File is already deleted in the bucket, this is okay\n this.log.debug(\n `File ${file.blobId} not found in bucket ${bucket.name}, cleaning up database record`,\n );\n } else {\n // Other errors (permission, network, etc.) - log but continue to clean up database\n this.log.warn(\n `Failed to delete file ${file.blobId} from bucket ${bucket.name}`,\n e,\n );\n }\n }\n\n return { ok: true, id: String(file.id) };\n }\n\n /**\n * Retrieves a file entity by its ID.\n * If already an entity object, returns it as-is (convenience method).\n *\n * @param id - Either a UUID string or an existing FileEntity object\n * @returns The file entity\n * @throws {NotFoundError} If the file doesn't exist in the database\n */\n public async getFileById(id: string | FileEntity): Promise<FileEntity> {\n if (typeof id === \"object\") {\n return id;\n }\n\n return await this.fileRepository.getById(id);\n }\n\n /**\n * Gets storage statistics including total size, file count, and breakdowns by bucket and MIME type.\n *\n * @returns Storage statistics with aggregated data\n */\n public async getStorageStats(): Promise<StorageStats> {\n const allFiles = await this.fileRepository.findMany({});\n\n const totalSize = allFiles.reduce((sum, file) => sum + file.size, 0);\n const totalFiles = allFiles.length;\n\n // Group by bucket\n const bucketMap = new Map<\n string,\n { totalSize: number; fileCount: number }\n >();\n for (const file of allFiles) {\n const existing = bucketMap.get(file.bucket) || {\n totalSize: 0,\n fileCount: 0,\n };\n existing.totalSize += file.size;\n existing.fileCount += 1;\n bucketMap.set(file.bucket, existing);\n }\n\n // Group by MIME type\n const mimeTypeMap = new Map<string, number>();\n for (const file of allFiles) {\n const existing = mimeTypeMap.get(file.mimeType) || 0;\n mimeTypeMap.set(file.mimeType, existing + 1);\n }\n\n return {\n totalSize,\n totalFiles,\n byBucket: Array.from(bucketMap.entries()).map(([bucket, stats]) => ({\n bucket,\n totalSize: stats.totalSize,\n fileCount: stats.fileCount,\n })),\n byMimeType: Array.from(mimeTypeMap.entries()).map(\n ([mimeType, fileCount]) => ({\n mimeType,\n fileCount,\n }),\n ),\n };\n }\n\n /**\n * Converts a file entity to a file resource (API response format).\n * Currently a pass-through, but allows for future transformation logic.\n *\n * @param entity - The file entity to convert\n * @returns The file resource for API responses\n */\n public entityToResource(entity: FileEntity): FileResource {\n return entity;\n }\n}\n","import { $inject } from \"alepha\";\nimport { $secure } from \"alepha/security\";\nimport { $action } from \"alepha/server\";\nimport { storageStatsSchema } from \"../schemas/storageStatsSchema.ts\";\nimport { FileService } from \"../services/FileService.ts\";\n\n/**\n * REST API controller for storage analytics and statistics.\n * Provides endpoints for viewing storage usage metrics.\n */\nexport class AdminFileStatsController {\n protected readonly url = \"/files/stats\";\n protected readonly group = \"admin:files\";\n protected readonly fileService = $inject(FileService);\n\n /**\n * GET /files/stats - Gets storage statistics.\n * Returns aggregated data including total size, file count,\n * and breakdowns by bucket and MIME type.\n */\n public readonly getFileStats = $action({\n path: this.url,\n group: this.group,\n use: [$secure({ permissions: [\"admin:file:read\"] })],\n description: \"Get storage statistics\",\n schema: {\n response: storageStatsSchema,\n },\n handler: () => this.fileService.getStorageStats(),\n });\n}\n","import type { Static } from \"alepha\";\nimport { t } from \"alepha\";\nimport { pageQuerySchema } from \"alepha/orm\";\n\nexport const fileQuerySchema = t.extend(pageQuerySchema, {\n bucket: t.optional(t.string()),\n tags: t.optional(t.array(t.string())),\n name: t.optional(t.string()),\n mimeType: t.optional(t.string()),\n creator: t.optional(t.uuid()),\n createdAfter: t.optional(t.datetime()),\n createdBefore: t.optional(t.datetime()),\n});\n\nexport type FileQuery = Static<typeof fileQuerySchema>;\n","import { type Static, t } from \"alepha\";\nimport { files } from \"../entities/files.ts\";\n\nexport const fileResourceSchema = t.extend(\n files.schema,\n {},\n {\n title: \"FileResource\",\n description: \"A file resource representing a file stored in the system.\",\n },\n);\n\nexport type FileResource = Static<typeof fileResourceSchema>;\n","import { $inject, t } from \"alepha\";\nimport { $secure } from \"alepha/security\";\nimport { $action, okSchema } from \"alepha/server\";\nimport { $etag } from \"alepha/server/etag\";\nimport { fileQuerySchema } from \"../schemas/fileQuerySchema.ts\";\nimport { fileResourceSchema } from \"../schemas/fileResourceSchema.ts\";\nimport { FileService } from \"../services/FileService.ts\";\n\n/**\n * REST API controller for file management operations.\n * Provides endpoints for uploading, downloading, listing, and deleting files.\n */\nexport class FileController {\n protected readonly url = \"/files\";\n protected readonly group = \"files\";\n protected readonly fileService = $inject(FileService);\n\n /**\n * GET /files - Lists files with optional filtering and pagination.\n * Supports filtering by bucket and tags.\n */\n public readonly findFiles = $action({\n path: this.url,\n group: `admin:${this.group}`,\n use: [$secure({ permissions: [\"admin:file:read\"] })],\n description: \"List files with filtering and pagination\",\n schema: {\n query: fileQuerySchema,\n response: t.page(fileResourceSchema),\n },\n handler: ({ query }) => this.fileService.findFiles(query),\n });\n\n /**\n * DELETE /files/:id - Deletes a file from both storage and database.\n * Removes the file from the bucket and cleans up the database record.\n */\n public readonly deleteFile = $action({\n method: \"DELETE\",\n path: `${this.url}/:id`,\n group: `admin:${this.group}`,\n use: [$secure({ permissions: [\"admin:file:delete\"] })],\n description: \"Delete a file\",\n schema: {\n params: t.object({\n id: t.uuid(),\n }),\n response: okSchema,\n },\n handler: ({ params }) => this.fileService.deleteFile(params.id),\n });\n\n /**\n * POST /files - Uploads a new file to storage.\n * Creates a database record with metadata and calculates checksum.\n * Optionally specify bucket and expiration date.\n */\n public readonly uploadFile = $action({\n path: this.url,\n group: this.group,\n use: [$secure({ permissions: [\"file:create\"] })],\n description: \"Upload a new file\",\n schema: {\n body: t.object({\n file: t.file(),\n }),\n query: t.object({\n expirationDate: t.optional(t.datetime()),\n bucket: t.optional(t.string()),\n }),\n response: fileResourceSchema,\n },\n handler: async ({ body, user, query }) =>\n this.fileService.uploadFile(body.file, {\n user,\n ...query,\n }),\n });\n\n /**\n * PATCH /files/:id - Updates file metadata.\n * Allows updating name, tags, and expiration date without modifying file content.\n */\n public readonly updateFile = $action({\n method: \"PATCH\",\n path: `${this.url}/:id`,\n group: `admin:${this.group}`,\n use: [$secure({ permissions: [\"admin:file:update\"] })],\n description: \"Update file metadata\",\n schema: {\n params: t.object({\n id: t.uuid(),\n }),\n body: t.object({\n name: t.optional(t.string()),\n tags: t.optional(t.array(t.string())),\n expirationDate: t.optional(t.datetime()),\n }),\n response: fileResourceSchema,\n },\n handler: ({ params, body }) => this.fileService.updateFile(params.id, body),\n });\n\n /**\n * GET /files/:id - Streams/downloads a file by its ID.\n * Returns the file content with appropriate Content-Type header.\n * Cached with ETag support for 1 year (immutable).\n */\n public readonly streamFile = $action({\n path: `${this.url}/:id`,\n group: this.group,\n description: \"Download a file\",\n use: [\n $secure({ permissions: [\"file:read\"] }),\n $etag({\n control: {\n public: true,\n maxAge: [1, \"year\"],\n immutable: true,\n },\n }),\n ],\n schema: {\n params: t.object({\n id: t.uuid(),\n }),\n response: t.file(),\n },\n handler: async ({ params }) => {\n return await this.fileService.streamFile(params.id);\n },\n });\n}\n","import { $inject } from \"alepha\";\nimport { $scheduler } from \"alepha/scheduler\";\nimport { FileService } from \"../services/FileService.ts\";\n\nexport class FileJobs {\n protected readonly fileService = $inject(FileService);\n\n public readonly purgeFiles = $scheduler({\n description: \"Purge files that are marked for deletion\",\n cron: \"0 0 * * *\", // Every day at midnight\n handler: async () => {\n const files = await this.fileService.findExpiredFiles();\n\n await Promise.all(\n files.map((file) => this.fileService.deleteFile(file.id)),\n );\n },\n });\n}\n","import { $module } from \"alepha\";\nimport { AlephaBucket } from \"alepha/bucket\";\nimport type { DurationLike } from \"alepha/datetime\";\nimport type { UserAccountToken } from \"alepha/security\";\nimport { AlephaServerEtag } from \"alepha/server/etag\";\nimport { AdminFileStatsController } from \"./controllers/AdminFileStatsController.ts\";\nimport { FileController } from \"./controllers/FileController.ts\";\nimport { FileJobs } from \"./jobs/FileJobs.ts\";\nimport { FileService } from \"./services/FileService.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./controllers/AdminFileStatsController.ts\";\nexport * from \"./controllers/FileController.ts\";\nexport * from \"./entities/files.ts\";\nexport * from \"./jobs/FileJobs.ts\";\nexport * from \"./schemas/storageStatsSchema.ts\";\nexport * from \"./services/FileService.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\ndeclare module \"alepha/bucket\" {\n interface BucketFileOptions {\n /**\n * Time to live for the files in the bucket.\n */\n ttl?: DurationLike;\n\n /**\n * Tags for the bucket.\n */\n tags?: string[];\n\n /**\n * User performing the operation.\n */\n user?: UserAccountToken;\n\n /**\n * Whether to persist the file metadata in the database.\n *\n * @default true\n */\n persist?: boolean;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * File management endpoints.\n *\n * **Features:**\n * - Upload/download endpoints\n * - File metadata storage\n * - TTL-based expiration\n * - Storage statistics\n *\n * @module alepha.api.files\n */\nexport const AlephaApiFiles = $module({\n name: \"alepha.api.files\",\n services: [FileController, AdminFileStatsController, FileJobs, FileService],\n imports: [AlephaBucket, AlephaServerEtag],\n});\n"],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AAE,MAAM,EACb,CAAC;GACF,UAAU,EAAE,MAAM;GACnB;EACD,SAAS,OAAO,EAAE,aAAa;AAC7B,UAAO,MAAM,KAAK,YAAY,WAAW,OAAO,GAAG;;EAEtD,CAAC;;;;AC/HJ,IAAa,WAAb,MAAsB;CACpB,cAAiC,QAAQ,YAAY;CAErD,aAA6B,WAAW;EACtC,aAAa;EACb,MAAM;EACN,SAAS,YAAY;GACnB,MAAM,QAAQ,MAAM,KAAK,YAAY,kBAAkB;AAEvD,SAAM,QAAQ,IACZ,MAAM,KAAK,SAAS,KAAK,YAAY,WAAW,KAAK,GAAG,CAAC,CAC1D;;EAEJ,CAAC;;;;;;;;;;;;;;;AC2CJ,MAAa,iBAAiB,QAAQ;CACpC,MAAM;CACN,UAAU;EAAC;EAAgB;EAA0B;EAAU;EAAY;CAC3E,SAAS,CAAC,cAAc,iBAAiB;CAC1C,CAAC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/api/files/schemas/storageStatsSchema.ts","../../../src/api/files/entities/files.ts","../../../src/api/files/services/FileService.ts","../../../src/api/files/controllers/AdminFileStatsController.ts","../../../src/api/files/schemas/fileQuerySchema.ts","../../../src/api/files/schemas/fileResourceSchema.ts","../../../src/api/files/controllers/FileController.ts","../../../src/api/files/jobs/FileJobs.ts","../../../src/api/files/index.ts"],"sourcesContent":["import type { Static } from \"alepha\";\nimport { t } from \"alepha\";\n\nexport const bucketStatsSchema = t.object({\n bucket: t.string(),\n totalSize: t.number(),\n fileCount: t.number(),\n});\n\nexport const mimeTypeStatsSchema = t.object({\n mimeType: t.string(),\n fileCount: t.number(),\n});\n\nexport const storageStatsSchema = t.object({\n totalSize: t.number(),\n totalFiles: t.number(),\n byBucket: t.array(bucketStatsSchema),\n byMimeType: t.array(mimeTypeStatsSchema),\n});\n\nexport type BucketStats = Static<typeof bucketStatsSchema>;\nexport type MimeTypeStats = Static<typeof mimeTypeStatsSchema>;\nexport type StorageStats = Static<typeof storageStatsSchema>;\n","import { type Static, t } from \"alepha\";\nimport { $entity, db } from \"alepha/orm\";\n\nexport const files = $entity({\n name: \"files\",\n schema: t.object({\n id: db.primaryKey(t.uuid()),\n version: db.version(),\n createdAt: db.createdAt(),\n updatedAt: db.updatedAt(),\n blobId: t.text(),\n creator: t.optional(t.uuid()),\n creatorRealm: t.optional(t.string()),\n creatorName: t.optional(t.string()),\n bucket: t.text(),\n expirationDate: t.optional(t.datetime()),\n name: t.text(),\n size: t.number(),\n mimeType: t.string(),\n tags: t.optional(t.array(t.text())),\n checksum: t.optional(t.string()),\n }),\n indexes: [\n \"expirationDate\",\n \"bucket\",\n \"creator\",\n \"createdAt\",\n \"mimeType\",\n {\n columns: [\"bucket\", \"createdAt\"],\n },\n ],\n});\n\nexport type FileEntity = Static<typeof files.schema>;\n","import { createHash } from \"node:crypto\";\nimport { $hook, $inject, Alepha, type FileLike } from \"alepha\";\nimport {\n $bucket,\n type BucketPrimitive,\n FileNotFoundError,\n} from \"alepha/bucket\";\nimport {\n type DateTime,\n DateTimeProvider,\n type DurationLike,\n} from \"alepha/datetime\";\nimport { $logger } from \"alepha/logger\";\nimport { $repository, type Page } from \"alepha/orm\";\nimport type { UserAccountToken } from \"alepha/security\";\nimport type { Ok } from \"alepha/server\";\nimport { NotFoundError } from \"alepha/server\";\nimport { type FileEntity, files } from \"../entities/files.ts\";\nimport type { FileQuery } from \"../schemas/fileQuerySchema.ts\";\nimport type { FileResource } from \"../schemas/fileResourceSchema.ts\";\nimport type { StorageStats } from \"../schemas/storageStatsSchema.ts\";\n\nexport class FileService {\n protected readonly alepha = $inject(Alepha);\n protected readonly log = $logger();\n protected readonly dateTimeProvider = $inject(DateTimeProvider);\n protected readonly defaultBucket = $bucket({ name: \"default\" });\n public readonly fileRepository = $repository(files);\n\n protected onUploadFile = $hook({\n on: \"bucket:file:uploaded\",\n handler: async ({ file, bucket, options, id }) => {\n if (options.persist === false) {\n return;\n }\n\n const checksum = await this.calculateChecksum(file);\n\n await this.fileRepository.create({\n blobId: id,\n mimeType: file.type,\n name: file.name,\n size: file.size,\n creator: options.user?.id,\n creatorRealm: options.user?.realm,\n expirationDate: this.getExpirationDate(options.ttl),\n bucket: bucket.name,\n checksum,\n });\n },\n });\n\n protected onDeleteBucketFile = $hook({\n on: \"bucket:file:deleted\",\n handler: async ({ bucket, id }) => {\n await this.fileRepository.deleteMany({\n blobId: { eq: id },\n bucket: { eq: bucket.name },\n });\n },\n });\n\n // -------------------------------------------------------------------------------------------------------------------\n\n /**\n * Calculates SHA-256 checksum of a file.\n *\n * @param file - The file to calculate checksum for\n * @returns Hexadecimal string representation of the SHA-256 hash\n * @protected\n */\n protected async calculateChecksum(file: FileLike): Promise<string> {\n const buffer = await file.arrayBuffer();\n const hash = createHash(\"sha256\");\n hash.update(Buffer.from(buffer));\n return hash.digest(\"hex\");\n }\n\n /**\n * Gets a bucket primitive by name.\n *\n * @param bucketName - The name of the bucket to retrieve (defaults to \"default\")\n * @returns The bucket primitive\n * @throws {NotFoundError} If the bucket is not found\n */\n public bucket(bucketName: string = this.defaultBucket.name): BucketPrimitive {\n const bucket = this.alepha\n .primitives($bucket)\n .find((it) => it.name === bucketName);\n\n if (!bucket) {\n throw new NotFoundError(`Bucket '${bucketName}' not found.`);\n }\n\n return bucket;\n }\n\n // -------------------------------------------------------------------------------------------------------------------\n\n /**\n * Finds files matching the given query criteria with pagination support.\n * Supports filtering by bucket, tags, name, mimeType, creator, and date range.\n *\n * @param q - Query parameters including bucket, tags, name, mimeType, creator, date range, pagination, and sorting\n * @returns Paginated list of file entities\n */\n public async findFiles(q: FileQuery = {}): Promise<Page<FileEntity>> {\n q.sort ??= \"-createdAt\";\n\n const where = this.fileRepository.createQueryWhere();\n\n if (q.bucket) {\n where.bucket = { eq: q.bucket };\n }\n\n if (q.tags) {\n where.tags = { arrayContains: q.tags };\n }\n\n if (q.name) {\n where.name = { ilike: `%${q.name}%` };\n }\n\n if (q.mimeType) {\n where.mimeType = { eq: q.mimeType };\n }\n\n if (q.creator) {\n where.creator = { eq: q.creator };\n }\n\n if (q.createdAfter && q.createdBefore) {\n where.createdAt = {\n gte: q.createdAfter,\n lte: q.createdBefore,\n };\n } else if (q.createdAfter) {\n where.createdAt = { gte: q.createdAfter };\n } else if (q.createdBefore) {\n where.createdAt = { lte: q.createdBefore };\n }\n\n return await this.fileRepository\n .paginate(q, { where }, { count: true })\n .then((page) => {\n return {\n ...page,\n content: page.content.map((it) => this.entityToResource(it)),\n };\n });\n }\n\n /**\n * Finds files that have expired based on their expiration date.\n * Limited to 1000 files per call to prevent memory issues.\n *\n * @returns Array of expired file entities\n */\n public async findExpiredFiles(): Promise<FileEntity[]> {\n return await this.fileRepository.findMany({\n limit: 1000,\n where: {\n expirationDate: { lte: this.dateTimeProvider.nowISOString() },\n },\n });\n }\n\n /**\n * Calculates an expiration date based on a TTL (time to live) duration.\n *\n * @param ttl - Duration like \"1 day\", \"2 hours\", etc.\n * @returns DateTime representation of the expiration date, or undefined if no TTL provided\n * @protected\n */\n protected getExpirationDate(ttl?: DurationLike): string | undefined {\n return ttl\n ? this.dateTimeProvider\n .now()\n .add(this.dateTimeProvider.duration(ttl))\n .toISOString()\n : undefined;\n }\n\n /**\n * Uploads a file to a bucket and creates a database record with metadata.\n * Automatically calculates and stores the file checksum (SHA-256).\n *\n * @param file - The file to upload\n * @param options - Upload options including bucket, expiration, user, and tags\n * @param options.bucket - Target bucket name (defaults to \"default\")\n * @param options.expirationDate - When the file should expire\n * @param options.user - User performing the upload (for audit trail)\n * @param options.tags - Tags to associate with the file\n * @returns The created file entity with all metadata\n * @throws {NotFoundError} If the specified bucket doesn't exist\n */\n public async uploadFile(\n file: FileLike,\n options: {\n expirationDate?: string | DateTime;\n bucket?: string;\n user?: UserAccountToken;\n tags?: string[];\n } = {},\n ): Promise<FileEntity> {\n const bucket = this.bucket(options.bucket);\n\n const checksum = await this.calculateChecksum(file);\n const blobId = await bucket.upload(file, { persist: false });\n\n let expirationDate: string | undefined;\n if (options.expirationDate) {\n expirationDate = this.dateTimeProvider\n .of(options.expirationDate)\n .toISOString();\n } else if (bucket.options.ttl) {\n expirationDate = this.getExpirationDate(bucket.options.ttl);\n }\n\n return await this.fileRepository.create({\n blobId: blobId,\n mimeType: file.type,\n name: file.name,\n size: file.size,\n creator: options.user?.id,\n creatorRealm: options.user?.realm,\n creatorName: options.user?.name,\n expirationDate,\n bucket: bucket.name,\n tags: options.tags,\n checksum,\n });\n }\n\n /**\n * Streams a file from storage by its database ID.\n *\n * @param id - The database ID (UUID) of the file to stream\n * @returns The file object ready for streaming/downloading\n * @throws {NotFoundError} If the file doesn't exist in the database\n * @throws {FileNotFoundError} If the file exists in database but not in storage\n */\n public async streamFile(id: string): Promise<FileLike> {\n const entity = await this.getFileById(id);\n const bucket = this.bucket(entity.bucket);\n\n return await bucket.download(entity.blobId);\n }\n\n /**\n * Updates file metadata (name, tags, expiration date).\n * Does not modify the actual file content in storage.\n *\n * @param id - The database ID (UUID) of the file to update\n * @param data - Partial file data to update\n * @param data.name - New file name\n * @param data.tags - New tags array\n * @param data.expirationDate - New expiration date\n * @returns The updated file entity\n * @throws {NotFoundError} If the file doesn't exist in the database\n */\n public async updateFile(\n id: string,\n data: {\n name?: string;\n tags?: string[];\n expirationDate?: DateTime | string;\n },\n ): Promise<FileEntity> {\n const file = await this.getFileById(id);\n\n const updateData: Partial<FileEntity> = {};\n\n if (data.name !== undefined) {\n updateData.name = data.name;\n }\n\n if (data.tags !== undefined) {\n updateData.tags = data.tags;\n }\n\n if (data.expirationDate !== undefined) {\n updateData.expirationDate = this.dateTimeProvider\n .of(data.expirationDate)\n .toISOString();\n }\n\n return await this.fileRepository.updateById(file.id, updateData);\n }\n\n /**\n * Deletes a file from both storage and database.\n * Handles cases where file is already deleted from storage gracefully.\n * Always ensures database record is removed even if storage deletion fails.\n *\n * @param id - The database ID (UUID) of the file to delete\n * @returns Success response with the deleted file ID\n * @throws {NotFoundError} If the file doesn't exist in the database\n */\n public async deleteFile(id: string): Promise<Ok> {\n const file = await this.getFileById(id);\n const bucket = this.bucket(file.bucket);\n\n // Always delete the database record\n await this.fileRepository.deleteById(file.id);\n\n try {\n await bucket.delete(file.blobId, true);\n } catch (e) {\n if (e instanceof FileNotFoundError) {\n // File is already deleted in the bucket, this is okay\n this.log.debug(\n `File ${file.blobId} not found in bucket ${bucket.name}, cleaning up database record`,\n );\n } else {\n // Other errors (permission, network, etc.) - log but continue to clean up database\n this.log.warn(\n `Failed to delete file ${file.blobId} from bucket ${bucket.name}`,\n e,\n );\n }\n }\n\n return { ok: true, id: String(file.id) };\n }\n\n /**\n * Retrieves a file entity by its ID.\n * If already an entity object, returns it as-is (convenience method).\n *\n * @param id - Either a UUID string or an existing FileEntity object\n * @returns The file entity\n * @throws {NotFoundError} If the file doesn't exist in the database\n */\n public async getFileById(id: string | FileEntity): Promise<FileEntity> {\n if (typeof id === \"object\") {\n return id;\n }\n\n return await this.fileRepository.getById(id);\n }\n\n /**\n * Gets storage statistics including total size, file count, and breakdowns by bucket and MIME type.\n *\n * @returns Storage statistics with aggregated data\n */\n public async getStorageStats(): Promise<StorageStats> {\n const allFiles = await this.fileRepository.findMany({});\n\n const totalSize = allFiles.reduce((sum, file) => sum + file.size, 0);\n const totalFiles = allFiles.length;\n\n // Group by bucket\n const bucketMap = new Map<\n string,\n { totalSize: number; fileCount: number }\n >();\n for (const file of allFiles) {\n const existing = bucketMap.get(file.bucket) || {\n totalSize: 0,\n fileCount: 0,\n };\n existing.totalSize += file.size;\n existing.fileCount += 1;\n bucketMap.set(file.bucket, existing);\n }\n\n // Group by MIME type\n const mimeTypeMap = new Map<string, number>();\n for (const file of allFiles) {\n const existing = mimeTypeMap.get(file.mimeType) || 0;\n mimeTypeMap.set(file.mimeType, existing + 1);\n }\n\n return {\n totalSize,\n totalFiles,\n byBucket: Array.from(bucketMap.entries()).map(([bucket, stats]) => ({\n bucket,\n totalSize: stats.totalSize,\n fileCount: stats.fileCount,\n })),\n byMimeType: Array.from(mimeTypeMap.entries()).map(\n ([mimeType, fileCount]) => ({\n mimeType,\n fileCount,\n }),\n ),\n };\n }\n\n /**\n * Converts a file entity to a file resource (API response format).\n * Currently a pass-through, but allows for future transformation logic.\n *\n * @param entity - The file entity to convert\n * @returns The file resource for API responses\n */\n public entityToResource(entity: FileEntity): FileResource {\n return entity;\n }\n}\n","import { $inject } from \"alepha\";\nimport { $secure } from \"alepha/security\";\nimport { $action } from \"alepha/server\";\nimport { storageStatsSchema } from \"../schemas/storageStatsSchema.ts\";\nimport { FileService } from \"../services/FileService.ts\";\n\n/**\n * REST API controller for storage analytics and statistics.\n * Provides endpoints for viewing storage usage metrics.\n */\nexport class AdminFileStatsController {\n protected readonly url = \"/files/stats\";\n protected readonly group = \"admin:files\";\n protected readonly fileService = $inject(FileService);\n\n /**\n * GET /files/stats - Gets storage statistics.\n * Returns aggregated data including total size, file count,\n * and breakdowns by bucket and MIME type.\n */\n public readonly getFileStats = $action({\n path: this.url,\n group: this.group,\n use: [$secure({ permissions: [\"admin:file:read\"] })],\n description: \"Get storage statistics\",\n schema: {\n response: storageStatsSchema,\n },\n handler: () => this.fileService.getStorageStats(),\n });\n}\n","import type { Static } from \"alepha\";\nimport { t } from \"alepha\";\nimport { pageQuerySchema } from \"alepha/orm\";\n\nexport const fileQuerySchema = t.extend(pageQuerySchema, {\n bucket: t.optional(t.string()),\n tags: t.optional(t.array(t.string())),\n name: t.optional(t.string()),\n mimeType: t.optional(t.string()),\n creator: t.optional(t.uuid()),\n createdAfter: t.optional(t.datetime()),\n createdBefore: t.optional(t.datetime()),\n});\n\nexport type FileQuery = Static<typeof fileQuerySchema>;\n","import { type Static, t } from \"alepha\";\nimport { files } from \"../entities/files.ts\";\n\nexport const fileResourceSchema = t.extend(\n files.schema,\n {},\n {\n title: \"FileResource\",\n description: \"A file resource representing a file stored in the system.\",\n },\n);\n\nexport type FileResource = Static<typeof fileResourceSchema>;\n","import { $inject, t } from \"alepha\";\nimport { $secure } from \"alepha/security\";\nimport { $action, okSchema } from \"alepha/server\";\nimport { $etag } from \"alepha/server/etag\";\nimport { fileQuerySchema } from \"../schemas/fileQuerySchema.ts\";\nimport { fileResourceSchema } from \"../schemas/fileResourceSchema.ts\";\nimport { FileService } from \"../services/FileService.ts\";\n\n/**\n * REST API controller for file management operations.\n * Provides endpoints for uploading, downloading, listing, and deleting files.\n */\nexport class FileController {\n protected readonly url = \"/files\";\n protected readonly group = \"files\";\n protected readonly fileService = $inject(FileService);\n\n /**\n * GET /files - Lists files with optional filtering and pagination.\n * Supports filtering by bucket and tags.\n */\n public readonly findFiles = $action({\n path: this.url,\n group: `admin:${this.group}`,\n use: [$secure({ permissions: [\"admin:file:read\"] })],\n description: \"List files with filtering and pagination\",\n schema: {\n query: fileQuerySchema,\n response: t.page(fileResourceSchema),\n },\n handler: ({ query }) => this.fileService.findFiles(query),\n });\n\n /**\n * DELETE /files/:id - Deletes a file from both storage and database.\n * Removes the file from the bucket and cleans up the database record.\n */\n public readonly deleteFile = $action({\n method: \"DELETE\",\n path: `${this.url}/:id`,\n group: `admin:${this.group}`,\n use: [$secure({ permissions: [\"admin:file:delete\"] })],\n description: \"Delete a file\",\n schema: {\n params: t.object({\n id: t.uuid(),\n }),\n response: okSchema,\n },\n handler: ({ params }) => this.fileService.deleteFile(params.id),\n });\n\n /**\n * POST /files - Uploads a new file to storage.\n * Creates a database record with metadata and calculates checksum.\n * Optionally specify bucket and expiration date.\n */\n public readonly uploadFile = $action({\n path: this.url,\n group: this.group,\n use: [$secure({ permissions: [\"file:create\"] })],\n description: \"Upload a new file\",\n schema: {\n body: t.object({\n file: t.file(),\n }),\n query: t.object({\n expirationDate: t.optional(t.datetime()),\n bucket: t.optional(t.string()),\n }),\n response: fileResourceSchema,\n },\n handler: async ({ body, user, query }) =>\n this.fileService.uploadFile(body.file, {\n user,\n ...query,\n }),\n });\n\n /**\n * PATCH /files/:id - Updates file metadata.\n * Allows updating name, tags, and expiration date without modifying file content.\n */\n public readonly updateFile = $action({\n method: \"PATCH\",\n path: `${this.url}/:id`,\n group: `admin:${this.group}`,\n use: [$secure({ permissions: [\"admin:file:update\"] })],\n description: \"Update file metadata\",\n schema: {\n params: t.object({\n id: t.uuid(),\n }),\n body: t.object({\n name: t.optional(t.string()),\n tags: t.optional(t.array(t.string())),\n expirationDate: t.optional(t.datetime()),\n }),\n response: fileResourceSchema,\n },\n handler: ({ params, body }) => this.fileService.updateFile(params.id, body),\n });\n\n /**\n * GET /files/:id - Streams/downloads a file by its ID.\n * Returns the file content with appropriate Content-Type header.\n * Cached with ETag support for 1 year (immutable).\n */\n public readonly streamFile = $action({\n path: `${this.url}/:id`,\n group: this.group,\n description: \"Download a file\",\n use: [\n $secure({ permissions: [\"file:read\"] }),\n $etag({\n control: {\n public: true,\n maxAge: [1, \"year\"],\n immutable: true,\n },\n }),\n ],\n schema: {\n params: t.object({\n id: t.uuid(),\n }),\n response: t.file(),\n },\n handler: async ({ params }) => {\n return await this.fileService.streamFile(params.id);\n },\n });\n}\n","import { $inject } from \"alepha\";\nimport { $scheduler } from \"alepha/scheduler\";\nimport { FileService } from \"../services/FileService.ts\";\n\nexport class FileJobs {\n protected readonly fileService = $inject(FileService);\n\n public readonly purgeFiles = $scheduler({\n name: \"api:files:purgeFiles\",\n description: \"Purge files that are marked for deletion\",\n cron: \"0 * * * *\", // Hourly at minute 0\n handler: async () => {\n const files = await this.fileService.findExpiredFiles();\n\n await Promise.all(\n files.map((file) => this.fileService.deleteFile(file.id)),\n );\n },\n });\n}\n","import { $module } from \"alepha\";\nimport { AlephaBucket } from \"alepha/bucket\";\nimport type { DurationLike } from \"alepha/datetime\";\nimport type { UserAccountToken } from \"alepha/security\";\nimport { AlephaServerEtag } from \"alepha/server/etag\";\nimport { AdminFileStatsController } from \"./controllers/AdminFileStatsController.ts\";\nimport { FileController } from \"./controllers/FileController.ts\";\nimport { FileJobs } from \"./jobs/FileJobs.ts\";\nimport { FileService } from \"./services/FileService.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./controllers/AdminFileStatsController.ts\";\nexport * from \"./controllers/FileController.ts\";\nexport * from \"./entities/files.ts\";\nexport * from \"./jobs/FileJobs.ts\";\nexport * from \"./schemas/storageStatsSchema.ts\";\nexport * from \"./services/FileService.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\ndeclare module \"alepha/bucket\" {\n interface BucketFileOptions {\n /**\n * Time to live for the files in the bucket.\n */\n ttl?: DurationLike;\n\n /**\n * Tags for the bucket.\n */\n tags?: string[];\n\n /**\n * User performing the operation.\n */\n user?: UserAccountToken;\n\n /**\n * Whether to persist the file metadata in the database.\n *\n * @default true\n */\n persist?: boolean;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * File management endpoints.\n *\n * **Features:**\n * - Upload/download endpoints\n * - File metadata storage\n * - TTL-based expiration\n * - Storage statistics\n *\n * @module alepha.api.files\n */\nexport const AlephaApiFiles = $module({\n name: \"alepha.api.files\",\n services: [FileController, AdminFileStatsController, FileJobs, FileService],\n imports: [AlephaBucket, AlephaServerEtag],\n});\n"],"mappings":";;;;;;;;;;;AAGA,MAAa,oBAAoB,EAAE,OAAO;CACxC,QAAQ,EAAE,QAAQ;CAClB,WAAW,EAAE,QAAQ;CACrB,WAAW,EAAE,QAAQ;CACtB,CAAC;AAEF,MAAa,sBAAsB,EAAE,OAAO;CAC1C,UAAU,EAAE,QAAQ;CACpB,WAAW,EAAE,QAAQ;CACtB,CAAC;AAEF,MAAa,qBAAqB,EAAE,OAAO;CACzC,WAAW,EAAE,QAAQ;CACrB,YAAY,EAAE,QAAQ;CACtB,UAAU,EAAE,MAAM,kBAAkB;CACpC,YAAY,EAAE,MAAM,oBAAoB;CACzC,CAAC;;;AChBF,MAAa,QAAQ,QAAQ;CAC3B,MAAM;CACN,QAAQ,EAAE,OAAO;EACf,IAAI,GAAG,WAAW,EAAE,MAAM,CAAC;EAC3B,SAAS,GAAG,SAAS;EACrB,WAAW,GAAG,WAAW;EACzB,WAAW,GAAG,WAAW;E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 +1,24 @@
1
1
  import { $atom, $module, t } from "alepha";
2
- import { $entity, db, pageQuerySchema } from "alepha/orm";
3
2
  import { logEntrySchema } from "alepha/logger";
3
+ import { $entity, db } from "alepha/orm";
4
4
  //#region ../../src/api/jobs/entities/jobExecutionEntity.ts
5
+ /**
6
+ * Job execution record.
7
+ *
8
+ * Stores durable state for queue-mode jobs (outbox pattern) and error records
9
+ * for cron-mode jobs. Successful executions are trimmed by the sweep to keep
10
+ * the last N rows per job (configurable via `jobConfig.keepLastSuccess`).
11
+ *
12
+ * Status transitions:
13
+ * - queue push → pending
14
+ * - worker claim → running
15
+ * - success → ok
16
+ * - terminal failure → error
17
+ * - retry → scheduled (with scheduledAt = now + backoff)
18
+ * - delay → scheduled (with scheduledAt = now + delay)
19
+ * - sweep picks due ones → pending
20
+ * - cancel → cancelled
21
+ */
5
22
  const jobExecutionEntity = $entity({
6
23
  name: "job_executions",
7
24
  schema: t.object({
@@ -10,14 +27,12 @@ const jobExecutionEntity = $entity({
10
27
  updatedAt: db.updatedAt(),
11
28
  jobName: t.text(),
12
29
  key: t.optional(t.nullable(t.text())),
13
- payload: t.optional(t.record(t.text(), t.any())),
14
30
  status: db.default(t.enum([
15
31
  "pending",
16
- "scheduled",
17
- "retrying",
18
32
  "running",
19
- "completed",
20
- "dead",
33
+ "scheduled",
34
+ "ok",
35
+ "error",
21
36
  "cancelled"
22
37
  ]), "pending"),
23
38
  priority: db.default(t.integer({
@@ -26,12 +41,12 @@ const jobExecutionEntity = $entity({
26
41
  }), 2),
27
42
  attempt: db.default(t.integer(), 0),
28
43
  maxAttempts: db.default(t.integer(), 1),
44
+ payload: t.optional(t.record(t.text(), t.any())),
29
45
  scheduledAt: t.optional(t.datetime()),
30
46
  startedAt: t.optional(t.datetime()),
31
47
  completedAt: t.optional(t.datetime()),
32
- result: t.optional(t.record(t.text(), t.any())),
33
48
  error: t.optional(t.text()),
34
- workerId: t.optional(t.text()),
49
+ logs: t.optional(t.array(logEntrySchema)),
35
50
  triggeredBy: t.optional(t.text()),
36
51
  triggeredByName: t.optional(t.text()),
37
52
  cancelledBy: t.optional(t.text()),
@@ -41,15 +56,9 @@ const jobExecutionEntity = $entity({
41
56
  { columns: [
42
57
  "jobName",
43
58
  "status",
44
- "priority",
45
59
  "scheduledAt"
46
60
  ] },
47
- { columns: [
48
- "jobName",
49
- "status",
50
- "startedAt"
51
- ] },
52
- { columns: ["jobName", "completedAt"] },
61
+ { columns: ["jobName", "startedAt"] },
53
62
  {
54
63
  columns: ["jobName", "key"],
55
64
  unique: true
@@ -57,186 +66,93 @@ const jobExecutionEntity = $entity({
57
66
  ]
58
67
  });
59
68
  //#endregion
60
- //#region ../../src/api/jobs/entities/jobExecutionLogEntity.ts
61
- const jobExecutionLogEntity = $entity({
62
- name: "job_execution_logs",
63
- schema: t.object({
64
- id: db.primaryKey(t.uuid()),
65
- logs: t.array(logEntrySchema)
66
- })
67
- });
68
- //#endregion
69
- //#region ../../src/api/jobs/schemas/jobActivitySchema.ts
70
- const jobActivityPointSchema = t.object({
71
- date: t.text(),
72
- completed: t.integer(),
73
- failed: t.integer()
74
- });
75
- const jobActivityQuerySchema = t.object({ days: t.optional(t.integer({
76
- minimum: 1,
77
- maximum: 90
78
- })) });
79
- //#endregion
80
69
  //#region ../../src/api/jobs/schemas/jobConfigAtom.ts
81
70
  const jobConfig = $atom({
82
71
  name: "alepha.jobs",
83
- description: "Configuration for the $job v2 primitive.",
72
+ description: "Configuration for the $job primitive.",
84
73
  schema: t.object({
85
- recovery: t.object({
86
- interval: t.integer({ description: "Sweep interval (ms)." }),
87
- staleThreshold: t.integer({ description: "Pending age (ms) before re-dispatch." }),
88
- runTimeout: t.integer({ description: "Running age (ms) before assumed crash. Used as fallback when no per-job timeout is set." })
89
- }),
90
- delayed: t.object({ interval: t.integer({ description: "Sweep interval (ms)." }) }),
91
- logRetentionDays: t.integer({ description: "Days to keep completed/dead executions." }),
74
+ sweepInterval: t.integer({ description: "Sweep cron interval in milliseconds." }),
75
+ staleThreshold: t.integer({ description: "Pending age (ms) before the sweep re-dispatches it." }),
76
+ runTimeout: t.integer({ description: "Running age (ms) before assumed crash (fallback when no per-job timeout)." }),
77
+ keepLastSuccess: t.integer({ description: "Max successful rows to keep per job. Set 0 to disable and delete on success." }),
78
+ keepLastError: t.integer({ description: "Max error rows to keep per job." }),
92
79
  logMaxEntries: t.integer({ description: "Max log entries captured per execution." }),
93
80
  drainTimeout: t.integer({ description: "Max time (ms) to wait for in-flight jobs during shutdown." })
94
81
  }),
95
82
  default: {
96
- recovery: {
97
- interval: 3e5,
98
- staleThreshold: 3e5,
99
- runTimeout: 18e5
100
- },
101
- delayed: { interval: 3e5 },
102
- logRetentionDays: 30,
83
+ sweepInterval: 3e5,
84
+ staleThreshold: 3e5,
85
+ runTimeout: 18e5,
86
+ keepLastSuccess: 10,
87
+ keepLastError: 10,
103
88
  logMaxEntries: 100,
104
89
  drainTimeout: 3e4
105
90
  }
106
91
  });
107
92
  //#endregion
108
- //#region ../../src/api/jobs/schemas/jobCronInfoSchema.ts
109
- const jobCronInfoSchema = t.object({
110
- name: t.text(),
111
- cron: t.text(),
112
- lock: t.boolean(),
113
- priority: t.enum([
114
- "critical",
115
- "high",
116
- "normal",
117
- "low"
118
- ]),
119
- concurrency: t.integer(),
120
- hasSchema: t.boolean(),
121
- paused: t.boolean(),
122
- lastExecution: t.optional(t.object({
123
- id: t.uuid(),
124
- status: t.text(),
125
- startedAt: t.optional(t.datetime()),
126
- completedAt: t.optional(t.datetime()),
127
- error: t.optional(t.text())
128
- }))
129
- });
130
- //#endregion
131
- //#region ../../src/api/jobs/schemas/jobExecutionResourceSchema.ts
132
- const jobExecutionCanSchema = t.object({
133
- retry: t.boolean(),
134
- cancel: t.boolean()
135
- });
136
- const jobExecutionResourceSchema = t.extend(jobExecutionEntity.schema, { can: jobExecutionCanSchema }, {
137
- title: "JobExecutionResource",
138
- description: "A job execution resource."
139
- });
140
- //#endregion
141
- //#region ../../src/api/jobs/schemas/jobExecutionDetailResourceSchema.ts
142
- const jobExecutionDetailResourceSchema = t.extend(jobExecutionEntity.schema, {
143
- can: jobExecutionCanSchema,
144
- logs: t.optional(t.array(logEntrySchema))
145
- }, {
146
- title: "JobExecutionDetailResource",
147
- description: "A job execution resource with logs."
148
- });
149
- //#endregion
150
93
  //#region ../../src/api/jobs/schemas/jobExecutionQuerySchema.ts
151
- const jobExecutionQuerySchema = t.extend(pageQuerySchema, {
152
- job: t.optional(t.text({ description: "Filter by job name" })),
94
+ const jobExecutionQuerySchema = t.object({
153
95
  status: t.optional(t.enum([
154
96
  "pending",
155
- "scheduled",
156
- "retrying",
157
97
  "running",
158
- "completed",
159
- "dead",
98
+ "scheduled",
99
+ "ok",
100
+ "error",
160
101
  "cancelled"
161
102
  ])),
162
- priority: t.optional(t.enum([
163
- "critical",
164
- "high",
165
- "normal",
166
- "low"
167
- ])),
168
- from: t.optional(t.datetime({ description: "From date (ISO)" })),
169
- to: t.optional(t.datetime({ description: "To date (ISO)" }))
170
- });
171
- //#endregion
172
- //#region ../../src/api/jobs/schemas/jobFailureSchema.ts
173
- const jobFailureSchema = t.object({
174
- jobName: t.text(),
175
- failures: t.integer(),
176
- lastError: t.optional(t.text())
103
+ limit: t.optional(t.integer({
104
+ minimum: 1,
105
+ maximum: 200,
106
+ default: 20
107
+ }))
177
108
  });
178
109
  //#endregion
179
- //#region ../../src/api/jobs/schemas/jobQueueDepthSchema.ts
180
- const jobQueueDepthSchema = t.object({
181
- jobName: t.text(),
182
- pending: t.integer(),
183
- running: t.integer(),
184
- scheduled: t.integer(),
185
- retrying: t.integer(),
186
- dead: t.integer(),
187
- concurrency: t.integer(),
188
- paused: t.boolean()
110
+ //#region ../../src/api/jobs/schemas/jobExecutionResourceSchema.ts
111
+ const jobExecutionResourceSchema = t.extend(jobExecutionEntity.schema, { can: t.object({
112
+ retry: t.boolean(),
113
+ cancel: t.boolean()
114
+ }) }, {
115
+ title: "JobExecutionResource",
116
+ description: "A job execution row with derived actions."
189
117
  });
190
118
  //#endregion
191
119
  //#region ../../src/api/jobs/schemas/jobRegistrationSchema.ts
192
120
  const jobRegistrationSchema = t.object({
193
121
  name: t.text(),
194
- type: t.enum([
195
- "cron",
196
- "push",
197
- "both"
198
- ]),
122
+ description: t.optional(t.text()),
123
+ type: t.enum(["cron", "queue"]),
199
124
  priority: t.enum([
200
125
  "critical",
201
126
  "high",
202
127
  "normal",
203
128
  "low"
204
129
  ]),
205
- concurrency: t.integer(),
206
- hasSchema: t.boolean(),
207
130
  cron: t.optional(t.text()),
208
131
  timeout: t.optional(t.text()),
209
132
  retry: t.optional(t.object({
210
133
  retries: t.integer(),
211
134
  hasBackoff: t.boolean()
212
135
  })),
213
- paused: t.boolean()
214
- });
215
- //#endregion
216
- //#region ../../src/api/jobs/schemas/jobStatsSchema.ts
217
- const jobStatsSchema = t.object({
218
- registered: t.integer(),
219
- running: t.integer(),
220
- pending: t.integer(),
221
- scheduled: t.integer(),
222
- retrying: t.integer(),
223
- dead: t.integer(),
224
- completed: t.integer(),
225
- failed: t.integer()
136
+ recent: t.object({
137
+ ok: t.integer(),
138
+ error: t.integer(),
139
+ lastRun: t.optional(t.datetime())
140
+ })
226
141
  });
227
142
  //#endregion
228
143
  //#region ../../src/api/jobs/schemas/triggerJobSchema.ts
229
- const triggerJobSchema = t.object({
230
- name: t.text(),
231
- payload: t.optional(t.record(t.text(), t.any()))
232
- });
144
+ const triggerJobSchema = t.object({ payload: t.optional(t.record(t.text(), t.any())) });
233
145
  //#endregion
234
146
  //#region ../../src/api/jobs/index.browser.ts
235
147
  const AlephaApiJobs = $module({
236
148
  name: "alepha.api.jobs",
237
149
  services: []
238
150
  });
151
+ const AlephaApiJobsQueue = $module({
152
+ name: "alepha.api.jobs.queue",
153
+ services: []
154
+ });
239
155
  //#endregion
240
- export { AlephaApiJobs, jobActivityPointSchema, jobActivityQuerySchema, jobConfig, jobCronInfoSchema, jobExecutionCanSchema, jobExecutionDetailResourceSchema, jobExecutionEntity, jobExecutionLogEntity, jobExecutionQuerySchema, jobExecutionResourceSchema, jobFailureSchema, jobQueueDepthSchema, jobRegistrationSchema, jobStatsSchema, triggerJobSchema };
156
+ export { AlephaApiJobs, AlephaApiJobsQueue, jobConfig, jobExecutionEntity, jobExecutionQuerySchema, jobExecutionResourceSchema, jobRegistrationSchema, triggerJobSchema };
241
157
 
242
158
  //# sourceMappingURL=index.browser.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.browser.js","names":[],"sources":["../../../src/api/jobs/entities/jobExecutionEntity.ts","../../../src/api/jobs/entities/jobExecutionLogEntity.ts","../../../src/api/jobs/schemas/jobActivitySchema.ts","../../../src/api/jobs/schemas/jobConfigAtom.ts","../../../src/api/jobs/schemas/jobCronInfoSchema.ts","../../../src/api/jobs/schemas/jobExecutionResourceSchema.ts","../../../src/api/jobs/schemas/jobExecutionDetailResourceSchema.ts","../../../src/api/jobs/schemas/jobExecutionQuerySchema.ts","../../../src/api/jobs/schemas/jobFailureSchema.ts","../../../src/api/jobs/schemas/jobQueueDepthSchema.ts","../../../src/api/jobs/schemas/jobRegistrationSchema.ts","../../../src/api/jobs/schemas/jobStatsSchema.ts","../../../src/api/jobs/schemas/triggerJobSchema.ts","../../../src/api/jobs/index.browser.ts"],"sourcesContent":["import { type Static, t } from \"alepha\";\nimport { $entity, db } from \"alepha/orm\";\n\nexport const jobExecutionEntity = $entity({\n name: \"job_executions\",\n schema: t.object({\n id: db.primaryKey(t.uuid()),\n createdAt: db.createdAt(),\n updatedAt: db.updatedAt(),\n\n jobName: t.text(),\n key: t.optional(t.nullable(t.text())),\n\n payload: t.optional(t.record(t.text(), t.any())),\n status: db.default(\n t.enum([\n \"pending\",\n \"scheduled\",\n \"retrying\",\n \"running\",\n \"completed\",\n \"dead\",\n \"cancelled\",\n ]),\n \"pending\",\n ),\n priority: db.default(t.integer({ minimum: 0, maximum: 3 }), 2),\n\n attempt: db.default(t.integer(), 0),\n maxAttempts: db.default(t.integer(), 1),\n\n scheduledAt: t.optional(t.datetime()),\n startedAt: t.optional(t.datetime()),\n completedAt: t.optional(t.datetime()),\n\n result: t.optional(t.record(t.text(), t.any())),\n error: t.optional(t.text()),\n workerId: t.optional(t.text()),\n\n triggeredBy: t.optional(t.text()),\n triggeredByName: t.optional(t.text()),\n cancelledBy: t.optional(t.text()),\n cancelledByName: t.optional(t.text()),\n }),\n indexes: [\n { columns: [\"jobName\", \"status\", \"priority\", \"scheduledAt\"] },\n { columns: [\"jobName\", \"status\", \"startedAt\"] },\n { columns: [\"jobName\", \"completedAt\"] },\n { columns: [\"jobName\", \"key\"], unique: true },\n ],\n});\n\nexport type JobExecutionEntity = Static<typeof jobExecutionEntity.schema>;\n\nexport type JobStatus =\n | \"pending\"\n | \"scheduled\"\n | \"retrying\"\n | \"running\"\n | \"completed\"\n | \"dead\"\n | \"cancelled\";\n","import { type Static, t } from \"alepha\";\nimport { logEntrySchema } from \"alepha/logger\";\nimport { $entity, db } from \"alepha/orm\";\n\nexport const jobExecutionLogEntity = $entity({\n name: \"job_execution_logs\",\n schema: t.object({\n id: db.primaryKey(t.uuid()),\n logs: t.array(logEntrySchema),\n }),\n});\n\nexport type JobExecutionLogEntity = Static<typeof jobExecutionLogEntity.schema>;\n","import { type Static, t } from \"alepha\";\n\nexport const jobActivityPointSchema = t.object({\n date: t.text(),\n completed: t.integer(),\n failed: t.integer(),\n});\n\nexport type JobActivityPoint = Static<typeof jobActivityPointSchema>;\n\nexport const jobActivityQuerySchema = t.object({\n days: t.optional(t.integer({ minimum: 1, maximum: 90 })),\n});\n\nexport type JobActivityQuery = Static<typeof jobActivityQuerySchema>;\n","import { $atom, type Static, t } from \"alepha\";\n\nexport const jobConfig = $atom({\n name: \"alepha.jobs\",\n description: \"Configuration for the $job v2 primitive.\",\n schema: t.object({\n recovery: t.object({\n interval: t.integer({ description: \"Sweep interval (ms).\" }),\n staleThreshold: t.integer({\n description: \"Pending age (ms) before re-dispatch.\",\n }),\n runTimeout: t.integer({\n description:\n \"Running age (ms) before assumed crash. Used as fallback when no per-job timeout is set.\",\n }),\n }),\n delayed: t.object({\n interval: t.integer({ description: \"Sweep interval (ms).\" }),\n }),\n logRetentionDays: t.integer({\n description: \"Days to keep completed/dead executions.\",\n }),\n logMaxEntries: t.integer({\n description: \"Max log entries captured per execution.\",\n }),\n drainTimeout: t.integer({\n description: \"Max time (ms) to wait for in-flight jobs during shutdown.\",\n }),\n }),\n default: {\n recovery: {\n interval: 300_000,\n staleThreshold: 300_000,\n runTimeout: 1_800_000,\n },\n delayed: {\n interval: 300_000,\n },\n logRetentionDays: 30,\n logMaxEntries: 100,\n drainTimeout: 30_000,\n },\n});\n\nexport type JobConfig = Static<typeof jobConfig.schema>;\n\ndeclare module \"alepha\" {\n interface State {\n [jobConfig.key]: JobConfig;\n }\n}\n","import { type Static, t } from \"alepha\";\n\nexport const jobCronInfoSchema = t.object({\n name: t.text(),\n cron: t.text(),\n lock: t.boolean(),\n priority: t.enum([\"critical\", \"high\", \"normal\", \"low\"]),\n concurrency: t.integer(),\n hasSchema: t.boolean(),\n paused: t.boolean(),\n lastExecution: t.optional(\n t.object({\n id: t.uuid(),\n status: t.text(),\n startedAt: t.optional(t.datetime()),\n completedAt: t.optional(t.datetime()),\n error: t.optional(t.text()),\n }),\n ),\n});\n\nexport type JobCronInfo = Static<typeof jobCronInfoSchema>;\n","import { type Static, t } from \"alepha\";\nimport { jobExecutionEntity } from \"../entities/jobExecutionEntity.ts\";\n\nexport const jobExecutionCanSchema = t.object({\n retry: t.boolean(),\n cancel: t.boolean(),\n});\n\nexport const jobExecutionResourceSchema = t.extend(\n jobExecutionEntity.schema,\n {\n can: jobExecutionCanSchema,\n },\n {\n title: \"JobExecutionResource\",\n description: \"A job execution resource.\",\n },\n);\n\nexport type JobExecutionResource = Static<typeof jobExecutionResourceSchema>;\n","import { type Static, t } from \"alepha\";\nimport { logEntrySchema } from \"alepha/logger\";\nimport { jobExecutionEntity } from \"../entities/jobExecutionEntity.ts\";\nimport { jobExecutionCanSchema } from \"./jobExecutionResourceSchema.ts\";\n\nexport const jobExecutionDetailResourceSchema = t.extend(\n jobExecutionEntity.schema,\n {\n can: jobExecutionCanSchema,\n logs: t.optional(t.array(logEntrySchema)),\n },\n {\n title: \"JobExecutionDetailResource\",\n description: \"A job execution resource with logs.\",\n },\n);\n\nexport type JobExecutionDetailResource = Static<\n typeof jobExecutionDetailResourceSchema\n>;\n","import { type Static, t } from \"alepha\";\nimport { pageQuerySchema } from \"alepha/orm\";\n\nexport const jobExecutionQuerySchema = t.extend(pageQuerySchema, {\n job: t.optional(\n t.text({\n description: \"Filter by job name\",\n }),\n ),\n status: t.optional(\n t.enum([\n \"pending\",\n \"scheduled\",\n \"retrying\",\n \"running\",\n \"completed\",\n \"dead\",\n \"cancelled\",\n ]),\n ),\n priority: t.optional(t.enum([\"critical\", \"high\", \"normal\", \"low\"])),\n from: t.optional(\n t.datetime({\n description: \"From date (ISO)\",\n }),\n ),\n to: t.optional(\n t.datetime({\n description: \"To date (ISO)\",\n }),\n ),\n});\n\nexport type JobExecutionQuery = Static<typeof jobExecutionQuerySchema>;\n","import { type Static, t } from \"alepha\";\n\nexport const jobFailureSchema = t.object({\n jobName: t.text(),\n failures: t.integer(),\n lastError: t.optional(t.text()),\n});\n\nexport type JobFailure = Static<typeof jobFailureSchema>;\n","import { type Static, t } from \"alepha\";\n\nexport const jobQueueDepthSchema = t.object({\n jobName: t.text(),\n pending: t.integer(),\n running: t.integer(),\n scheduled: t.integer(),\n retrying: t.integer(),\n dead: t.integer(),\n concurrency: t.integer(),\n paused: t.boolean(),\n});\n\nexport type JobQueueDepth = Static<typeof jobQueueDepthSchema>;\n","import { type Static, t } from \"alepha\";\n\nexport const jobRegistrationSchema = t.object({\n name: t.text(),\n type: t.enum([\"cron\", \"push\", \"both\"]),\n priority: t.enum([\"critical\", \"high\", \"normal\", \"low\"]),\n concurrency: t.integer(),\n hasSchema: t.boolean(),\n cron: t.optional(t.text()),\n timeout: t.optional(t.text()),\n retry: t.optional(\n t.object({\n retries: t.integer(),\n hasBackoff: t.boolean(),\n }),\n ),\n paused: t.boolean(),\n});\n\nexport type JobRegistration = Static<typeof jobRegistrationSchema>;\n","import { type Static, t } from \"alepha\";\n\nexport const jobStatsSchema = t.object({\n registered: t.integer(),\n running: t.integer(),\n pending: t.integer(),\n scheduled: t.integer(),\n retrying: t.integer(),\n dead: t.integer(),\n completed: t.integer(),\n failed: t.integer(),\n});\n\nexport type JobStats = Static<typeof jobStatsSchema>;\n","import { type Static, t } from \"alepha\";\n\nexport const triggerJobSchema = t.object({\n name: t.text(),\n payload: t.optional(t.record(t.text(), t.any())),\n});\n\nexport type TriggerJob = Static<typeof triggerJobSchema>;\n","import { $module } from \"alepha\";\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport * from \"./entities/jobExecutionEntity.ts\";\nexport * from \"./entities/jobExecutionLogEntity.ts\";\nexport * from \"./schemas/jobActivitySchema.ts\";\nexport * from \"./schemas/jobConfigAtom.ts\";\nexport * from \"./schemas/jobCronInfoSchema.ts\";\nexport * from \"./schemas/jobExecutionDetailResourceSchema.ts\";\nexport * from \"./schemas/jobExecutionQuerySchema.ts\";\nexport * from \"./schemas/jobExecutionResourceSchema.ts\";\nexport * from \"./schemas/jobFailureSchema.ts\";\nexport * from \"./schemas/jobQueueDepthSchema.ts\";\nexport * from \"./schemas/jobRegistrationSchema.ts\";\nexport * from \"./schemas/jobStatsSchema.ts\";\nexport * from \"./schemas/triggerJobSchema.ts\";\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport const AlephaApiJobs = $module({\n name: \"alepha.api.jobs\",\n services: [],\n});\n"],"mappings":";;;;AAGA,MAAa,qBAAqB,QAAQ;CACxC,MAAM;CACN,QAAQ,EAAE,OAAO;EACf,IAAI,GAAG,WAAW,EAAE,MAAM,CAAC;EAC3B,WAAW,GAAG,WAAW;EACzB,WAAW,GAAG,WAAW;EAEzB,SAAS,EAAE,MAAM;EACjB,KAAK,EAAE,SAAS,EAAE,SAAS,EAA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jB,aAAa,EAAE,SAAS;CACxB,QAAQ,EAAE,SAAS;CACpB,CAAC;;;ACTF,MAAa,wBAAwB,EAAE,OAAO;CAC5C,MAAM,EAAE,MAAM;CACd,MAAM,EAAE,KAAK;EAAC;EAAQ;EAAQ;EAAO,CAAC;CACtC,UAAU,EAAE,KAAK;EAAC;EAAY;EAAQ;EAAU;EAAM,CAAC;CACvD,aAAa,EAAE,SAAS;CACxB,WAAW,EAAE,SAAS;CACtB,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC;CAC1B,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC;CAC7B,OAAO,EAAE,SACP,EAAE,OAAO;EACP,SAAS,EAAE,SAAS;EACpB,YAAY,EAAE,SAAS;EACxB,CAAC,CACH;CACD,QAAQ,EAAE,SAAS;CACpB,CAAC;;;ACfF,MAAa,iBAAiB,EAAE,OAAO;CACrC,YAAY,EAAE,SAAS;CACvB,SAAS,EAAE,SAAS;CACpB,SAAS,EAAE,SAAS;CACpB,WAAW,EAAE,SAAS;CACtB,UAAU,EAAE,SAAS;CACrB,MAAM,EAAE,SAAS;CACjB,WAAW,EAAE,SAAS;CACtB,QAAQ,EAAE,SAAS;CACpB,CAAC;;;ACTF,MAAa,mBAAmB,EAAE,OAAO;CACvC,MAAM,EAAE,MAAM;CACd,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,KAAK,CAAC,CAAC;CACjD,CAAC;;;ACeF,MAAa,gBAAgB,QAAQ;CACnC,MAAM;CACN,UAAU,EAAE;CACb,CAAC"}
1
+ {"version":3,"file":"index.browser.js","names":[],"sources":["../../../src/api/jobs/entities/jobExecutionEntity.ts","../../../src/api/jobs/schemas/jobConfigAtom.ts","../../../src/api/jobs/schemas/jobExecutionQuerySchema.ts","../../../src/api/jobs/schemas/jobExecutionResourceSchema.ts","../../../src/api/jobs/schemas/jobRegistrationSchema.ts","../../../src/api/jobs/schemas/triggerJobSchema.ts","../../../src/api/jobs/index.browser.ts"],"sourcesContent":["import { type Static, t } from \"alepha\";\nimport { logEntrySchema } from \"alepha/logger\";\nimport { $entity, db } from \"alepha/orm\";\n\n/**\n * Job execution record.\n *\n * Stores durable state for queue-mode jobs (outbox pattern) and error records\n * for cron-mode jobs. Successful executions are trimmed by the sweep to keep\n * the last N rows per job (configurable via `jobConfig.keepLastSuccess`).\n *\n * Status transitions:\n * - queue push → pending\n * - worker claim → running\n * - success → ok\n * - terminal failure → error\n * - retry → scheduled (with scheduledAt = now + backoff)\n * - delay → scheduled (with scheduledAt = now + delay)\n * - sweep picks due ones → pending\n * - cancel → cancelled\n */\nexport const jobExecutionEntity = $entity({\n name: \"job_executions\",\n schema: t.object({\n id: db.primaryKey(t.uuid()),\n createdAt: db.createdAt(),\n updatedAt: db.updatedAt(),\n\n jobName: t.text(),\n key: t.optional(t.nullable(t.text())),\n\n status: db.default(\n t.enum([\"pending\", \"running\", \"scheduled\", \"ok\", \"error\", \"cancelled\"]),\n \"pending\",\n ),\n priority: db.default(t.integer({ minimum: 0, maximum: 3 }), 2),\n\n attempt: db.default(t.integer(), 0),\n maxAttempts: db.default(t.integer(), 1),\n\n payload: t.optional(t.record(t.text(), t.any())),\n\n scheduledAt: t.optional(t.datetime()),\n startedAt: t.optional(t.datetime()),\n completedAt: t.optional(t.datetime()),\n\n error: t.optional(t.text()),\n logs: t.optional(t.array(logEntrySchema)),\n\n triggeredBy: t.optional(t.text()),\n triggeredByName: t.optional(t.text()),\n cancelledBy: t.optional(t.text()),\n cancelledByName: t.optional(t.text()),\n }),\n indexes: [\n { columns: [\"jobName\", \"status\", \"scheduledAt\"] },\n { columns: [\"jobName\", \"startedAt\"] },\n { columns: [\"jobName\", \"key\"], unique: true },\n ],\n});\n\nexport type JobExecutionEntity = Static<typeof jobExecutionEntity.schema>;\n\nexport type JobStatus =\n | \"pending\"\n | \"running\"\n | \"scheduled\"\n | \"ok\"\n | \"error\"\n | \"cancelled\";\n","import { $atom, type Static, t } from \"alepha\";\n\nexport const jobConfig = $atom({\n name: \"alepha.jobs\",\n description: \"Configuration for the $job primitive.\",\n schema: t.object({\n sweepInterval: t.integer({\n description: \"Sweep cron interval in milliseconds.\",\n }),\n staleThreshold: t.integer({\n description: \"Pending age (ms) before the sweep re-dispatches it.\",\n }),\n runTimeout: t.integer({\n description:\n \"Running age (ms) before assumed crash (fallback when no per-job timeout).\",\n }),\n keepLastSuccess: t.integer({\n description:\n \"Max successful rows to keep per job. Set 0 to disable and delete on success.\",\n }),\n keepLastError: t.integer({\n description: \"Max error rows to keep per job.\",\n }),\n logMaxEntries: t.integer({\n description: \"Max log entries captured per execution.\",\n }),\n drainTimeout: t.integer({\n description: \"Max time (ms) to wait for in-flight jobs during shutdown.\",\n }),\n }),\n default: {\n sweepInterval: 300_000,\n staleThreshold: 300_000,\n runTimeout: 1_800_000,\n keepLastSuccess: 10,\n keepLastError: 10,\n logMaxEntries: 100,\n drainTimeout: 30_000,\n },\n});\n\nexport type JobConfig = Static<typeof jobConfig.schema>;\n\ndeclare module \"alepha\" {\n interface State {\n [jobConfig.key]: JobConfig;\n }\n}\n","import { type Static, t } from \"alepha\";\n\nexport const jobExecutionQuerySchema = t.object({\n status: t.optional(\n t.enum([\"pending\", \"running\", \"scheduled\", \"ok\", \"error\", \"cancelled\"]),\n ),\n limit: t.optional(t.integer({ minimum: 1, maximum: 200, default: 20 })),\n});\n\nexport type JobExecutionQuery = Static<typeof jobExecutionQuerySchema>;\n","import { type Static, t } from \"alepha\";\nimport { jobExecutionEntity } from \"../entities/jobExecutionEntity.ts\";\n\nexport const jobExecutionResourceSchema = t.extend(\n jobExecutionEntity.schema,\n {\n can: t.object({\n retry: t.boolean(),\n cancel: t.boolean(),\n }),\n },\n {\n title: \"JobExecutionResource\",\n description: \"A job execution row with derived actions.\",\n },\n);\n\nexport type JobExecutionResource = Static<typeof jobExecutionResourceSchema>;\n","import { type Static, t } from \"alepha\";\n\nexport const jobRegistrationSchema = t.object({\n name: t.text(),\n description: t.optional(t.text()),\n type: t.enum([\"cron\", \"queue\"]),\n priority: t.enum([\"critical\", \"high\", \"normal\", \"low\"]),\n cron: t.optional(t.text()),\n timeout: t.optional(t.text()),\n retry: t.optional(\n t.object({\n retries: t.integer(),\n hasBackoff: t.boolean(),\n }),\n ),\n recent: t.object({\n ok: t.integer(),\n error: t.integer(),\n lastRun: t.optional(t.datetime()),\n }),\n});\n\nexport type JobRegistration = Static<typeof jobRegistrationSchema>;\n","import { type Static, t } from \"alepha\";\n\nexport const triggerJobSchema = t.object({\n payload: t.optional(t.record(t.text(), t.any())),\n});\n\nexport type TriggerJob = Static<typeof triggerJobSchema>;\n","import { $module } from \"alepha\";\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport * from \"./entities/jobExecutionEntity.ts\";\nexport * from \"./schemas/jobConfigAtom.ts\";\nexport * from \"./schemas/jobExecutionQuerySchema.ts\";\nexport * from \"./schemas/jobExecutionResourceSchema.ts\";\nexport * from \"./schemas/jobRegistrationSchema.ts\";\nexport * from \"./schemas/triggerJobSchema.ts\";\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport const AlephaApiJobs = $module({\n name: \"alepha.api.jobs\",\n services: [],\n});\n\nexport const AlephaApiJobsQueue = $module({\n name: \"alepha.api.jobs.queue\",\n services: [],\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,qBAAqB,QAAQ;CACxC,MAAM;CACN,QAAQ,EAAE,OAAO;EACf,IAAI,GAAG,WAAW,EAAE,MAAM,CAAC;EAC3B,WAAW,GAAG,WAAW;EACzB,WAAW,GAAG,WAAW;EAEzB,SAAS,EAAE,MAAM;EACjB,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;EAErC,QAAQ,GAAG,QACT,EAAE,KAAK;GAAC;GAAW;GAAW;GAAa;GAAM;GAAS;GAAY,CAAC,EACvE,UACD;EACD,UAAU,GAAG,QAAQ,EAAE,QAAQ;GAAE,SAAS;GAAG,SAAS;GAAG,CAAC,EA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