alepha 0.20.6 → 0.20.7

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 (243) hide show
  1. package/AGENTS.md +0 -1
  2. package/CLAUDE.md +0 -1
  3. package/assets/agents-template.md +0 -1
  4. package/dist/api/audits/index.browser.js +1 -0
  5. package/dist/api/audits/index.browser.js.map +1 -1
  6. package/dist/api/audits/index.d.ts +370 -355
  7. package/dist/api/audits/index.d.ts.map +1 -1
  8. package/dist/api/audits/index.js +1 -0
  9. package/dist/api/audits/index.js.map +1 -1
  10. package/dist/api/files/index.browser.js +1 -0
  11. package/dist/api/files/index.browser.js.map +1 -1
  12. package/dist/api/files/index.d.ts +179 -170
  13. package/dist/api/files/index.d.ts.map +1 -1
  14. package/dist/api/files/index.js +1 -0
  15. package/dist/api/files/index.js.map +1 -1
  16. package/dist/api/jobs/index.browser.js +7 -0
  17. package/dist/api/jobs/index.browser.js.map +1 -1
  18. package/dist/api/jobs/index.d.ts +271 -262
  19. package/dist/api/jobs/index.d.ts.map +1 -1
  20. package/dist/api/jobs/index.js +21 -3
  21. package/dist/api/jobs/index.js.map +1 -1
  22. package/dist/api/keys/index.d.ts +198 -192
  23. package/dist/api/keys/index.d.ts.map +1 -1
  24. package/dist/api/keys/index.js +1 -0
  25. package/dist/api/keys/index.js.map +1 -1
  26. package/dist/api/notifications/index.d.ts +246 -245
  27. package/dist/api/notifications/index.d.ts.map +1 -1
  28. package/dist/api/organizations/index.d.ts +100 -97
  29. package/dist/api/organizations/index.d.ts.map +1 -1
  30. package/dist/api/parameters/index.d.ts +323 -320
  31. package/dist/api/parameters/index.d.ts.map +1 -1
  32. package/dist/api/payments/index.d.ts +431 -376
  33. package/dist/api/payments/index.d.ts.map +1 -1
  34. package/dist/api/payments/index.js +202 -87
  35. package/dist/api/payments/index.js.map +1 -1
  36. package/dist/api/subscriptions/index.d.ts +1695 -0
  37. package/dist/api/subscriptions/index.d.ts.map +1 -0
  38. package/dist/api/subscriptions/index.js +1919 -0
  39. package/dist/api/subscriptions/index.js.map +1 -0
  40. package/dist/api/users/index.d.ts +863 -847
  41. package/dist/api/users/index.d.ts.map +1 -1
  42. package/dist/api/verifications/index.d.ts +126 -125
  43. package/dist/api/verifications/index.d.ts.map +1 -1
  44. package/dist/bucket/index.d.ts +3 -2
  45. package/dist/bucket/index.d.ts.map +1 -1
  46. package/dist/cache/core/index.d.ts +114 -4
  47. package/dist/cache/core/index.d.ts.map +1 -1
  48. package/dist/cache/core/index.js +181 -15
  49. package/dist/cache/core/index.js.map +1 -1
  50. package/dist/cache/core/index.workerd.js +181 -15
  51. package/dist/cache/core/index.workerd.js.map +1 -1
  52. package/dist/cache/database/index.d.ts +20 -19
  53. package/dist/cache/database/index.d.ts.map +1 -1
  54. package/dist/cache/redis/index.d.ts +3 -2
  55. package/dist/cache/redis/index.d.ts.map +1 -1
  56. package/dist/cli/core/index.d.ts +113 -129
  57. package/dist/cli/core/index.d.ts.map +1 -1
  58. package/dist/cli/core/index.js +75 -7
  59. package/dist/cli/core/index.js.map +1 -1
  60. package/dist/cli/devtools/index.d.ts +3 -2
  61. package/dist/cli/devtools/index.d.ts.map +1 -1
  62. package/dist/cli/platform/index.d.ts +346 -290
  63. package/dist/cli/platform/index.d.ts.map +1 -1
  64. package/dist/cli/platform/index.js +105 -6
  65. package/dist/cli/platform/index.js.map +1 -1
  66. package/dist/cli/vendor/index.d.ts +12 -11
  67. package/dist/cli/vendor/index.d.ts.map +1 -1
  68. package/dist/command/index.d.ts +5 -4
  69. package/dist/command/index.d.ts.map +1 -1
  70. package/dist/core/index.browser.js +1 -1
  71. package/dist/core/index.browser.js.map +1 -1
  72. package/dist/core/index.d.ts +119 -118
  73. package/dist/core/index.d.ts.map +1 -1
  74. package/dist/core/index.js +1 -1
  75. package/dist/core/index.js.map +1 -1
  76. package/dist/core/index.native.js +1 -1
  77. package/dist/core/index.native.js.map +1 -1
  78. package/dist/core/index.workerd.js +1 -1
  79. package/dist/core/index.workerd.js.map +1 -1
  80. package/dist/crypto/index.d.ts +3 -2
  81. package/dist/crypto/index.d.ts.map +1 -1
  82. package/dist/email/core/index.d.ts +3 -2
  83. package/dist/email/core/index.d.ts.map +1 -1
  84. package/dist/email/smtp/index.d.ts +7 -6
  85. package/dist/email/smtp/index.d.ts.map +1 -1
  86. package/dist/lock/core/index.d.ts +5 -4
  87. package/dist/lock/core/index.d.ts.map +1 -1
  88. package/dist/logger/index.d.ts +10 -9
  89. package/dist/logger/index.d.ts.map +1 -1
  90. package/dist/mcp/index.d.ts +9 -8
  91. package/dist/mcp/index.d.ts.map +1 -1
  92. package/dist/mcp/index.js +1 -1
  93. package/dist/mcp/index.js.map +1 -1
  94. package/dist/orm/core/index.browser.js +9 -3
  95. package/dist/orm/core/index.browser.js.map +1 -1
  96. package/dist/orm/core/index.bun.js +31 -10
  97. package/dist/orm/core/index.bun.js.map +1 -1
  98. package/dist/orm/core/index.d.ts +33 -14
  99. package/dist/orm/core/index.d.ts.map +1 -1
  100. package/dist/orm/core/index.js +31 -10
  101. package/dist/orm/core/index.js.map +1 -1
  102. package/dist/orm/postgres/index.d.ts +6 -5
  103. package/dist/orm/postgres/index.d.ts.map +1 -1
  104. package/dist/queue/core/index.d.ts +5 -4
  105. package/dist/queue/core/index.d.ts.map +1 -1
  106. package/dist/queue/redis/index.d.ts +3 -2
  107. package/dist/queue/redis/index.d.ts.map +1 -1
  108. package/dist/react/form/index.d.ts +5 -0
  109. package/dist/react/form/index.d.ts.map +1 -1
  110. package/dist/react/form/index.js +6 -4
  111. package/dist/react/form/index.js.map +1 -1
  112. package/dist/react/i18n/index.d.ts +2 -1
  113. package/dist/react/i18n/index.d.ts.map +1 -1
  114. package/dist/react/router/index.d.ts +206 -205
  115. package/dist/react/router/index.d.ts.map +1 -1
  116. package/dist/react/ui/index.d.ts +11 -11
  117. package/dist/react/ui/index.d.ts.map +1 -1
  118. package/dist/scheduler/index.d.ts +3 -2
  119. package/dist/scheduler/index.d.ts.map +1 -1
  120. package/dist/security/index.browser.js +29 -1
  121. package/dist/security/index.browser.js.map +1 -1
  122. package/dist/security/index.d.ts +82 -35
  123. package/dist/security/index.d.ts.map +1 -1
  124. package/dist/security/index.js +56 -3
  125. package/dist/security/index.js.map +1 -1
  126. package/dist/server/auth/index.d.ts +163 -158
  127. package/dist/server/auth/index.d.ts.map +1 -1
  128. package/dist/server/auth/index.js +16 -4
  129. package/dist/server/auth/index.js.map +1 -1
  130. package/dist/server/core/index.d.ts +35 -34
  131. package/dist/server/core/index.d.ts.map +1 -1
  132. package/dist/server/cors/index.d.ts +7 -6
  133. package/dist/server/cors/index.d.ts.map +1 -1
  134. package/dist/server/health/index.d.ts +16 -15
  135. package/dist/server/health/index.d.ts.map +1 -1
  136. package/dist/server/links/index.d.ts +51 -50
  137. package/dist/server/links/index.d.ts.map +1 -1
  138. package/dist/server/rate-limit/index.d.ts +6 -5
  139. package/dist/server/rate-limit/index.d.ts.map +1 -1
  140. package/dist/server/swagger/index.d.ts +2 -1
  141. package/dist/server/swagger/index.d.ts.map +1 -1
  142. package/dist/topic/redis/index.d.ts +3 -2
  143. package/dist/topic/redis/index.d.ts.map +1 -1
  144. package/package.json +16 -32
  145. package/src/api/audits/entities/audits.ts +1 -0
  146. package/src/api/files/entities/files.ts +1 -0
  147. package/src/api/jobs/__tests__/$job.spec.ts +92 -40
  148. package/src/api/jobs/entities/jobExecutionEntity.ts +1 -0
  149. package/src/api/jobs/providers/JobProvider.ts +20 -5
  150. package/src/api/jobs/schemas/jobConfigAtom.ts +5 -0
  151. package/src/api/keys/entities/apiKeyEntity.ts +1 -0
  152. package/src/api/payments/controllers/MockCheckoutController.ts +146 -0
  153. package/src/api/payments/index.ts +3 -0
  154. package/src/api/payments/providers/MemoryPaymentProvider.ts +9 -4
  155. package/src/api/payments/providers/PaymentProvider.ts +25 -9
  156. package/src/api/payments/services/PaymentService.ts +3 -0
  157. package/src/api/subscriptions/__tests__/BillingService.spec.ts +218 -0
  158. package/src/api/subscriptions/__tests__/SubscriptionService.spec.ts +278 -0
  159. package/src/api/subscriptions/controllers/AdminSubscriptionController.ts +212 -0
  160. package/src/api/subscriptions/controllers/SubscriptionController.ts +189 -0
  161. package/src/api/subscriptions/entities/subscriptionEvents.ts +54 -0
  162. package/src/api/subscriptions/entities/subscriptions.ts +68 -0
  163. package/src/api/subscriptions/index.ts +133 -0
  164. package/src/api/subscriptions/jobs/SubscriptionJobs.ts +382 -0
  165. package/src/api/subscriptions/middleware/$requireLimit.ts +50 -0
  166. package/src/api/subscriptions/middleware/$requirePlan.ts +49 -0
  167. package/src/api/subscriptions/notifications/SubscriptionNotifications.ts +110 -0
  168. package/src/api/subscriptions/schemas/cancelSubscriptionSchema.ts +8 -0
  169. package/src/api/subscriptions/schemas/changePlanSchema.ts +9 -0
  170. package/src/api/subscriptions/schemas/createSubscriptionSchema.ts +11 -0
  171. package/src/api/subscriptions/schemas/entitlementsSchema.ts +21 -0
  172. package/src/api/subscriptions/schemas/mrrSchema.ts +13 -0
  173. package/src/api/subscriptions/schemas/planDefinitionSchema.ts +71 -0
  174. package/src/api/subscriptions/schemas/planResourceSchema.ts +25 -0
  175. package/src/api/subscriptions/schemas/subscriptionEventResourceSchema.ts +8 -0
  176. package/src/api/subscriptions/schemas/subscriptionQuerySchema.ts +19 -0
  177. package/src/api/subscriptions/schemas/subscriptionResourceSchema.ts +6 -0
  178. package/src/api/subscriptions/schemas/subscriptionSettingsSchema.ts +32 -0
  179. package/src/api/subscriptions/schemas/subscriptionStatsSchema.ts +23 -0
  180. package/src/api/subscriptions/services/BillingService.ts +437 -0
  181. package/src/api/subscriptions/services/SubscriptionConfig.ts +56 -0
  182. package/src/api/subscriptions/services/SubscriptionService.ts +867 -0
  183. package/src/api/subscriptions/services/UsageService.ts +118 -0
  184. package/src/cache/core/__tests__/$cache.memory.spec.ts +450 -0
  185. package/src/cache/core/__tests__/$cache.swr.spec.ts +394 -0
  186. package/src/cache/core/index.ts +16 -0
  187. package/src/cache/core/primitives/$cache.ts +347 -21
  188. package/src/cli/core/tasks/BuildCloudflareTask.ts +16 -0
  189. package/src/cli/core/templates/agentMd.ts +39 -4
  190. package/src/cli/core/templates/biomeJson.ts +25 -1
  191. package/src/cli/core/templates/saasAdminLayoutTsx.ts +2 -2
  192. package/src/cli/platform/__tests__/CloudflareAdapter.spec.ts +117 -0
  193. package/src/cli/platform/adapters/CloudflareAdapter.ts +104 -7
  194. package/src/cli/platform/atoms/platformOptions.ts +13 -0
  195. package/src/cli/platform/schemas/platform.ts +1 -0
  196. package/src/cli/platform/services/CloudflareApi.ts +61 -0
  197. package/src/cli/platform/services/PlatformOrchestrator.ts +9 -4
  198. package/src/core/__tests__/$module.spec.ts +2 -2
  199. package/src/core/primitives/$module.ts +4 -4
  200. package/src/mcp/providers/McpServerProvider.ts +1 -1
  201. package/src/orm/core/providers/DatabaseTypeProvider.ts +9 -3
  202. package/src/orm/core/providers/drivers/DatabaseProvider.ts +1 -1
  203. package/src/orm/core/schemas/insertSchema.ts +10 -2
  204. package/src/orm/core/services/Repository.ts +27 -7
  205. package/src/react/form/hooks/useFormState.ts +8 -1
  206. package/src/react/form/index.ts +10 -1
  207. package/src/react/form/services/FormModel.ts +9 -3
  208. package/src/security/atoms/currentTenantAtom.ts +34 -0
  209. package/src/security/index.browser.ts +1 -0
  210. package/src/security/index.ts +12 -1
  211. package/src/security/primitives/$issuer.ts +17 -1
  212. package/src/security/providers/SecurityProvider.ts +37 -0
  213. package/src/server/auth/__tests__/validateRedirectUri.spec.ts +78 -0
  214. package/src/server/auth/providers/ServerAuthProvider.ts +21 -5
  215. package/tsconfig.base.json +2 -1
  216. package/dist/react/websocket/index.d.ts +0 -117
  217. package/dist/react/websocket/index.d.ts.map +0 -1
  218. package/dist/react/websocket/index.js +0 -108
  219. package/dist/react/websocket/index.js.map +0 -1
  220. package/dist/websocket/index.browser.js +0 -848
  221. package/dist/websocket/index.browser.js.map +0 -1
  222. package/dist/websocket/index.d.ts +0 -876
  223. package/dist/websocket/index.d.ts.map +0 -1
  224. package/dist/websocket/index.js +0 -1185
  225. package/dist/websocket/index.js.map +0 -1
  226. package/src/react/websocket/hooks/useRoom.tsx +0 -251
  227. package/src/react/websocket/index.ts +0 -7
  228. package/src/websocket/__tests__/$channel.spec.ts +0 -30
  229. package/src/websocket/__tests__/$websocket-new.spec.ts +0 -195
  230. package/src/websocket/__tests__/RoomManager.spec.ts +0 -146
  231. package/src/websocket/__tests__/websocket-integration.spec.ts +0 -951
  232. package/src/websocket/errors/WebSocketError.ts +0 -34
  233. package/src/websocket/index.browser.ts +0 -25
  234. package/src/websocket/index.shared.ts +0 -8
  235. package/src/websocket/index.ts +0 -85
  236. package/src/websocket/interfaces/WebSocketInterfaces.ts +0 -252
  237. package/src/websocket/primitives/$channel.ts +0 -131
  238. package/src/websocket/primitives/$websocket.ts +0 -107
  239. package/src/websocket/providers/NodeWebSocketServerProvider.ts +0 -617
  240. package/src/websocket/providers/WebSocketServerProvider.ts +0 -56
  241. package/src/websocket/services/RoomManager.ts +0 -160
  242. package/src/websocket/services/WebSocketClient.ts +0 -642
  243. package/src/websocket/services/WebSocketTopicService.ts +0 -108
@@ -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 * Delete many files in one round-trip per bucket. The database rows are\n * removed in a single `deleteMany`, and each affected bucket gets a single\n * `bucket.deleteMany` call (R2/S3 batch where supported).\n */\n public async deleteFiles(ids: string[]): Promise<string[]> {\n if (ids.length === 0) return [];\n\n const files = await this.fileRepository.findMany({\n where: { id: { inArray: ids } },\n columns: [\"id\", \"bucket\", \"blobId\"],\n });\n if (files.length === 0) return [];\n\n const dbDeleted = await this.fileRepository.deleteMany({\n id: { inArray: files.map((f) => f.id) },\n });\n\n const blobsByBucket = new Map<string, string[]>();\n for (const f of files) {\n const list = blobsByBucket.get(f.bucket) ?? [];\n list.push(f.blobId);\n blobsByBucket.set(f.bucket, list);\n }\n\n for (const [bucketName, blobIds] of blobsByBucket) {\n try {\n await this.bucket(bucketName).deleteMany(blobIds, true);\n } catch (e) {\n // DB rows already gone — log and continue. Orphaned blobs are\n // recoverable; orphaned DB rows would be worse.\n this.log.warn(\n `Failed to bulk-delete ${blobIds.length} files from bucket ${bucketName}`,\n e,\n );\n }\n }\n\n return dbDeleted.map(String);\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/delete - Delete many files in one request, batching the\n * underlying bucket calls per bucket (R2/S3 batch where supported).\n */\n public readonly deleteFiles = $action({\n method: \"POST\",\n path: `${this.url}/delete`,\n group: `admin:${this.group}`,\n use: [$secure({ permissions: [\"admin:file:delete\"] })],\n description: \"Delete many files\",\n schema: {\n body: t.object({\n ids: t.array(t.uuid(), { minItems: 1, maxItems: 1000 }),\n }),\n response: t.object({\n deleted: t.array(t.string()),\n }),\n },\n handler: async ({ body }) => {\n const deleted = await this.fileService.deleteFiles(body.ids);\n return { deleted };\n },\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;EACzB,QAAQ,EAAE,MAAM;EAChB,SAAS,EAAE,SAAS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 {"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 organizationId: db.organization(),\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 * Delete many files in one round-trip per bucket. The database rows are\n * removed in a single `deleteMany`, and each affected bucket gets a single\n * `bucket.deleteMany` call (R2/S3 batch where supported).\n */\n public async deleteFiles(ids: string[]): Promise<string[]> {\n if (ids.length === 0) return [];\n\n const files = await this.fileRepository.findMany({\n where: { id: { inArray: ids } },\n columns: [\"id\", \"bucket\", \"blobId\"],\n });\n if (files.length === 0) return [];\n\n const dbDeleted = await this.fileRepository.deleteMany({\n id: { inArray: files.map((f) => f.id) },\n });\n\n const blobsByBucket = new Map<string, string[]>();\n for (const f of files) {\n const list = blobsByBucket.get(f.bucket) ?? [];\n list.push(f.blobId);\n blobsByBucket.set(f.bucket, list);\n }\n\n for (const [bucketName, blobIds] of blobsByBucket) {\n try {\n await this.bucket(bucketName).deleteMany(blobIds, true);\n } catch (e) {\n // DB rows already gone — log and continue. Orphaned blobs are\n // recoverable; orphaned DB rows would be worse.\n this.log.warn(\n `Failed to bulk-delete ${blobIds.length} files from bucket ${bucketName}`,\n e,\n );\n }\n }\n\n return dbDeleted.map(String);\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/delete - Delete many files in one request, batching the\n * underlying bucket calls per bucket (R2/S3 batch where supported).\n */\n public readonly deleteFiles = $action({\n method: \"POST\",\n path: `${this.url}/delete`,\n group: `admin:${this.group}`,\n use: [$secure({ permissions: [\"admin:file:delete\"] })],\n description: \"Delete many files\",\n schema: {\n body: t.object({\n ids: t.array(t.uuid(), { minItems: 1, maxItems: 1000 }),\n }),\n response: t.object({\n deleted: t.array(t.string()),\n }),\n },\n handler: async ({ body }) => {\n const deleted = await this.fileService.deleteFiles(body.ids);\n return { deleted };\n },\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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E,MAAM;GACnB;EACD,SAAS,OAAO,EAAE,aAAa;GAC7B,OAAO,MAAM,KAAK,YAAY,WAAW,OAAO,GAAG;;EAEtD,CAAC;;;;ACvJJ,IAAa,WAAb,MAAsB;CACpB,cAAiC,QAAQ,YAAY;CAErD,aAA6B,WAAW;EACtC,MAAM;EACN,aAAa;EACb,MAAM;EACN,SAAS,YAAY;GACnB,MAAM,QAAQ,MAAM,KAAK,YAAY,kBAAkB;GAEvD,MAAM,QAAQ,IACZ,MAAM,KAAK,SAAS,KAAK,YAAY,WAAW,KAAK,GAAG,CAAC,CAC1D;;EAEJ,CAAC;;;;;;;;;;;;;;;AC0CJ,MAAa,iBAAiB,QAAQ;CACpC,MAAM;CACN,UAAU;EAAC;EAAgB;EAA0B;EAAU;EAAY;CAC3E,SAAS,CAAC,cAAc,iBAAiB;CAC1C,CAAC"}
@@ -58,6 +58,11 @@ const jobExecutionEntity = $entity({
58
58
  "status",
59
59
  "scheduledAt"
60
60
  ] },
61
+ { columns: [
62
+ "jobName",
63
+ "status",
64
+ "createdAt"
65
+ ] },
61
66
  { columns: ["jobName", "startedAt"] },
62
67
  {
63
68
  columns: ["jobName", "key"],
@@ -72,6 +77,7 @@ const jobConfig = $atom({
72
77
  description: "Configuration for the $job primitive.",
73
78
  schema: t.object({
74
79
  sweepCron: t.text({ description: "Cron expression for the sweep tick. Must be minute-granular at minimum (cron resolution). On Cloudflare Workers this expression is emitted into wrangler.jsonc by the build." }),
80
+ trimCron: t.text({ description: "Cron expression for the ring-buffer trim tick (per-job keepLastSuccess/keepLastError enforcement). Decoupled from `sweepCron` because trim is bounded by job execution rate, not retry latency — running it every sweep is wasted work for most apps." }),
75
81
  staleThreshold: t.integer({ description: "Pending age (ms) before the sweep re-dispatches it." }),
76
82
  runTimeout: t.integer({ description: "Running age (ms) before assumed crash (fallback when no per-job timeout)." }),
77
83
  keepLastSuccess: t.integer({ description: "Max successful rows to keep per job. Set 0 to disable and delete on success." }),
@@ -81,6 +87,7 @@ const jobConfig = $atom({
81
87
  }),
82
88
  default: {
83
89
  sweepCron: "*/5 * * * *",
90
+ trimCron: "0 * * * *",
84
91
  staleThreshold: 3e5,
85
92
  runTimeout: 18e5,
86
93
  keepLastSuccess: 10,
@@ -1 +1 @@
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 (or `scheduled` if `delay`/`scheduledAt` was given)\n * - worker claim → running\n * - success → ok (or row deleted, depending on `record` and `keepLastSuccess`)\n * - terminal failure → error\n * - retryable failure → scheduled (with scheduledAt = now; sweep picks it up)\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 sweepCron: t.text({\n description:\n \"Cron expression for the sweep tick. Must be minute-granular at minimum (cron resolution). On Cloudflare Workers this expression is emitted into wrangler.jsonc by the build.\",\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 sweepCron: \"*/5 * * * *\",\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\n/**\n * Public-facing schema for a job execution row.\n *\n * Diverges from the raw entity in two places, both for API ergonomics:\n *\n * - `priority` is exposed as the **string enum** (`critical`/`high`/...)\n * instead of the numeric value used internally for SQL ordering. The\n * `JobService` is responsible for the int → string transform.\n * - `can` derives the available admin actions from the row's status.\n */\nexport const jobExecutionResourceSchema = t.extend(\n jobExecutionEntity.schema,\n {\n priority: t.enum([\"critical\", \"high\", \"normal\", \"low\"]),\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\", \"direct\"], {\n description:\n \"Effective runtime mode. 'cron' = scheduled. 'queue' = push-driven, dispatched via AlephaApiJobsQueue. 'direct' = push-driven, processed in-process (no queue infrastructure loaded), with the sweep as the safety net.\",\n }),\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 }),\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,EAAE,EAAE;EAE9D,SAAS,GAAG,QAAQ,EAAE,SAAS,EAAE,EAAE;EACnC,aAAa,GAAG,QAAQ,EAAE,SAAS,EAAE,EAAE;EAEvC,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,KAAK,CAAC,CAAC;EAEhD,aAAa,EAAE,SAAS,EAAE,UAAU,CAAC;EACrC,WAAW,EAAE,SAAS,EAAE,UAAU,CAAC;EACnC,aAAa,EAAE,SAAS,EAAE,UAAU,CAAC;EAErC,OAAO,EAAE,SA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AE,OAC1C,mBAAmB,QACnB;CACE,UAAU,EAAE,KAAK;EAAC;EAAY;EAAQ;EAAU;EAAM,CAAC;CACvD,KAAK,EAAE,OAAO;EACZ,OAAO,EAAE,SAAS;EAClB,QAAQ,EAAE,SAAS;EACpB,CAAC;CACH,EACD;CACE,OAAO;CACP,aAAa;CACd,CACF;;;ACxBD,MAAa,wBAAwB,EAAE,OAAO;CAC5C,MAAM,EAAE,MAAM;CACd,aAAa,EAAE,SAAS,EAAE,MAAM,CAAC;CACjC,MAAM,EAAE,KAAK;EAAC;EAAQ;EAAS;EAAS,EAAE,EACxC,aACE,0NACH,CAAC;CACF,UAAU,EAAE,KAAK;EAAC;EAAY;EAAQ;EAAU;EAAM,CAAC;CACvD,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC;CAC1B,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC;CAC7B,OAAO,EAAE,SACP,EAAE,OAAO,EACP,SAAS,EAAE,SAAS,EACrB,CAAC,CACH;CACD,QAAQ,EAAE,OAAO;EACf,IAAI,EAAE,SAAS;EACf,OAAO,EAAE,SAAS;EAClB,SAAS,EAAE,SAAS,EAAE,UAAU,CAAC;EAClC,CAAC;CACH,CAAC;;;ACpBF,MAAa,mBAAmB,EAAE,OAAO,EACvC,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,KAAK,CAAC,CAAC,EACjD,CAAC;;;ACSF,MAAa,gBAAgB,QAAQ;CACnC,MAAM;CACN,UAAU,EAAE;CACb,CAAC;AAEF,MAAa,qBAAqB,QAAQ;CACxC,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 (or `scheduled` if `delay`/`scheduledAt` was given)\n * - worker claim → running\n * - success → ok (or row deleted, depending on `record` and `keepLastSuccess`)\n * - terminal failure → error\n * - retryable failure → scheduled (with scheduledAt = now; sweep picks it up)\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\", \"status\", \"createdAt\"] },\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 sweepCron: t.text({\n description:\n \"Cron expression for the sweep tick. Must be minute-granular at minimum (cron resolution). On Cloudflare Workers this expression is emitted into wrangler.jsonc by the build.\",\n }),\n trimCron: t.text({\n description:\n \"Cron expression for the ring-buffer trim tick (per-job keepLastSuccess/keepLastError enforcement). Decoupled from `sweepCron` because trim is bounded by job execution rate, not retry latency — running it every sweep is wasted work for most apps.\",\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 sweepCron: \"*/5 * * * *\",\n trimCron: \"0 * * * *\",\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\n/**\n * Public-facing schema for a job execution row.\n *\n * Diverges from the raw entity in two places, both for API ergonomics:\n *\n * - `priority` is exposed as the **string enum** (`critical`/`high`/...)\n * instead of the numeric value used internally for SQL ordering. The\n * `JobService` is responsible for the int → string transform.\n * - `can` derives the available admin actions from the row's status.\n */\nexport const jobExecutionResourceSchema = t.extend(\n jobExecutionEntity.schema,\n {\n priority: t.enum([\"critical\", \"high\", \"normal\", \"low\"]),\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\", \"direct\"], {\n description:\n \"Effective runtime mode. 'cron' = scheduled. 'queue' = push-driven, dispatched via AlephaApiJobsQueue. 'direct' = push-driven, processed in-process (no queue infrastructure loaded), with the sweep as the safety net.\",\n }),\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 }),\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,EAAE,EAAE;EAE9D,SAAS,GAAG,QAAQ,EAAE,SAAS,EAAE,EAAE;EACnC,aAAa,GAAG,QAAQ,EAAE,SAAS,EAAE,EAAE;EAEvC,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,KAAK,CAAC,CAAC;EAEhD,aAAa,EAAE,SAAS,EAAE,UAAU,CAAC;EACrC,WAAW,EAAE,SAAS,EAAE,UAAU,CAAC;EACnC,aAAa,EAAE,SAAS,EAAE,UAAU,CAAC;EAErC,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC;EAC3B,MAAM,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;EAEzC,aAAa,EAAE,SAAS,EAAE,MAAM,CAAC;EACjC,iBAAiB,EAAE,SAAS,EAAE,MAAM,CAAC;EACrC,aAAa,EAAE,SAAS,EAA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