@happyvertical/smrt-core 0.55.7 → 0.55.8

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 (203) hide show
  1. package/AGENTS.md +2 -1
  2. package/agents/browser-entry.md +44 -0
  3. package/agents/build-knowledge.md +7 -0
  4. package/agents/recipes.md +217 -0
  5. package/agents/revision-guard.md +72 -1
  6. package/dist/audit-context.d.ts.map +1 -1
  7. package/dist/audit-context.js +2 -2
  8. package/dist/audit-context.js.map +1 -1
  9. package/dist/browser.d.ts +2 -1
  10. package/dist/browser.d.ts.map +1 -1
  11. package/dist/browser.js +7 -7
  12. package/dist/cascade.d.ts +1 -1
  13. package/dist/cascade.d.ts.map +1 -1
  14. package/dist/cascade.js +1 -1
  15. package/dist/cascade.js.map +1 -1
  16. package/dist/change-feed.d.ts.map +1 -1
  17. package/dist/change-feed.js +1 -2
  18. package/dist/change-feed.js.map +1 -1
  19. package/dist/class.d.ts +1 -1
  20. package/dist/class.d.ts.map +1 -1
  21. package/dist/class.js +7 -3
  22. package/dist/class.js.map +1 -1
  23. package/dist/collection.d.ts.map +1 -1
  24. package/dist/collection.js +1 -1
  25. package/dist/collection.js.map +1 -1
  26. package/dist/consumer-plugin/index.js +2 -2
  27. package/dist/data-query.d.ts.map +1 -1
  28. package/dist/data-query.js +2 -13
  29. package/dist/data-query.js.map +1 -1
  30. package/dist/database.js +1 -1
  31. package/dist/database.js.map +1 -1
  32. package/dist/dispatch/bus.js +1 -1
  33. package/dist/dispatch/bus.js.map +1 -1
  34. package/dist/embedded-write-queue.d.ts +1 -1
  35. package/dist/embedded-write-queue.d.ts.map +1 -1
  36. package/dist/embedded-write-queue.js +7 -5
  37. package/dist/embedded-write-queue.js.map +1 -1
  38. package/dist/embeddings/hash.js +2 -2
  39. package/dist/embeddings/hash.js.map +1 -1
  40. package/dist/embeddings/storage.d.ts.map +1 -1
  41. package/dist/embeddings/storage.js +1 -2
  42. package/dist/embeddings/storage.js.map +1 -1
  43. package/dist/errors.d.ts.map +1 -1
  44. package/dist/errors.js +1 -0
  45. package/dist/errors.js.map +1 -1
  46. package/dist/generation-snapshot.js +1 -1
  47. package/dist/generators/index.js +1 -1
  48. package/dist/generators/mcp.js +3 -3
  49. package/dist/generators/preflight-route.js +1 -1
  50. package/dist/generators/rest.js +1 -1
  51. package/dist/generators.js +1 -1
  52. package/dist/host.browser.d.ts +12 -0
  53. package/dist/host.browser.d.ts.map +1 -0
  54. package/dist/host.browser.js +30 -0
  55. package/dist/host.browser.js.map +1 -0
  56. package/dist/host.d.ts +18 -0
  57. package/dist/host.d.ts.map +1 -0
  58. package/dist/host.js +15 -0
  59. package/dist/host.js.map +1 -0
  60. package/dist/index.d.ts +1 -0
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +10 -9
  63. package/dist/knowledge.d.ts.map +1 -1
  64. package/dist/knowledge.js +5 -4
  65. package/dist/knowledge.js.map +1 -1
  66. package/dist/manifest/browser-capability.generated.d.ts +14 -0
  67. package/dist/manifest/browser-capability.generated.d.ts.map +1 -0
  68. package/dist/manifest/browser-capability.generated.js +499 -0
  69. package/dist/manifest/browser-capability.generated.js.map +1 -0
  70. package/dist/manifest/discover-base-classes.js +1 -1
  71. package/dist/manifest/discover-smrt-packages.js +1 -1
  72. package/dist/manifest/generator.js +3 -3
  73. package/dist/manifest/index.js +2 -2
  74. package/dist/manifest/local-manifest-reader.d.ts +48 -0
  75. package/dist/manifest/local-manifest-reader.d.ts.map +1 -0
  76. package/dist/manifest/local-manifest-reader.js +81 -0
  77. package/dist/manifest/local-manifest-reader.js.map +1 -0
  78. package/dist/manifest/manager.d.ts +5 -28
  79. package/dist/manifest/manager.d.ts.map +1 -1
  80. package/dist/manifest/manager.js +10 -56
  81. package/dist/manifest/manager.js.map +1 -1
  82. package/dist/manifest/manifest-loader.d.ts +1 -1
  83. package/dist/manifest/manifest-loader.d.ts.map +1 -1
  84. package/dist/manifest/manifest-loader.js +43 -12
  85. package/dist/manifest/manifest-loader.js.map +1 -1
  86. package/dist/manifest/node-host.d.ts +38 -0
  87. package/dist/manifest/node-host.d.ts.map +1 -0
  88. package/dist/manifest/node-host.js +52 -0
  89. package/dist/manifest/node-host.js.map +1 -0
  90. package/dist/manifest/package-manifest-exports.js +1 -1
  91. package/dist/manifest/static-manifest.d.ts.map +1 -1
  92. package/dist/manifest/static-manifest.js +7 -2
  93. package/dist/manifest/static-manifest.js.map +1 -1
  94. package/dist/manifest/store.d.ts +2 -1
  95. package/dist/manifest/store.d.ts.map +1 -1
  96. package/dist/manifest/store.js +7 -4
  97. package/dist/manifest/store.js.map +1 -1
  98. package/dist/manifest.js +1 -1
  99. package/dist/manifest.json +9 -2
  100. package/dist/native-duckdb.d.ts +28 -0
  101. package/dist/native-duckdb.d.ts.map +1 -0
  102. package/dist/native-duckdb.js +51 -0
  103. package/dist/native-duckdb.js.map +1 -0
  104. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_md.js +169 -0
  105. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_md.js.map +1 -0
  106. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_u64.js +13 -0
  107. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_u64.js.map +1 -0
  108. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/sha2.js +198 -0
  109. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/sha2.js.map +1 -0
  110. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/utils.js +243 -0
  111. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/utils.js.map +1 -0
  112. package/dist/object.d.ts +56 -0
  113. package/dist/object.d.ts.map +1 -1
  114. package/dist/object.js +139 -16
  115. package/dist/object.js.map +1 -1
  116. package/dist/postgres-permissions.d.ts.map +1 -1
  117. package/dist/postgres-permissions.js +3 -3
  118. package/dist/postgres-permissions.js.map +1 -1
  119. package/dist/prebuild/index.js +1 -1
  120. package/dist/recipe-demo.d.ts +70 -0
  121. package/dist/recipe-demo.d.ts.map +1 -0
  122. package/dist/recipe-demo.js +130 -0
  123. package/dist/recipe-demo.js.map +1 -0
  124. package/dist/recipe.d.ts +64 -1
  125. package/dist/recipe.d.ts.map +1 -1
  126. package/dist/recipe.js +30 -0
  127. package/dist/recipe.js.map +1 -1
  128. package/dist/registry/class-registration.js +2 -2
  129. package/dist/registry/class-registration.js.map +1 -1
  130. package/dist/registry/db-cache-key.js +4 -5
  131. package/dist/registry/db-cache-key.js.map +1 -1
  132. package/dist/registry/inheritance-resolver.js +1 -1
  133. package/dist/registry/name-resolver.js +1 -1
  134. package/dist/registry/qualified-name-aliases.js +1 -1
  135. package/dist/registry/schema-builder.d.ts.map +1 -1
  136. package/dist/registry/schema-builder.js +3 -3
  137. package/dist/registry/schema-builder.js.map +1 -1
  138. package/dist/registry.d.ts.map +1 -1
  139. package/dist/registry.js +5 -8
  140. package/dist/registry.js.map +1 -1
  141. package/dist/revision-guard.js +1 -1
  142. package/dist/revision-guard.js.map +1 -1
  143. package/dist/scanner/manifest-generator.d.ts.map +1 -1
  144. package/dist/scanner/manifest-generator.js +19 -10
  145. package/dist/scanner/manifest-generator.js.map +1 -1
  146. package/dist/scanner/recipe-demo-pass.d.ts +14 -0
  147. package/dist/scanner/recipe-demo-pass.d.ts.map +1 -0
  148. package/dist/scanner/recipe-demo-pass.js +33 -0
  149. package/dist/scanner/recipe-demo-pass.js.map +1 -0
  150. package/dist/scanner/types.d.ts +7 -1
  151. package/dist/scanner/types.d.ts.map +1 -1
  152. package/dist/scanner/types.js.map +1 -1
  153. package/dist/schema/ddl/duckdb-strategy.d.ts.map +1 -1
  154. package/dist/schema/ddl/duckdb-strategy.js +1 -1
  155. package/dist/schema/ddl/duckdb-strategy.js.map +1 -1
  156. package/dist/schema/foreign-key-planner.d.ts.map +1 -1
  157. package/dist/schema/foreign-key-planner.js +1 -1
  158. package/dist/schema/foreign-key-planner.js.map +1 -1
  159. package/dist/schema/generator.d.ts.map +1 -1
  160. package/dist/schema/generator.js +10 -14
  161. package/dist/schema/generator.js.map +1 -1
  162. package/dist/schema/schema-aggregator.js +1 -1
  163. package/dist/scripts/browser-entry-evaluation.mjs +157 -0
  164. package/dist/smrt-knowledge.json +27 -12
  165. package/dist/system/browser.d.ts +16 -0
  166. package/dist/system/browser.d.ts.map +1 -0
  167. package/dist/system/browser.js +6 -0
  168. package/dist/system/index.d.ts +1 -6
  169. package/dist/system/index.d.ts.map +1 -1
  170. package/dist/system/index.js +2 -1
  171. package/dist/testing/database.js +1 -1
  172. package/dist/tools/index.js +1 -1
  173. package/dist/unchanged-indexed.d.ts +85 -0
  174. package/dist/unchanged-indexed.d.ts.map +1 -0
  175. package/dist/unchanged-indexed.js +219 -0
  176. package/dist/unchanged-indexed.js.map +1 -0
  177. package/dist/utils/async-context.d.ts +22 -0
  178. package/dist/utils/async-context.d.ts.map +1 -0
  179. package/dist/utils/async-context.js +27 -0
  180. package/dist/utils/async-context.js.map +1 -0
  181. package/dist/utils/import-project-vite.js +1 -1
  182. package/dist/utils/import-workspace-module.js +1 -1
  183. package/dist/utils/json.browser.d.ts +18 -0
  184. package/dist/utils/json.browser.d.ts.map +1 -0
  185. package/dist/utils/json.browser.js +47 -0
  186. package/dist/utils/json.browser.js.map +1 -0
  187. package/dist/utils/sha256.d.ts +15 -0
  188. package/dist/utils/sha256.d.ts.map +1 -0
  189. package/dist/utils/sha256.js +29 -0
  190. package/dist/utils/sha256.js.map +1 -0
  191. package/dist/vite-plugin/changes-route.js +1 -1
  192. package/dist/vite-plugin/dev-plane-route.js +1 -1
  193. package/dist/vite-plugin/events-route.js +1 -1
  194. package/dist/vite-plugin/import-build-aware.js +1 -1
  195. package/dist/vite-plugin/index.js +2 -2
  196. package/dist/vite-plugin/resources-route.js +1 -1
  197. package/dist/vite-plugin/sveltekit-generator.js +2 -2
  198. package/dist/vite-plugin/sveltekit-path.js +1 -1
  199. package/dist/vite-plugin/sveltekit-register-injection.js +1 -1
  200. package/dist/vite-plugin/sveltekit-route-coordinator.js +1 -1
  201. package/dist/vite-plugin/sync-apply-route.js +1 -1
  202. package/dist/vite-plugin/web-collections.js +2 -2
  203. package/package.json +21 -11
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Comprehensive error handling system for SMRT framework\n *\n * Provides specialized error types for different failure scenarios\n * with proper error codes, messages, and debugging information.\n */\n\n/**\n * Abstract base class for all SMRT framework errors.\n *\n * Adds a structured `code` (machine-readable string constant), a `category`\n * (coarse error domain), optional structured `details`, and an optional\n * causal `Error` chain on top of the standard `Error` class.\n *\n * Never throw `SmrtError` directly — use one of the concrete subclasses\n * (`DatabaseError`, `AIError`, `ValidationError`, etc.) or their static\n * factory methods for consistent error codes and messages.\n *\n * @example\n * ```typescript\n * try {\n * await product.save();\n * } catch (err) {\n * if (err instanceof ValidationError) {\n * console.error(err.code, err.details); // 'VALIDATION_REQUIRED_FIELD', { fieldName, objectType }\n * }\n * if (err instanceof SmrtError) {\n * logger.error(ErrorUtils.sanitizeError(err));\n * }\n * }\n * ```\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport { classifyDatabaseError } from './db-errors';\nimport { redactDatabaseUrl } from './utils/database-url.js';\n\nconst logger = createLogger({ level: 'info' });\n\nexport abstract class SmrtError extends Error {\n public readonly code: string;\n public readonly category:\n | 'database'\n | 'ai'\n | 'filesystem'\n | 'validation'\n | 'network'\n | 'configuration'\n | 'runtime';\n public readonly details?: Record<string, unknown>;\n public readonly cause?: Error;\n\n constructor(\n message: string,\n code: string,\n category: SmrtError['category'],\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n this.category = category;\n this.details = details;\n this.cause = cause;\n\n // Maintain proper stack trace for V8\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Converts error to a serializable object for logging/debugging\n */\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n category: this.category,\n details: this.details,\n stack: this.stack,\n cause: this.cause\n ? {\n name: this.cause.name,\n message: this.cause.message,\n stack: this.cause.stack,\n }\n : undefined,\n };\n }\n}\n\ntype ErrorLikeWithContext = Error & {\n cause?: unknown;\n context?: {\n originalError?: unknown;\n };\n};\n\nfunction collectErrorMessages(\n value: unknown,\n messages: string[],\n visited: Set<unknown>,\n depth = 0,\n): void {\n if (!value || visited.has(value) || depth > 10) {\n return;\n }\n\n visited.add(value);\n\n if (typeof value === 'string') {\n const trimmed = value.trim();\n if (trimmed) {\n messages.push(trimmed);\n }\n return;\n }\n\n if (!(value instanceof Error)) {\n return;\n }\n\n const message = value.message?.trim();\n if (message) {\n messages.push(message);\n }\n\n const errorWithContext = value as ErrorLikeWithContext;\n collectErrorMessages(\n errorWithContext.context?.originalError,\n messages,\n visited,\n depth + 1,\n );\n collectErrorMessages(errorWithContext.cause, messages, visited, depth + 1);\n}\n\nfunction getPrimaryCauseMessage(cause?: Error): {\n message?: string;\n messages?: string[];\n} {\n if (!cause) {\n return {};\n }\n\n const collected: string[] = [];\n collectErrorMessages(cause, collected, new Set<unknown>());\n\n const uniqueMessages = [...new Set(collected.filter(Boolean))];\n if (uniqueMessages.length === 0) {\n return {};\n }\n\n return {\n message: uniqueMessages[uniqueMessages.length - 1],\n messages: uniqueMessages,\n };\n}\n\n/**\n * Errors originating from database operations.\n *\n * Use the static factory methods rather than the constructor directly:\n * - `DatabaseError.connectionFailed(url, cause)` — DB connection failure\n * - `DatabaseError.queryFailed(query, cause)` — SQL execution error\n * - `DatabaseError.schemaError(table, op, cause)` — DDL/migration error\n * - `DatabaseError.constraintViolation(constraint, value, cause)` — FK/CHECK/UNIQUE\n * - `DatabaseError.corruptedData(field, class, cause)` — unparse-able column data\n * - `DatabaseError.missingDiscriminator(class, rowId)` — STI row missing `_meta_type`\n * - `DatabaseError.stiDiscriminatorConflict(...)` — legacy STI discriminator collides during qualification\n * - `DatabaseError.schemaMissing(table, class)` — table not yet migrated\n *\n * All errors have `category: 'database'` and codes prefixed with `DB_`.\n */\nexport class DatabaseError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'database', details, cause);\n }\n\n static connectionFailed(dbUrl: string, cause?: Error): DatabaseError {\n // Never carry the password into the message or details (#3527).\n const displayUrl = redactDatabaseUrl(dbUrl);\n return new DatabaseError(\n `Failed to connect to database: ${displayUrl}`,\n 'DB_CONNECTION_FAILED',\n { dbUrl: displayUrl },\n cause,\n );\n }\n\n static queryFailed(query: string, cause?: Error): DatabaseError {\n // Include the deepest actionable cause message for better debugging.\n const causeInfo = getPrimaryCauseMessage(cause);\n const causeMsg = causeInfo.message ? `\\nCause: ${causeInfo.message}` : '';\n return new DatabaseError(\n `Database query failed: ${query.substring(0, 100)}${query.length > 100 ? '...' : ''}${causeMsg}`,\n 'DB_QUERY_FAILED',\n {\n query,\n causeMessage: causeInfo.message,\n causeMessages: causeInfo.messages,\n },\n cause,\n );\n }\n\n static schemaError(\n tableName: string,\n operation: string,\n cause?: Error,\n ): DatabaseError {\n return new DatabaseError(\n `Schema operation failed for table '${tableName}': ${operation}`,\n 'DB_SCHEMA_ERROR',\n { tableName, operation },\n cause,\n );\n }\n\n static constraintViolation(\n constraint: string,\n value: unknown,\n cause?: Error,\n ): DatabaseError {\n return new DatabaseError(\n `Database constraint violation: ${constraint}`,\n 'DB_CONSTRAINT_VIOLATION',\n { constraint, value },\n cause,\n );\n }\n\n static corruptedData(\n fieldName: string,\n className: string,\n cause?: Error,\n ): DatabaseError {\n return new DatabaseError(\n `Corrupted data in field '${fieldName}' for ${className}. ` +\n `The data cannot be parsed or is malformed. ` +\n `This may indicate database corruption or incompatible schema changes.`,\n 'DB_CORRUPTED_DATA',\n { fieldName, className },\n cause,\n );\n }\n\n static missingDiscriminator(\n className: string,\n rowId?: string,\n ): DatabaseError {\n return new DatabaseError(\n `Missing discriminator (_meta_type) for STI class ${className}${rowId ? ` (row id: ${rowId})` : ''}. ` +\n `STI classes require a discriminator column to determine the correct subclass. ` +\n `This may indicate a schema mismatch or manual database modification.`,\n 'DB_MISSING_DISCRIMINATOR',\n { className, rowId },\n );\n }\n\n static stiDiscriminatorConflict(details: {\n className: string;\n tableName: string;\n id: string;\n slug: string;\n context: string;\n conflictIdentity: Record<string, unknown>;\n legacyMetaType: string;\n qualifiedMetaType: string;\n duplicateId: string;\n }): DatabaseError {\n const identityText = Object.entries(details.conflictIdentity)\n .map(([key, value]) => `${key} '${String(value)}'`)\n .join(', ');\n\n return new DatabaseError(\n `Legacy STI discriminator collision for ${details.className} (${details.tableName}). ` +\n `Row '${details.id}' would upgrade _meta_type from '${details.legacyMetaType}' to '${details.qualifiedMetaType}', ` +\n `but row '${details.duplicateId}' already uses the qualified discriminator for ${identityText || 'the same conflict identity'}. ` +\n `Merge or remove the duplicate legacy/qualified rows before saving.`,\n 'DB_STI_DISCRIMINATOR_CONFLICT',\n details,\n );\n }\n\n static schemaMissing(tableName: string, className: string): DatabaseError {\n return new DatabaseError(\n `Table '${tableName}' does not exist for class '${className}'. ` +\n `Run 'smrt db:migrate' to create database schema.`,\n 'DB_SCHEMA_MISSING',\n { tableName, className },\n );\n }\n}\n\n/**\n * Errors from AI provider integrations.\n *\n * Use the static factory methods:\n * - `AIError.providerError(provider, operation, cause)` — generic provider failure\n * - `AIError.rateLimitExceeded(provider, retryAfter)` — rate limit hit\n * - `AIError.invalidResponse(provider, response)` — unexpected response shape\n * - `AIError.authenticationFailed(provider)` — bad API key / credentials\n *\n * All errors have `category: 'ai'` and codes prefixed with `AI_`.\n * AI errors are considered retryable by `ErrorUtils.isRetryable()`.\n */\nexport class AIError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'ai', details, cause);\n }\n\n static providerError(\n provider: string,\n operation: string,\n cause?: Error,\n ): AIError {\n return new AIError(\n `AI provider '${provider}' failed during ${operation}`,\n 'AI_PROVIDER_ERROR',\n { provider, operation },\n cause,\n );\n }\n\n static rateLimitExceeded(provider: string, retryAfter?: number): AIError {\n return new AIError(\n `AI provider '${provider}' rate limit exceeded`,\n 'AI_RATE_LIMIT',\n { provider, retryAfter },\n );\n }\n\n static invalidResponse(provider: string, response: unknown): AIError {\n return new AIError(\n `AI provider '${provider}' returned invalid response`,\n 'AI_INVALID_RESPONSE',\n { provider, response },\n );\n }\n\n static authenticationFailed(provider: string): AIError {\n return new AIError(\n `AI provider '${provider}' authentication failed`,\n 'AI_AUTH_FAILED',\n { provider },\n );\n }\n}\n\n/**\n * Errors from filesystem operations.\n *\n * Use the static factory methods:\n * - `FilesystemError.fileNotFound(path)` — file does not exist\n * - `FilesystemError.permissionDenied(path, operation)` — access denied\n * - `FilesystemError.diskSpaceExceeded(path, requiredBytes)` — insufficient space\n *\n * All errors have `category: 'filesystem'` and codes prefixed with `FS_`.\n */\nexport class FilesystemError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'filesystem', details, cause);\n }\n\n static fileNotFound(path: string): FilesystemError {\n return new FilesystemError(`File not found: ${path}`, 'FS_FILE_NOT_FOUND', {\n path,\n });\n }\n\n static permissionDenied(path: string, operation: string): FilesystemError {\n return new FilesystemError(\n `Permission denied for ${operation} on: ${path}`,\n 'FS_PERMISSION_DENIED',\n { path, operation },\n );\n }\n\n static diskSpaceExceeded(\n path: string,\n requiredBytes: number,\n ): FilesystemError {\n return new FilesystemError(\n `Insufficient disk space for operation on: ${path}`,\n 'FS_DISK_SPACE_EXCEEDED',\n { path, requiredBytes },\n );\n }\n}\n\n/**\n * Input/data validation errors thrown before or during a database operation.\n *\n * `save()` throws `ValidationError` when field validation fails. The collection's\n * `convertWhereKeys()` throws it for invalid WHERE clause operators or field names.\n * `ValidationError` is **not** retried by `ErrorUtils.withRetry()`.\n *\n * Use the static factory methods:\n * - `ValidationError.requiredField(field, objectType)` — missing required field\n * - `ValidationError.invalidValue(field, value, expected)` — wrong type/format\n * - `ValidationError.uniqueConstraint(field, value)` — duplicate unique value\n * - `ValidationError.rangeError(field, value, min?, max?)` — out of allowed range\n *\n * All errors have `category: 'validation'` and codes prefixed with `VALIDATION_`.\n */\nexport class ValidationError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'validation', details, cause);\n }\n\n static requiredField(fieldName: string, objectType: string): ValidationError {\n return new ValidationError(\n `Required field '${fieldName}' is missing for ${objectType}`,\n 'VALIDATION_REQUIRED_FIELD',\n { fieldName, objectType },\n );\n }\n\n static invalidValue(\n fieldName: string,\n value: unknown,\n expectedType: string,\n ): ValidationError {\n return new ValidationError(\n `Invalid value for field '${fieldName}': expected ${expectedType}, got ${typeof value}`,\n 'VALIDATION_INVALID_VALUE',\n { fieldName, value, expectedType },\n );\n }\n\n static uniqueConstraint(fieldName: string, value: unknown): ValidationError {\n return new ValidationError(\n `Unique constraint violation for field '${fieldName}' with value: ${String(value)}`,\n 'VALIDATION_UNIQUE_CONSTRAINT',\n { fieldName, value },\n );\n }\n\n static rangeError(\n fieldName: string,\n value: number,\n min?: number,\n max?: number,\n ): ValidationError {\n const range =\n min !== undefined && max !== undefined\n ? `between ${min} and ${max}`\n : min !== undefined\n ? `>= ${min}`\n : `<= ${max}`;\n\n return new ValidationError(\n `Value for field '${fieldName}' must be ${range}, got: ${value}`,\n 'VALIDATION_RANGE_ERROR',\n { fieldName, value, min, max },\n );\n }\n}\n\n/**\n * Errors from HTTP and external network operations.\n *\n * Use the static factory methods:\n * - `NetworkError.requestFailed(url, status?, body?)` — non-2xx response or connection failure\n * - `NetworkError.timeout(url, timeoutMs)` — request exceeded timeout\n * - `NetworkError.serviceUnavailable(service, reason?)` — external service down\n *\n * All errors have `category: 'network'` and codes prefixed with `NETWORK_`.\n * Network errors are considered retryable by `ErrorUtils.isRetryable()`.\n */\nexport class NetworkError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'network', details, cause);\n }\n\n static requestFailed(\n url: string,\n status?: number,\n responseBody?: string | Error,\n ): NetworkError {\n const cause = responseBody instanceof Error ? responseBody : undefined;\n const body = typeof responseBody === 'string' ? responseBody : undefined;\n return new NetworkError(\n `Network request failed: ${url}${status ? ` (Status: ${status})` : ''}${body ? ` - ${body.substring(0, 200)}` : ''}`,\n 'NETWORK_REQUEST_FAILED',\n { url, status, responseBody: body },\n cause,\n );\n }\n\n static timeout(url: string, timeoutMs: number): NetworkError {\n return new NetworkError(\n `Network request timed out after ${timeoutMs}ms: ${url}`,\n 'NETWORK_TIMEOUT',\n { url, timeoutMs },\n );\n }\n\n static serviceUnavailable(service: string, reason?: string): NetworkError {\n return new NetworkError(\n reason\n ? `External service unavailable: ${service} - ${reason}`\n : `External service unavailable: ${service}`,\n 'NETWORK_SERVICE_UNAVAILABLE',\n { service, reason },\n );\n }\n}\n\n/**\n * Errors from misconfigured or incompatible class/framework setup.\n *\n * These are typically thrown during class registration (i.e. at module load time),\n * not during normal request handling.\n *\n * Use the static factory methods:\n * - `ConfigurationError.missingConfiguration(key, context?)` — missing required config\n * - `ConfigurationError.invalidConfiguration(key, value, expected)` — wrong config type/value\n * - `ConfigurationError.initializationFailed(component, cause?)` — component failed to start\n * - `ConfigurationError.circularInheritance(class, chain)` — circular class inheritance\n * - `ConfigurationError.incompatibleStrategy(class, strategy, parent, parentStrategy)` — STI mismatch\n * - `ConfigurationError.unregisteredBaseClass(child, base)` — STI base not yet registered\n *\n * All errors have `category: 'configuration'` and codes prefixed with `CONFIG_`.\n * Configuration errors are **not** retried by `ErrorUtils.withRetry()`.\n */\nexport class ConfigurationError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'configuration', details, cause);\n }\n\n static missingConfiguration(\n configKey: string,\n context?: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `Missing required configuration: ${configKey}${context ? ` in ${context}` : ''}`,\n 'CONFIG_MISSING',\n { configKey, context },\n );\n }\n\n static invalidConfiguration(\n configKey: string,\n value: unknown,\n expected: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `Invalid configuration for ${configKey}: expected ${expected}, got ${typeof value}`,\n 'CONFIG_INVALID',\n { configKey, value, expected },\n );\n }\n\n static initializationFailed(\n component: string,\n cause?: Error,\n ): ConfigurationError {\n return new ConfigurationError(\n `Failed to initialize component: ${component}`,\n 'CONFIG_INIT_FAILED',\n { component },\n cause,\n );\n }\n\n static circularInheritance(\n className: string,\n inheritanceChain: string[],\n ): ConfigurationError {\n return new ConfigurationError(\n `Circular inheritance detected for class '${className}'. ` +\n `Inheritance chain: ${inheritanceChain.join(' → ')} → ${className}. ` +\n `Classes cannot inherit from themselves directly or indirectly.`,\n 'CONFIG_CIRCULAR_INHERITANCE',\n { className, inheritanceChain },\n );\n }\n\n static incompatibleStrategy(\n className: string,\n classStrategy: string,\n parentClass: string,\n parentStrategy: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `Incompatible table strategy for class '${className}' (${classStrategy}). ` +\n `Parent class '${parentClass}' uses ${parentStrategy} strategy. ` +\n `Child classes must use the same table strategy as their parent. ` +\n `Either change ${className} to use ${parentStrategy}, or remove the inheritance.`,\n 'CONFIG_INCOMPATIBLE_STRATEGY',\n { className, classStrategy, parentClass, parentStrategy },\n );\n }\n\n static unregisteredBaseClass(\n childClass: string,\n baseClass: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `STI base class '${baseClass}' is not registered for child class '${childClass}'. ` +\n `When using Single Table Inheritance, the base class must be registered before any child classes. ` +\n `Ensure ${baseClass} is decorated with @smrt({ tableStrategy: 'sti' }) and imported before ${childClass}.`,\n 'CONFIG_UNREGISTERED_BASE',\n { childClass, baseClass },\n );\n }\n}\n\n/**\n * Errors representing unexpected runtime failures not covered by other categories.\n *\n * `RuntimeError` is the catch-all for internal framework errors — invalid object\n * state, exhausted resources, or failures in operations like `save()` and `loadFromId()`\n * that propagate from an unknown cause.\n *\n * Use the static factory methods:\n * - `RuntimeError.operationFailed(operation, context?, cause?)` — generic operation failure\n * - `RuntimeError.invalidState(message, context?)` — unexpected object/system state\n * - `RuntimeError.resourceExhausted(resource, limit)` — limit exceeded (e.g. connections)\n *\n * All errors have `category: 'runtime'` and codes prefixed with `RUNTIME_`.\n */\nexport class RuntimeError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'runtime', details, cause);\n }\n\n static operationFailed(\n operation: string,\n context?: string,\n cause?: Error,\n ): RuntimeError {\n return new RuntimeError(\n `Operation failed: ${operation}${context ? ` in ${context}` : ''}`,\n 'RUNTIME_OPERATION_FAILED',\n { operation, context },\n cause,\n );\n }\n\n static invalidState(\n message: string,\n context?: Record<string, unknown>,\n ): RuntimeError {\n return new RuntimeError(message, 'RUNTIME_INVALID_STATE', context);\n }\n\n static resourceExhausted(resource: string, limit: number): RuntimeError {\n return new RuntimeError(\n `Resource exhausted: ${resource} exceeded limit of ${limit}`,\n 'RUNTIME_RESOURCE_EXHAUSTED',\n { resource, limit },\n );\n }\n}\n\n/**\n * Error thrown when a tenant isolation boundary is crossed while resolving a\n * relationship.\n *\n * Raised by {@link SmrtObject.loadRelated} / {@link SmrtObject.loadRelatedMany}\n * (and {@link SmrtObject.getRelated}, which delegates to them) when a\n * tenant-scoped object resolves a relationship to an object belonging to a\n * *different*, non-null tenant — the genuine cross-tenant data leak. The guard\n * is a no-op when either side has a `null` tenant (global / non-tenant-scoped\n * models) and when both sides share the same tenant, so it only fires on real\n * leaks. Pass `{ allowCrossTenant: true }` to the loader to deliberately opt out.\n *\n * The `code` is always `'TENANT_ISOLATION_VIOLATION'` and the category is\n * `'validation'`. It is never retried — `ErrorUtils.withRetry()` rethrows it\n * immediately and `ErrorUtils.isRetryable()` returns `false` — because a tenant\n * boundary violation is deterministic. `tenantId` is the owning object's tenant\n * and `attemptedTenantId` is the tenant of the object that was reached.\n *\n * This shares its stable `code`, `name`, `tenantId`, and `attemptedTenantId`\n * shape with the interceptor-level `TenantIsolationError` in\n * `@happyvertical/smrt-tenancy`, so cross-cutting handlers can match either via\n * `err.code === 'TENANT_ISOLATION_VIOLATION'`. They are intentionally distinct\n * classes because `@happyvertical/smrt-core` cannot depend on the tenancy\n * package (the dependency runs the other way).\n *\n * @example\n * ```typescript\n * try {\n * await order.loadRelated('customerId');\n * } catch (err) {\n * if (err instanceof TenantIsolationError) {\n * // err.tenantId — the order's tenant\n * // err.attemptedTenantId — the customer's tenant\n * }\n * }\n * ```\n *\n * @see SmrtObject.loadRelated\n * @see SmrtObject.loadRelatedMany\n */\nexport class TenantIsolationError extends SmrtError {\n /** The tenant ID of the object that owns the relationship. */\n public readonly tenantId?: string;\n /** The tenant ID of the related object that was reached (and rejected). */\n public readonly attemptedTenantId?: string;\n\n constructor(\n message: string,\n details?: {\n tenantId?: string;\n attemptedTenantId?: string;\n [key: string]: unknown;\n },\n cause?: Error,\n ) {\n super(message, 'TENANT_ISOLATION_VIOLATION', 'validation', details, cause);\n this.tenantId = details?.tenantId;\n this.attemptedTenantId = details?.attemptedTenantId;\n }\n\n /**\n * Builds a {@link TenantIsolationError} for a blocked cross-tenant\n * relationship resolution, with a descriptive message and structured details.\n */\n static crossTenantReference(details: {\n sourceClass: string;\n fieldName: string;\n sourceTenantId: string;\n targetClass?: string;\n targetTenantId: string;\n }): TenantIsolationError {\n const target = details.targetClass\n ? `${details.targetClass} (tenant '${details.targetTenantId}')`\n : `tenant '${details.targetTenantId}'`;\n return new TenantIsolationError(\n `Cross-tenant relationship access blocked on ${details.sourceClass}.${details.fieldName}: ` +\n `owning tenant '${details.sourceTenantId}' does not match ${target}. ` +\n `Pass { allowCrossTenant: true } to loadRelated()/loadRelatedMany()/getRelated() to override.`,\n {\n tenantId: details.sourceTenantId,\n attemptedTenantId: details.targetTenantId,\n sourceClass: details.sourceClass,\n fieldName: details.fieldName,\n targetClass: details.targetClass,\n },\n );\n }\n\n /**\n * Builds a {@link TenantIsolationError} for a natural-key save whose\n * conflict target matched a row owned by a different tenant (or a global\n * row, or — for a global save — a tenant's row). `save()` refuses instead of\n * letting `ON CONFLICT … DO UPDATE` rewrite that row's `id` and tenant.\n *\n * The other row's owner is deliberately NOT reported: naming it would\n * disclose another tenant's identity to the caller. Only the caller's own\n * values appear in the message and details.\n */\n static naturalKeyOwnedElsewhere(details: {\n className: string;\n tableName: string;\n conflictColumns: string[];\n conflictValues: Record<string, unknown>;\n ownershipColumns: string[];\n tenantId?: string | null;\n }): TenantIsolationError {\n const key = details.conflictColumns\n .map(\n (column) =>\n `${column}=${JSON.stringify(details.conflictValues[column] ?? null)}`,\n )\n .join(', ');\n return new TenantIsolationError(\n `Refusing to save ${details.className}: its natural key (${key}) on ` +\n `\"${details.tableName}\" already belongs to a row with a different owner ` +\n `(${details.ownershipColumns.join(', ')}). Saving would overwrite that row's ` +\n `id and owner. Give the table a tenant-inclusive unique key ` +\n `(declare tenant scope, or drop the explicit conflictColumns that omit ` +\n `the tenant column, then run \\`smrt db:migrate\\`), or choose another natural key.`,\n {\n tenantId: details.tenantId ?? undefined,\n className: details.className,\n tableName: details.tableName,\n conflictColumns: details.conflictColumns,\n ownershipColumns: details.ownershipColumns,\n reason: 'natural_key_owned_elsewhere',\n },\n );\n }\n}\n\n/**\n * Error thrown by `runOnce()` (`./run-once.ts`, #3080) when a submission's\n * claim cannot be resolved to a definite, replayable result.\n *\n * Mirrors the \"refused vs unknown outcome\" distinction #2990 drew for\n * `AssistantDock` actions:\n * - `RUN_ONCE_IN_FLIGHT` — a claim for this key exists and has not completed.\n * This is a definite decision, not an unknown one: some execution currently\n * holds the key. Retry later with the SAME token and content — minting a\n * fresh token would create an unrelated claim and defeat the guard.\n * - `RUN_ONCE_OUTCOME_UNKNOWN` — the claim insert reported a conflict but no\n * claim row could be read back. Genuinely indeterminate: retrying with the\n * SAME token and content is still safe (a completed claim replays; anything\n * else runs as a fresh attempt), but the caller must not treat this as\n * either success or failure.\n *\n * Both are `category: 'runtime'` and neither is retried automatically —\n * `runOnce()` never loops on them, because only the caller knows whether\n * retrying inline is appropriate for its own request (a SvelteKit action may\n * prefer to tell the user \"still processing\" over blocking on a retry loop).\n */\nexport class RunOnceClaimError extends SmrtError {\n /** The derived claim key this error concerns. */\n public readonly claimKey: string;\n\n constructor(\n message: string,\n code: 'RUN_ONCE_IN_FLIGHT' | 'RUN_ONCE_OUTCOME_UNKNOWN',\n claimKey: string,\n ) {\n super(message, code, 'runtime', { claimKey });\n this.claimKey = claimKey;\n }\n\n static inFlight(claimKey: string): RunOnceClaimError {\n return new RunOnceClaimError(\n `runOnce: claim \"${claimKey}\" is already in flight. Retry later with ` +\n `the same token and content — do not mint a new token.`,\n 'RUN_ONCE_IN_FLIGHT',\n claimKey,\n );\n }\n\n static outcomeUnknown(claimKey: string): RunOnceClaimError {\n return new RunOnceClaimError(\n `runOnce: outcome for claim \"${claimKey}\" is unknown. Retrying with ` +\n `the same token and content is safe, but do not treat this as ` +\n `either success or failure.`,\n 'RUN_ONCE_OUTCOME_UNKNOWN',\n claimKey,\n );\n }\n}\n\n/**\n * Utility functions for error handling\n */\nexport class ErrorUtils {\n /**\n * Wraps a function with error handling and automatic retry logic.\n *\n * Retries are for failures a later attempt might survive. An error is\n * rethrown immediately, with no backoff, when it is:\n *\n * - a {@link ValidationError} or {@link ConfigurationError} — the input is\n * wrong, and the same input will be wrong next time;\n * - a {@link TenantIsolationError} — a security boundary, and deterministic;\n * - a **deterministic database failure** (#2366), classified through the\n * driver-error cause chain by {@link classifyDatabaseError}: constraint\n * violations, invalid input syntax, missing tables/columns, and statements\n * issued inside an already-aborted PostgreSQL transaction (`25P02`).\n *\n * The database check matters because `@happyvertical/sql` wraps every driver\n * error as `DatabaseError('Failed to upsert record into table', …)`, hiding\n * the constraint wording from `error.message`. Without it, a unique-key\n * collision burned the full 500 + 1000 + 2000 ms backoff and — inside a\n * caller-managed transaction — replaced the real cause with\n * `25P02 current transaction is aborted` on the way out.\n *\n * Errors the classifier has no opinion about (`kind: 'unknown'`) keep the\n * original permissive behavior and are retried.\n */\n static async withRetry<T>(\n operation: () => Promise<T>,\n maxRetries = 3,\n delay = 1000,\n backoffMultiplier = 2,\n ): Promise<T> {\n let lastError: Error = new Error('Operation failed without error details');\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n if (attempt === maxRetries) {\n throw lastError;\n }\n\n // Skip retry for certain error types. A tenant isolation violation is\n // deterministic — retrying re-fetches the same cross-tenant target — and\n // is a security boundary, so it must never be retried.\n if (\n error instanceof ValidationError ||\n error instanceof ConfigurationError ||\n error instanceof TenantIsolationError\n ) {\n throw error;\n }\n\n // A deterministic database failure cannot be retried into success, and\n // retrying it inside a transaction actively destroys evidence: every\n // later attempt runs on the aborted client and reports `25P02` instead\n // of the constraint that actually failed (#2366).\n if (classifyDatabaseError(error).deterministic) {\n throw lastError;\n }\n\n // Wait before retrying with exponential backoff\n // Wrap in try-catch to handle any potential timer errors\n try {\n await new Promise<void>((resolve) => {\n setTimeout(() => resolve(), delay * backoffMultiplier ** attempt);\n });\n } catch (timerError) {\n // Log timer error but don't fail the retry\n logger.error('Timer error during retry', { error: timerError });\n }\n }\n }\n\n throw lastError;\n }\n\n /**\n * Checks if an error is retryable.\n *\n * A database failure is classified through its driver-error cause chain\n * first (#2366), so a wrapped `40001 serialization_failure` or `SQLITE_BUSY`\n * reports retryable while a wrapped `23505 unique_violation` does not —\n * neither of which the `category === 'database'` test alone could tell\n * apart. Only when the chain yields no opinion do the original\n * category/message heuristics apply.\n */\n static isRetryable(error: Error): boolean {\n const databaseClassification = classifyDatabaseError(error);\n if (databaseClassification.kind !== 'unknown') {\n return databaseClassification.retryable;\n }\n\n if (error instanceof SmrtError) {\n return error.category === 'network' || error.category === 'ai';\n }\n\n // Check for common retryable error patterns\n const retryablePatterns = [\n /ECONNRESET/,\n /ETIMEDOUT/,\n /ENOTFOUND/,\n /rate.?limit/i,\n /timeout/i,\n /503/,\n /502/,\n /500/,\n ];\n\n return retryablePatterns.some((pattern) => pattern.test(error.message));\n }\n\n /**\n * Sanitizes an error for safe logging (removes sensitive information)\n */\n static sanitizeError(error: Error): Record<string, unknown> {\n const sanitized: Record<string, unknown> = {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n\n if (error instanceof SmrtError) {\n sanitized.code = error.code;\n sanitized.category = error.category;\n\n // Sanitize details to remove potential sensitive information\n if (error.details) {\n const details: Record<string, unknown> = { ...error.details };\n sanitized.details = details;\n\n // Remove common sensitive fields\n const sensitiveFields = [\n 'password',\n 'token',\n 'key',\n 'secret',\n 'apiKey',\n ];\n for (const field of sensitiveFields) {\n if (details[field]) {\n details[field] = '[REDACTED]';\n }\n }\n }\n }\n\n return sanitized;\n }\n}\n\n/**\n * Validation report that collects multiple validation errors\n *\n * Useful for validating an entire object and reporting all errors\n * at once rather than stopping at the first error.\n *\n * @example\n * ```typescript\n * const report = new ValidationReport('Product');\n * report.addError(ValidationError.requiredField('name', 'Product'));\n * report.addError(ValidationError.rangeError('price', -10, 0));\n *\n * if (report.hasErrors()) {\n * console.error(report.toString());\n * // Output:\n * // Validation failed for Product with 2 errors:\n * // - name: Required field 'name' is missing for Product\n * // - price: Value -10 for field 'price' is outside allowed range [0, undefined]\n * }\n * ```\n */\nexport class ValidationReport {\n private errors: ValidationError[] = [];\n private objectType: string;\n\n constructor(objectType: string) {\n this.objectType = objectType;\n }\n\n /**\n * Add a validation error to the report\n */\n addError(error: ValidationError): void {\n this.errors.push(error);\n }\n\n /**\n * Check if there are any validation errors\n */\n hasErrors(): boolean {\n return this.errors.length > 0;\n }\n\n /**\n * Get all validation errors\n */\n getErrors(): ValidationError[] {\n return [...this.errors];\n }\n\n /**\n * Get the number of validation errors\n */\n getErrorCount(): number {\n return this.errors.length;\n }\n\n /**\n * Convert to a human-readable string\n */\n toString(): string {\n if (this.errors.length === 0) {\n return `Validation passed for ${this.objectType}`;\n }\n\n const errorList = this.errors\n .map((err, idx) => ` ${idx + 1}. ${err.message}`)\n .join('\\n');\n\n return `Validation failed for ${this.objectType} with ${this.errors.length} error(s):\\n${errorList}`;\n }\n\n /**\n * Convert to JSON format\n */\n toJSON(): object {\n return {\n objectType: this.objectType,\n errorCount: this.errors.length,\n errors: this.errors.map((err) => err.toJSON()),\n };\n }\n\n /**\n * Throw the first error if there are any errors\n */\n throwIfErrors(): void {\n if (this.errors.length > 0) {\n throw this.errors[0];\n }\n }\n\n /**\n * Clear all errors\n */\n clear(): void {\n this.errors = [];\n }\n}\n\n/**\n * Validation utility functions\n */\nexport class ValidationUtils {\n /**\n * Validate a single field value\n *\n * @param fieldName - Name of the field\n * @param value - Value to validate\n * @param options - Validation options (required, min, max, etc.)\n * @returns ValidationError if validation fails, null otherwise\n */\n static async validateField(\n fieldName: string,\n value: unknown,\n options: {\n required?: boolean;\n min?: number;\n max?: number;\n minLength?: number;\n maxLength?: number;\n pattern?: string | RegExp;\n type?: string;\n customValidator?: (value: unknown) => boolean | Promise<boolean>;\n customMessage?: string;\n },\n objectType: string = 'Object',\n ): Promise<ValidationError | null> {\n // Required check\n if (\n options.required &&\n (value === null || value === undefined || value === '')\n ) {\n return ValidationError.requiredField(fieldName, objectType);\n }\n\n // Skip further validation if value is null/undefined and not required\n if (value === null || value === undefined) {\n return null;\n }\n\n // Numeric range validation\n if (typeof value === 'number') {\n if (options.min !== undefined && value < options.min) {\n return ValidationError.rangeError(\n fieldName,\n value,\n options.min,\n options.max,\n );\n }\n if (options.max !== undefined && value > options.max) {\n return ValidationError.rangeError(\n fieldName,\n value,\n options.min,\n options.max,\n );\n }\n }\n\n // String length validation\n if (typeof value === 'string') {\n if (options.minLength !== undefined && value.length < options.minLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with minimum length ${options.minLength}`,\n );\n }\n if (options.maxLength !== undefined && value.length > options.maxLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with maximum length ${options.maxLength}`,\n );\n }\n\n // Pattern validation\n if (options.pattern) {\n const regex =\n typeof options.pattern === 'string'\n ? new RegExp(options.pattern)\n : options.pattern;\n if (!regex.test(value)) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string matching pattern ${options.pattern}`,\n );\n }\n }\n }\n\n // Custom validator\n if (options.customValidator) {\n try {\n const isValid = await options.customValidator(value);\n if (!isValid) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n options.customMessage || 'custom validation failed',\n );\n }\n } catch (error) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `custom validation error: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return null;\n }\n\n /**\n * Validate required field\n */\n static validateRequired(\n fieldName: string,\n value: unknown,\n objectType: string = 'Object',\n ): ValidationError | null {\n if (value === null || value === undefined || value === '') {\n return ValidationError.requiredField(fieldName, objectType);\n }\n return null;\n }\n\n /**\n * Validate numeric range\n */\n static validateRange(\n fieldName: string,\n value: number,\n min?: number,\n max?: number,\n ): ValidationError | null {\n if (min !== undefined && value < min) {\n return ValidationError.rangeError(fieldName, value, min, max);\n }\n if (max !== undefined && value > max) {\n return ValidationError.rangeError(fieldName, value, min, max);\n }\n return null;\n }\n\n /**\n * Validate string length\n */\n static validateLength(\n fieldName: string,\n value: string,\n minLength?: number,\n maxLength?: number,\n ): ValidationError | null {\n if (minLength !== undefined && value.length < minLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with minimum length ${minLength}`,\n );\n }\n if (maxLength !== undefined && value.length > maxLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with maximum length ${maxLength}`,\n );\n }\n return null;\n }\n\n /**\n * Validate string pattern\n */\n static validatePattern(\n fieldName: string,\n value: string,\n pattern: string | RegExp,\n ): ValidationError | null {\n const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern;\n if (!regex.test(value)) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string matching pattern ${pattern}`,\n );\n }\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;AAE7C,IAAsB,YAAtB,cAAwC,MAAM;CAC5C;CACA;CAQA;CACA;CAEA,YACE,SACA,MACA,UACA,SACA,OACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO,KAAK,YAAY;EAC7B,KAAK,OAAO;EACZ,KAAK,WAAW;EAChB,KAAK,UAAU;EACf,KAAK,QAAQ;EAGb,IAAI,MAAM,mBACR,MAAM,kBAAkB,MAAM,KAAK,WAAW;CAElD;;;;CAKA,SAAS;EACP,OAAO;GACL,MAAM,KAAK;GACX,SAAS,KAAK;GACd,MAAM,KAAK;GACX,UAAU,KAAK;GACf,SAAS,KAAK;GACd,OAAO,KAAK;GACZ,OAAO,KAAK,QACR;IACE,MAAM,KAAK,MAAM;IACjB,SAAS,KAAK,MAAM;IACpB,OAAO,KAAK,MAAM;GACpB,IACA,KAAA;EACN;CACF;AACF;AASA,SAAS,qBACP,OACA,UACA,SACA,QAAQ,GACF;CACN,IAAI,CAAC,SAAS,QAAQ,IAAI,KAAK,KAAK,QAAQ,IAC1C;CAGF,QAAQ,IAAI,KAAK;CAEjB,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,UAAU,MAAM,KAAK;EAC3B,IAAI,SACF,SAAS,KAAK,OAAO;EAEvB;CACF;CAEA,IAAI,EAAE,iBAAiB,QACrB;CAGF,MAAM,UAAU,MAAM,SAAS,KAAK;CACpC,IAAI,SACF,SAAS,KAAK,OAAO;CAGvB,MAAM,mBAAmB;CACzB,qBACE,iBAAiB,SAAS,eAC1B,UACA,SACA,QAAQ,CACV;CACA,qBAAqB,iBAAiB,OA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AAI,QAAQ,KAAA,KAAa,QAAQ,KAC/B,OAAO,gBAAgB,WAAW,WAAW,OAAO,KAAK,GAAG;EAE9D,OAAO;CACT;;;;CAKA,OAAO,eACL,WACA,OACA,WACA,WACwB;EACxB,IAAI,cAAc,KAAA,KAAa,MAAM,SAAS,WAC5C,OAAO,gBAAgB,aACrB,WACA,OACA,8BAA8B,WAChC;EAEF,IAAI,cAAc,KAAA,KAAa,MAAM,SAAS,WAC5C,OAAO,gBAAgB,aACrB,WACA,OACA,8BAA8B,WAChC;EAEF,OAAO;CACT;;;;CAKA,OAAO,gBACL,WACA,OACA,SACwB;EAExB,IAAI,EADU,OAAO,YAAY,WAAW,IAAI,OAAO,OAAO,IAAI,QAAA,CACvD,KAAK,KAAK,GACnB,OAAO,gBAAgB,aACrB,WACA,OACA,2BAA2B,SAC7B;EAEF,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Comprehensive error handling system for SMRT framework\n *\n * Provides specialized error types for different failure scenarios\n * with proper error codes, messages, and debugging information.\n */\n\n/**\n * Abstract base class for all SMRT framework errors.\n *\n * Adds a structured `code` (machine-readable string constant), a `category`\n * (coarse error domain), optional structured `details`, and an optional\n * causal `Error` chain on top of the standard `Error` class.\n *\n * Never throw `SmrtError` directly — use one of the concrete subclasses\n * (`DatabaseError`, `AIError`, `ValidationError`, etc.) or their static\n * factory methods for consistent error codes and messages.\n *\n * @example\n * ```typescript\n * try {\n * await product.save();\n * } catch (err) {\n * if (err instanceof ValidationError) {\n * console.error(err.code, err.details); // 'VALIDATION_REQUIRED_FIELD', { fieldName, objectType }\n * }\n * if (err instanceof SmrtError) {\n * logger.error(ErrorUtils.sanitizeError(err));\n * }\n * }\n * ```\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport { classifyDatabaseError } from './db-errors';\nimport { redactDatabaseUrl } from './utils/database-url.js';\n\nconst logger = createLogger({ level: 'info' });\n\nexport abstract class SmrtError extends Error {\n public readonly code: string;\n public readonly category:\n | 'database'\n | 'ai'\n | 'filesystem'\n | 'validation'\n | 'network'\n | 'configuration'\n | 'runtime';\n public readonly details?: Record<string, unknown>;\n public readonly cause?: Error;\n\n constructor(\n message: string,\n code: string,\n category: SmrtError['category'],\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n this.category = category;\n this.details = details;\n this.cause = cause;\n\n // Maintain proper stack trace for V8\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Converts error to a serializable object for logging/debugging\n */\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n category: this.category,\n details: this.details,\n stack: this.stack,\n cause: this.cause\n ? {\n name: this.cause.name,\n message: this.cause.message,\n stack: this.cause.stack,\n }\n : undefined,\n };\n }\n}\n\ntype ErrorLikeWithContext = Error & {\n cause?: unknown;\n context?: {\n originalError?: unknown;\n };\n};\n\nfunction collectErrorMessages(\n value: unknown,\n messages: string[],\n visited: Set<unknown>,\n depth = 0,\n): void {\n if (!value || visited.has(value) || depth > 10) {\n return;\n }\n\n visited.add(value);\n\n if (typeof value === 'string') {\n const trimmed = value.trim();\n if (trimmed) {\n messages.push(trimmed);\n }\n return;\n }\n\n if (!(value instanceof Error)) {\n return;\n }\n\n const message = value.message?.trim();\n if (message) {\n messages.push(message);\n }\n\n const errorWithContext = value as ErrorLikeWithContext;\n collectErrorMessages(\n errorWithContext.context?.originalError,\n messages,\n visited,\n depth + 1,\n );\n collectErrorMessages(errorWithContext.cause, messages, visited, depth + 1);\n}\n\nfunction getPrimaryCauseMessage(cause?: Error): {\n message?: string;\n messages?: string[];\n} {\n if (!cause) {\n return {};\n }\n\n const collected: string[] = [];\n collectErrorMessages(cause, collected, new Set<unknown>());\n\n const uniqueMessages = [...new Set(collected.filter(Boolean))];\n if (uniqueMessages.length === 0) {\n return {};\n }\n\n return {\n message: uniqueMessages[uniqueMessages.length - 1],\n messages: uniqueMessages,\n };\n}\n\n/**\n * Errors originating from database operations.\n *\n * Use the static factory methods rather than the constructor directly:\n * - `DatabaseError.connectionFailed(url, cause)` — DB connection failure\n * - `DatabaseError.queryFailed(query, cause)` — SQL execution error\n * - `DatabaseError.schemaError(table, op, cause)` — DDL/migration error\n * - `DatabaseError.constraintViolation(constraint, value, cause)` — FK/CHECK/UNIQUE\n * - `DatabaseError.corruptedData(field, class, cause)` — unparse-able column data\n * - `DatabaseError.missingDiscriminator(class, rowId)` — STI row missing `_meta_type`\n * - `DatabaseError.stiDiscriminatorConflict(...)` — legacy STI discriminator collides during qualification\n * - `DatabaseError.schemaMissing(table, class)` — table not yet migrated\n *\n * All errors have `category: 'database'` and codes prefixed with `DB_`.\n */\nexport class DatabaseError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'database', details, cause);\n }\n\n static connectionFailed(dbUrl: string, cause?: Error): DatabaseError {\n // Never carry the password into the message or details (#3527).\n const displayUrl = redactDatabaseUrl(dbUrl);\n return new DatabaseError(\n `Failed to connect to database: ${displayUrl}`,\n 'DB_CONNECTION_FAILED',\n { dbUrl: displayUrl },\n cause,\n );\n }\n\n static queryFailed(query: string, cause?: Error): DatabaseError {\n // Include the deepest actionable cause message for better debugging.\n const causeInfo = getPrimaryCauseMessage(cause);\n const causeMsg = causeInfo.message ? `\\nCause: ${causeInfo.message}` : '';\n return new DatabaseError(\n `Database query failed: ${query.substring(0, 100)}${query.length > 100 ? '...' : ''}${causeMsg}`,\n 'DB_QUERY_FAILED',\n {\n query,\n causeMessage: causeInfo.message,\n causeMessages: causeInfo.messages,\n },\n cause,\n );\n }\n\n static schemaError(\n tableName: string,\n operation: string,\n cause?: Error,\n ): DatabaseError {\n return new DatabaseError(\n `Schema operation failed for table '${tableName}': ${operation}`,\n 'DB_SCHEMA_ERROR',\n { tableName, operation },\n cause,\n );\n }\n\n static constraintViolation(\n constraint: string,\n value: unknown,\n cause?: Error,\n ): DatabaseError {\n return new DatabaseError(\n `Database constraint violation: ${constraint}`,\n 'DB_CONSTRAINT_VIOLATION',\n { constraint, value },\n cause,\n );\n }\n\n static corruptedData(\n fieldName: string,\n className: string,\n cause?: Error,\n ): DatabaseError {\n return new DatabaseError(\n `Corrupted data in field '${fieldName}' for ${className}. ` +\n `The data cannot be parsed or is malformed. ` +\n `This may indicate database corruption or incompatible schema changes.`,\n 'DB_CORRUPTED_DATA',\n { fieldName, className },\n cause,\n );\n }\n\n static missingDiscriminator(\n className: string,\n rowId?: string,\n ): DatabaseError {\n return new DatabaseError(\n `Missing discriminator (_meta_type) for STI class ${className}${rowId ? ` (row id: ${rowId})` : ''}. ` +\n `STI classes require a discriminator column to determine the correct subclass. ` +\n `This may indicate a schema mismatch or manual database modification.`,\n 'DB_MISSING_DISCRIMINATOR',\n { className, rowId },\n );\n }\n\n static stiDiscriminatorConflict(details: {\n className: string;\n tableName: string;\n id: string;\n slug: string;\n context: string;\n conflictIdentity: Record<string, unknown>;\n legacyMetaType: string;\n qualifiedMetaType: string;\n duplicateId: string;\n }): DatabaseError {\n const identityText = Object.entries(details.conflictIdentity)\n .map(([key, value]) => `${key} '${String(value)}'`)\n .join(', ');\n\n return new DatabaseError(\n `Legacy STI discriminator collision for ${details.className} (${details.tableName}). ` +\n `Row '${details.id}' would upgrade _meta_type from '${details.legacyMetaType}' to '${details.qualifiedMetaType}', ` +\n `but row '${details.duplicateId}' already uses the qualified discriminator for ${identityText || 'the same conflict identity'}. ` +\n `Merge or remove the duplicate legacy/qualified rows before saving.`,\n 'DB_STI_DISCRIMINATOR_CONFLICT',\n details,\n );\n }\n\n static schemaMissing(tableName: string, className: string): DatabaseError {\n return new DatabaseError(\n `Table '${tableName}' does not exist for class '${className}'. ` +\n `Run 'smrt db:migrate' to create database schema.`,\n 'DB_SCHEMA_MISSING',\n { tableName, className },\n );\n }\n}\n\n/**\n * Errors from AI provider integrations.\n *\n * Use the static factory methods:\n * - `AIError.providerError(provider, operation, cause)` — generic provider failure\n * - `AIError.rateLimitExceeded(provider, retryAfter)` — rate limit hit\n * - `AIError.invalidResponse(provider, response)` — unexpected response shape\n * - `AIError.authenticationFailed(provider)` — bad API key / credentials\n *\n * All errors have `category: 'ai'` and codes prefixed with `AI_`.\n * AI errors are considered retryable by `ErrorUtils.isRetryable()`.\n */\nexport class AIError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'ai', details, cause);\n }\n\n static providerError(\n provider: string,\n operation: string,\n cause?: Error,\n ): AIError {\n return new AIError(\n `AI provider '${provider}' failed during ${operation}`,\n 'AI_PROVIDER_ERROR',\n { provider, operation },\n cause,\n );\n }\n\n static rateLimitExceeded(provider: string, retryAfter?: number): AIError {\n return new AIError(\n `AI provider '${provider}' rate limit exceeded`,\n 'AI_RATE_LIMIT',\n { provider, retryAfter },\n );\n }\n\n static invalidResponse(provider: string, response: unknown): AIError {\n return new AIError(\n `AI provider '${provider}' returned invalid response`,\n 'AI_INVALID_RESPONSE',\n { provider, response },\n );\n }\n\n static authenticationFailed(provider: string): AIError {\n return new AIError(\n `AI provider '${provider}' authentication failed`,\n 'AI_AUTH_FAILED',\n { provider },\n );\n }\n}\n\n/**\n * Errors from filesystem operations.\n *\n * Use the static factory methods:\n * - `FilesystemError.fileNotFound(path)` — file does not exist\n * - `FilesystemError.permissionDenied(path, operation)` — access denied\n * - `FilesystemError.diskSpaceExceeded(path, requiredBytes)` — insufficient space\n *\n * All errors have `category: 'filesystem'` and codes prefixed with `FS_`.\n */\nexport class FilesystemError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'filesystem', details, cause);\n }\n\n static fileNotFound(path: string): FilesystemError {\n return new FilesystemError(`File not found: ${path}`, 'FS_FILE_NOT_FOUND', {\n path,\n });\n }\n\n static permissionDenied(path: string, operation: string): FilesystemError {\n return new FilesystemError(\n `Permission denied for ${operation} on: ${path}`,\n 'FS_PERMISSION_DENIED',\n { path, operation },\n );\n }\n\n static diskSpaceExceeded(\n path: string,\n requiredBytes: number,\n ): FilesystemError {\n return new FilesystemError(\n `Insufficient disk space for operation on: ${path}`,\n 'FS_DISK_SPACE_EXCEEDED',\n { path, requiredBytes },\n );\n }\n}\n\n/**\n * Input/data validation errors thrown before or during a database operation.\n *\n * `save()` throws `ValidationError` when field validation fails. The collection's\n * `convertWhereKeys()` throws it for invalid WHERE clause operators or field names.\n * `ValidationError` is **not** retried by `ErrorUtils.withRetry()`.\n *\n * Use the static factory methods:\n * - `ValidationError.requiredField(field, objectType)` — missing required field\n * - `ValidationError.invalidValue(field, value, expected)` — wrong type/format\n * - `ValidationError.uniqueConstraint(field, value)` — duplicate unique value\n * - `ValidationError.rangeError(field, value, min?, max?)` — out of allowed range\n *\n * All errors have `category: 'validation'` and codes prefixed with `VALIDATION_`.\n */\nexport class ValidationError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'validation', details, cause);\n }\n\n static requiredField(fieldName: string, objectType: string): ValidationError {\n return new ValidationError(\n `Required field '${fieldName}' is missing for ${objectType}`,\n 'VALIDATION_REQUIRED_FIELD',\n { fieldName, objectType },\n );\n }\n\n static invalidValue(\n fieldName: string,\n value: unknown,\n expectedType: string,\n ): ValidationError {\n return new ValidationError(\n `Invalid value for field '${fieldName}': expected ${expectedType}, got ${typeof value}`,\n 'VALIDATION_INVALID_VALUE',\n { fieldName, value, expectedType },\n );\n }\n\n static uniqueConstraint(fieldName: string, value: unknown): ValidationError {\n return new ValidationError(\n `Unique constraint violation for field '${fieldName}' with value: ${String(value)}`,\n 'VALIDATION_UNIQUE_CONSTRAINT',\n { fieldName, value },\n );\n }\n\n static rangeError(\n fieldName: string,\n value: number,\n min?: number,\n max?: number,\n ): ValidationError {\n const range =\n min !== undefined && max !== undefined\n ? `between ${min} and ${max}`\n : min !== undefined\n ? `>= ${min}`\n : `<= ${max}`;\n\n return new ValidationError(\n `Value for field '${fieldName}' must be ${range}, got: ${value}`,\n 'VALIDATION_RANGE_ERROR',\n { fieldName, value, min, max },\n );\n }\n}\n\n/**\n * Errors from HTTP and external network operations.\n *\n * Use the static factory methods:\n * - `NetworkError.requestFailed(url, status?, body?)` — non-2xx response or connection failure\n * - `NetworkError.timeout(url, timeoutMs)` — request exceeded timeout\n * - `NetworkError.serviceUnavailable(service, reason?)` — external service down\n *\n * All errors have `category: 'network'` and codes prefixed with `NETWORK_`.\n * Network errors are considered retryable by `ErrorUtils.isRetryable()`.\n */\nexport class NetworkError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'network', details, cause);\n }\n\n static requestFailed(\n url: string,\n status?: number,\n responseBody?: string | Error,\n ): NetworkError {\n const cause = responseBody instanceof Error ? responseBody : undefined;\n const body = typeof responseBody === 'string' ? responseBody : undefined;\n return new NetworkError(\n `Network request failed: ${url}${status ? ` (Status: ${status})` : ''}${body ? ` - ${body.substring(0, 200)}` : ''}`,\n 'NETWORK_REQUEST_FAILED',\n { url, status, responseBody: body },\n cause,\n );\n }\n\n static timeout(url: string, timeoutMs: number): NetworkError {\n return new NetworkError(\n `Network request timed out after ${timeoutMs}ms: ${url}`,\n 'NETWORK_TIMEOUT',\n { url, timeoutMs },\n );\n }\n\n static serviceUnavailable(service: string, reason?: string): NetworkError {\n return new NetworkError(\n reason\n ? `External service unavailable: ${service} - ${reason}`\n : `External service unavailable: ${service}`,\n 'NETWORK_SERVICE_UNAVAILABLE',\n { service, reason },\n );\n }\n}\n\n/**\n * Errors from misconfigured or incompatible class/framework setup.\n *\n * These are typically thrown during class registration (i.e. at module load time),\n * not during normal request handling.\n *\n * Use the static factory methods:\n * - `ConfigurationError.missingConfiguration(key, context?)` — missing required config\n * - `ConfigurationError.invalidConfiguration(key, value, expected)` — wrong config type/value\n * - `ConfigurationError.initializationFailed(component, cause?)` — component failed to start\n * - `ConfigurationError.circularInheritance(class, chain)` — circular class inheritance\n * - `ConfigurationError.incompatibleStrategy(class, strategy, parent, parentStrategy)` — STI mismatch\n * - `ConfigurationError.unregisteredBaseClass(child, base)` — STI base not yet registered\n *\n * All errors have `category: 'configuration'` and codes prefixed with `CONFIG_`.\n * Configuration errors are **not** retried by `ErrorUtils.withRetry()`.\n */\nexport class ConfigurationError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'configuration', details, cause);\n }\n\n static missingConfiguration(\n configKey: string,\n context?: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `Missing required configuration: ${configKey}${context ? ` in ${context}` : ''}`,\n 'CONFIG_MISSING',\n { configKey, context },\n );\n }\n\n static invalidConfiguration(\n configKey: string,\n value: unknown,\n expected: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `Invalid configuration for ${configKey}: expected ${expected}, got ${typeof value}`,\n 'CONFIG_INVALID',\n { configKey, value, expected },\n );\n }\n\n static initializationFailed(\n component: string,\n cause?: Error,\n ): ConfigurationError {\n return new ConfigurationError(\n `Failed to initialize component: ${component}`,\n 'CONFIG_INIT_FAILED',\n { component },\n cause,\n );\n }\n\n static circularInheritance(\n className: string,\n inheritanceChain: string[],\n ): ConfigurationError {\n return new ConfigurationError(\n `Circular inheritance detected for class '${className}'. ` +\n `Inheritance chain: ${inheritanceChain.join(' → ')} → ${className}. ` +\n `Classes cannot inherit from themselves directly or indirectly.`,\n 'CONFIG_CIRCULAR_INHERITANCE',\n { className, inheritanceChain },\n );\n }\n\n static incompatibleStrategy(\n className: string,\n classStrategy: string,\n parentClass: string,\n parentStrategy: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `Incompatible table strategy for class '${className}' (${classStrategy}). ` +\n `Parent class '${parentClass}' uses ${parentStrategy} strategy. ` +\n `Child classes must use the same table strategy as their parent. ` +\n `Either change ${className} to use ${parentStrategy}, or remove the inheritance.`,\n 'CONFIG_INCOMPATIBLE_STRATEGY',\n { className, classStrategy, parentClass, parentStrategy },\n );\n }\n\n static unregisteredBaseClass(\n childClass: string,\n baseClass: string,\n ): ConfigurationError {\n return new ConfigurationError(\n `STI base class '${baseClass}' is not registered for child class '${childClass}'. ` +\n `When using Single Table Inheritance, the base class must be registered before any child classes. ` +\n `Ensure ${baseClass} is decorated with @smrt({ tableStrategy: 'sti' }) and imported before ${childClass}.`,\n 'CONFIG_UNREGISTERED_BASE',\n { childClass, baseClass },\n );\n }\n}\n\n/**\n * Errors representing unexpected runtime failures not covered by other categories.\n *\n * `RuntimeError` is the catch-all for internal framework errors — invalid object\n * state, exhausted resources, or failures in operations like `save()` and `loadFromId()`\n * that propagate from an unknown cause.\n *\n * Use the static factory methods:\n * - `RuntimeError.operationFailed(operation, context?, cause?)` — generic operation failure\n * - `RuntimeError.invalidState(message, context?)` — unexpected object/system state\n * - `RuntimeError.resourceExhausted(resource, limit)` — limit exceeded (e.g. connections)\n *\n * All errors have `category: 'runtime'` and codes prefixed with `RUNTIME_`.\n */\nexport class RuntimeError extends SmrtError {\n constructor(\n message: string,\n code: string,\n details?: Record<string, unknown>,\n cause?: Error,\n ) {\n super(message, code, 'runtime', details, cause);\n }\n\n static operationFailed(\n operation: string,\n context?: string,\n cause?: Error,\n ): RuntimeError {\n return new RuntimeError(\n `Operation failed: ${operation}${context ? ` in ${context}` : ''}`,\n 'RUNTIME_OPERATION_FAILED',\n { operation, context },\n cause,\n );\n }\n\n static invalidState(\n message: string,\n context?: Record<string, unknown>,\n ): RuntimeError {\n return new RuntimeError(message, 'RUNTIME_INVALID_STATE', context);\n }\n\n static resourceExhausted(resource: string, limit: number): RuntimeError {\n return new RuntimeError(\n `Resource exhausted: ${resource} exceeded limit of ${limit}`,\n 'RUNTIME_RESOURCE_EXHAUSTED',\n { resource, limit },\n );\n }\n}\n\n/**\n * Error thrown when a tenant isolation boundary is crossed while resolving a\n * relationship.\n *\n * Raised by {@link SmrtObject.loadRelated} / {@link SmrtObject.loadRelatedMany}\n * (and {@link SmrtObject.getRelated}, which delegates to them) when a\n * tenant-scoped object resolves a relationship to an object belonging to a\n * *different*, non-null tenant — the genuine cross-tenant data leak. The guard\n * is a no-op when either side has a `null` tenant (global / non-tenant-scoped\n * models) and when both sides share the same tenant, so it only fires on real\n * leaks. Pass `{ allowCrossTenant: true }` to the loader to deliberately opt out.\n *\n * The `code` is always `'TENANT_ISOLATION_VIOLATION'` and the category is\n * `'validation'`. It is never retried — `ErrorUtils.withRetry()` rethrows it\n * immediately and `ErrorUtils.isRetryable()` returns `false` — because a tenant\n * boundary violation is deterministic. `tenantId` is the owning object's tenant\n * and `attemptedTenantId` is the tenant of the object that was reached.\n *\n * This shares its stable `code`, `name`, `tenantId`, and `attemptedTenantId`\n * shape with the interceptor-level `TenantIsolationError` in\n * `@happyvertical/smrt-tenancy`, so cross-cutting handlers can match either via\n * `err.code === 'TENANT_ISOLATION_VIOLATION'`. They are intentionally distinct\n * classes because `@happyvertical/smrt-core` cannot depend on the tenancy\n * package (the dependency runs the other way).\n *\n * @example\n * ```typescript\n * try {\n * await order.loadRelated('customerId');\n * } catch (err) {\n * if (err instanceof TenantIsolationError) {\n * // err.tenantId — the order's tenant\n * // err.attemptedTenantId — the customer's tenant\n * }\n * }\n * ```\n *\n * @see SmrtObject.loadRelated\n * @see SmrtObject.loadRelatedMany\n */\nexport class TenantIsolationError extends SmrtError {\n /** The tenant ID of the object that owns the relationship. */\n public readonly tenantId?: string;\n /** The tenant ID of the related object that was reached (and rejected). */\n public readonly attemptedTenantId?: string;\n\n constructor(\n message: string,\n details?: {\n tenantId?: string;\n attemptedTenantId?: string;\n [key: string]: unknown;\n },\n cause?: Error,\n ) {\n super(message, 'TENANT_ISOLATION_VIOLATION', 'validation', details, cause);\n this.tenantId = details?.tenantId;\n this.attemptedTenantId = details?.attemptedTenantId;\n }\n\n /**\n * Builds a {@link TenantIsolationError} for a blocked cross-tenant\n * relationship resolution, with a descriptive message and structured details.\n */\n static crossTenantReference(details: {\n sourceClass: string;\n fieldName: string;\n sourceTenantId: string;\n targetClass?: string;\n targetTenantId: string;\n }): TenantIsolationError {\n const target = details.targetClass\n ? `${details.targetClass} (tenant '${details.targetTenantId}')`\n : `tenant '${details.targetTenantId}'`;\n return new TenantIsolationError(\n `Cross-tenant relationship access blocked on ${details.sourceClass}.${details.fieldName}: ` +\n `owning tenant '${details.sourceTenantId}' does not match ${target}. ` +\n `Pass { allowCrossTenant: true } to loadRelated()/loadRelatedMany()/getRelated() to override.`,\n {\n tenantId: details.sourceTenantId,\n attemptedTenantId: details.targetTenantId,\n sourceClass: details.sourceClass,\n fieldName: details.fieldName,\n targetClass: details.targetClass,\n },\n );\n }\n\n /**\n * Builds a {@link TenantIsolationError} for a natural-key save whose\n * conflict target matched a row owned by a different tenant (or a global\n * row, or — for a global save — a tenant's row). `save()` refuses instead of\n * letting `ON CONFLICT … DO UPDATE` rewrite that row's `id` and tenant.\n *\n * The other row's owner is deliberately NOT reported: naming it would\n * disclose another tenant's identity to the caller. Only the caller's own\n * values appear in the message and details.\n */\n static naturalKeyOwnedElsewhere(details: {\n className: string;\n tableName: string;\n conflictColumns: string[];\n conflictValues: Record<string, unknown>;\n ownershipColumns: string[];\n tenantId?: string | null;\n }): TenantIsolationError {\n const key = details.conflictColumns\n .map(\n (column) =>\n `${column}=${JSON.stringify(details.conflictValues[column] ?? null)}`,\n )\n .join(', ');\n return new TenantIsolationError(\n `Refusing to save ${details.className}: its natural key (${key}) on ` +\n `\"${details.tableName}\" already belongs to a row with a different owner ` +\n `(${details.ownershipColumns.join(', ')}). Saving would overwrite that row's ` +\n `id and owner. Give the table a tenant-inclusive unique key ` +\n `(declare tenant scope, or drop the explicit conflictColumns that omit ` +\n `the tenant column, then run \\`smrt db:migrate\\`), or choose another natural key.`,\n {\n tenantId: details.tenantId ?? undefined,\n className: details.className,\n tableName: details.tableName,\n conflictColumns: details.conflictColumns,\n ownershipColumns: details.ownershipColumns,\n reason: 'natural_key_owned_elsewhere',\n },\n );\n }\n}\n\n/**\n * Error thrown by `runOnce()` (`./run-once.ts`, #3080) when a submission's\n * claim cannot be resolved to a definite, replayable result.\n *\n * Mirrors the \"refused vs unknown outcome\" distinction #2990 drew for\n * `AssistantDock` actions:\n * - `RUN_ONCE_IN_FLIGHT` — a claim for this key exists and has not completed.\n * This is a definite decision, not an unknown one: some execution currently\n * holds the key. Retry later with the SAME token and content — minting a\n * fresh token would create an unrelated claim and defeat the guard.\n * - `RUN_ONCE_OUTCOME_UNKNOWN` — the claim insert reported a conflict but no\n * claim row could be read back. Genuinely indeterminate: retrying with the\n * SAME token and content is still safe (a completed claim replays; anything\n * else runs as a fresh attempt), but the caller must not treat this as\n * either success or failure.\n *\n * Both are `category: 'runtime'` and neither is retried automatically —\n * `runOnce()` never loops on them, because only the caller knows whether\n * retrying inline is appropriate for its own request (a SvelteKit action may\n * prefer to tell the user \"still processing\" over blocking on a retry loop).\n */\nexport class RunOnceClaimError extends SmrtError {\n /** The derived claim key this error concerns. */\n public readonly claimKey: string;\n\n constructor(\n message: string,\n code: 'RUN_ONCE_IN_FLIGHT' | 'RUN_ONCE_OUTCOME_UNKNOWN',\n claimKey: string,\n ) {\n super(message, code, 'runtime', { claimKey });\n this.claimKey = claimKey;\n }\n\n static inFlight(claimKey: string): RunOnceClaimError {\n return new RunOnceClaimError(\n `runOnce: claim \"${claimKey}\" is already in flight. Retry later with ` +\n `the same token and content — do not mint a new token.`,\n 'RUN_ONCE_IN_FLIGHT',\n claimKey,\n );\n }\n\n static outcomeUnknown(claimKey: string): RunOnceClaimError {\n return new RunOnceClaimError(\n `runOnce: outcome for claim \"${claimKey}\" is unknown. Retrying with ` +\n `the same token and content is safe, but do not treat this as ` +\n `either success or failure.`,\n 'RUN_ONCE_OUTCOME_UNKNOWN',\n claimKey,\n );\n }\n}\n\n/**\n * Utility functions for error handling\n */\nexport class ErrorUtils {\n /**\n * Wraps a function with error handling and automatic retry logic.\n *\n * Retries are for failures a later attempt might survive. An error is\n * rethrown immediately, with no backoff, when it is:\n *\n * - a {@link ValidationError} or {@link ConfigurationError} — the input is\n * wrong, and the same input will be wrong next time;\n * - a {@link TenantIsolationError} — a security boundary, and deterministic;\n * - a **deterministic database failure** (#2366), classified through the\n * driver-error cause chain by {@link classifyDatabaseError}: constraint\n * violations, invalid input syntax, missing tables/columns, and statements\n * issued inside an already-aborted PostgreSQL transaction (`25P02`).\n *\n * The database check matters because `@happyvertical/sql` wraps every driver\n * error as `DatabaseError('Failed to upsert record into table', …)`, hiding\n * the constraint wording from `error.message`. Without it, a unique-key\n * collision burned the full 500 + 1000 + 2000 ms backoff and — inside a\n * caller-managed transaction — replaced the real cause with\n * `25P02 current transaction is aborted` on the way out.\n *\n * Errors the classifier has no opinion about (`kind: 'unknown'`) keep the\n * original permissive behavior and are retried.\n */\n static async withRetry<T>(\n operation: () => Promise<T>,\n maxRetries = 3,\n delay = 1000,\n backoffMultiplier = 2,\n ): Promise<T> {\n let lastError: Error = new Error('Operation failed without error details');\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n if (attempt === maxRetries) {\n throw lastError;\n }\n\n // Skip retry for certain error types. A tenant isolation violation is\n // deterministic — retrying re-fetches the same cross-tenant target — and\n // is a security boundary, so it must never be retried.\n if (\n error instanceof ValidationError ||\n error instanceof ConfigurationError ||\n error instanceof TenantIsolationError\n ) {\n throw error;\n }\n\n // An invalid-state error names a condition re-running cannot change\n // (and a write that already ran must not run again, #3737).\n if (\n error instanceof RuntimeError &&\n error.code === 'RUNTIME_INVALID_STATE'\n ) {\n throw error;\n }\n\n // A deterministic database failure cannot be retried into success, and\n // retrying it inside a transaction actively destroys evidence: every\n // later attempt runs on the aborted client and reports `25P02` instead\n // of the constraint that actually failed (#2366).\n if (classifyDatabaseError(error).deterministic) {\n throw lastError;\n }\n\n // Wait before retrying with exponential backoff\n // Wrap in try-catch to handle any potential timer errors\n try {\n await new Promise<void>((resolve) => {\n setTimeout(() => resolve(), delay * backoffMultiplier ** attempt);\n });\n } catch (timerError) {\n // Log timer error but don't fail the retry\n logger.error('Timer error during retry', { error: timerError });\n }\n }\n }\n\n throw lastError;\n }\n\n /**\n * Checks if an error is retryable.\n *\n * A database failure is classified through its driver-error cause chain\n * first (#2366), so a wrapped `40001 serialization_failure` or `SQLITE_BUSY`\n * reports retryable while a wrapped `23505 unique_violation` does not —\n * neither of which the `category === 'database'` test alone could tell\n * apart. Only when the chain yields no opinion do the original\n * category/message heuristics apply.\n */\n static isRetryable(error: Error): boolean {\n const databaseClassification = classifyDatabaseError(error);\n if (databaseClassification.kind !== 'unknown') {\n return databaseClassification.retryable;\n }\n\n if (error instanceof SmrtError) {\n return error.category === 'network' || error.category === 'ai';\n }\n\n // Check for common retryable error patterns\n const retryablePatterns = [\n /ECONNRESET/,\n /ETIMEDOUT/,\n /ENOTFOUND/,\n /rate.?limit/i,\n /timeout/i,\n /503/,\n /502/,\n /500/,\n ];\n\n return retryablePatterns.some((pattern) => pattern.test(error.message));\n }\n\n /**\n * Sanitizes an error for safe logging (removes sensitive information)\n */\n static sanitizeError(error: Error): Record<string, unknown> {\n const sanitized: Record<string, unknown> = {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n\n if (error instanceof SmrtError) {\n sanitized.code = error.code;\n sanitized.category = error.category;\n\n // Sanitize details to remove potential sensitive information\n if (error.details) {\n const details: Record<string, unknown> = { ...error.details };\n sanitized.details = details;\n\n // Remove common sensitive fields\n const sensitiveFields = [\n 'password',\n 'token',\n 'key',\n 'secret',\n 'apiKey',\n ];\n for (const field of sensitiveFields) {\n if (details[field]) {\n details[field] = '[REDACTED]';\n }\n }\n }\n }\n\n return sanitized;\n }\n}\n\n/**\n * Validation report that collects multiple validation errors\n *\n * Useful for validating an entire object and reporting all errors\n * at once rather than stopping at the first error.\n *\n * @example\n * ```typescript\n * const report = new ValidationReport('Product');\n * report.addError(ValidationError.requiredField('name', 'Product'));\n * report.addError(ValidationError.rangeError('price', -10, 0));\n *\n * if (report.hasErrors()) {\n * console.error(report.toString());\n * // Output:\n * // Validation failed for Product with 2 errors:\n * // - name: Required field 'name' is missing for Product\n * // - price: Value -10 for field 'price' is outside allowed range [0, undefined]\n * }\n * ```\n */\nexport class ValidationReport {\n private errors: ValidationError[] = [];\n private objectType: string;\n\n constructor(objectType: string) {\n this.objectType = objectType;\n }\n\n /**\n * Add a validation error to the report\n */\n addError(error: ValidationError): void {\n this.errors.push(error);\n }\n\n /**\n * Check if there are any validation errors\n */\n hasErrors(): boolean {\n return this.errors.length > 0;\n }\n\n /**\n * Get all validation errors\n */\n getErrors(): ValidationError[] {\n return [...this.errors];\n }\n\n /**\n * Get the number of validation errors\n */\n getErrorCount(): number {\n return this.errors.length;\n }\n\n /**\n * Convert to a human-readable string\n */\n toString(): string {\n if (this.errors.length === 0) {\n return `Validation passed for ${this.objectType}`;\n }\n\n const errorList = this.errors\n .map((err, idx) => ` ${idx + 1}. ${err.message}`)\n .join('\\n');\n\n return `Validation failed for ${this.objectType} with ${this.errors.length} error(s):\\n${errorList}`;\n }\n\n /**\n * Convert to JSON format\n */\n toJSON(): object {\n return {\n objectType: this.objectType,\n errorCount: this.errors.length,\n errors: this.errors.map((err) => err.toJSON()),\n };\n }\n\n /**\n * Throw the first error if there are any errors\n */\n throwIfErrors(): void {\n if (this.errors.length > 0) {\n throw this.errors[0];\n }\n }\n\n /**\n * Clear all errors\n */\n clear(): void {\n this.errors = [];\n }\n}\n\n/**\n * Validation utility functions\n */\nexport class ValidationUtils {\n /**\n * Validate a single field value\n *\n * @param fieldName - Name of the field\n * @param value - Value to validate\n * @param options - Validation options (required, min, max, etc.)\n * @returns ValidationError if validation fails, null otherwise\n */\n static async validateField(\n fieldName: string,\n value: unknown,\n options: {\n required?: boolean;\n min?: number;\n max?: number;\n minLength?: number;\n maxLength?: number;\n pattern?: string | RegExp;\n type?: string;\n customValidator?: (value: unknown) => boolean | Promise<boolean>;\n customMessage?: string;\n },\n objectType: string = 'Object',\n ): Promise<ValidationError | null> {\n // Required check\n if (\n options.required &&\n (value === null || value === undefined || value === '')\n ) {\n return ValidationError.requiredField(fieldName, objectType);\n }\n\n // Skip further validation if value is null/undefined and not required\n if (value === null || value === undefined) {\n return null;\n }\n\n // Numeric range validation\n if (typeof value === 'number') {\n if (options.min !== undefined && value < options.min) {\n return ValidationError.rangeError(\n fieldName,\n value,\n options.min,\n options.max,\n );\n }\n if (options.max !== undefined && value > options.max) {\n return ValidationError.rangeError(\n fieldName,\n value,\n options.min,\n options.max,\n );\n }\n }\n\n // String length validation\n if (typeof value === 'string') {\n if (options.minLength !== undefined && value.length < options.minLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with minimum length ${options.minLength}`,\n );\n }\n if (options.maxLength !== undefined && value.length > options.maxLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with maximum length ${options.maxLength}`,\n );\n }\n\n // Pattern validation\n if (options.pattern) {\n const regex =\n typeof options.pattern === 'string'\n ? new RegExp(options.pattern)\n : options.pattern;\n if (!regex.test(value)) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string matching pattern ${options.pattern}`,\n );\n }\n }\n }\n\n // Custom validator\n if (options.customValidator) {\n try {\n const isValid = await options.customValidator(value);\n if (!isValid) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n options.customMessage || 'custom validation failed',\n );\n }\n } catch (error) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `custom validation error: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return null;\n }\n\n /**\n * Validate required field\n */\n static validateRequired(\n fieldName: string,\n value: unknown,\n objectType: string = 'Object',\n ): ValidationError | null {\n if (value === null || value === undefined || value === '') {\n return ValidationError.requiredField(fieldName, objectType);\n }\n return null;\n }\n\n /**\n * Validate numeric range\n */\n static validateRange(\n fieldName: string,\n value: number,\n min?: number,\n max?: number,\n ): ValidationError | null {\n if (min !== undefined && value < min) {\n return ValidationError.rangeError(fieldName, value, min, max);\n }\n if (max !== undefined && value > max) {\n return ValidationError.rangeError(fieldName, value, min, max);\n }\n return null;\n }\n\n /**\n * Validate string length\n */\n static validateLength(\n fieldName: string,\n value: string,\n minLength?: number,\n maxLength?: number,\n ): ValidationError | null {\n if (minLength !== undefined && value.length < minLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with minimum length ${minLength}`,\n );\n }\n if (maxLength !== undefined && value.length > maxLength) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string with maximum length ${maxLength}`,\n );\n }\n return null;\n }\n\n /**\n * Validate string pattern\n */\n static validatePattern(\n fieldName: string,\n value: string,\n pattern: string | RegExp,\n ): ValidationError | null {\n const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern;\n if (!regex.test(value)) {\n return ValidationError.invalidValue(\n fieldName,\n value,\n `string matching pattern ${pattern}`,\n );\n }\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;AAE7C,IAAsB,YAAtB,cAAwC,MAAM;CAC5C;CACA;CAQA;CACA;CAEA,YACE,SACA,MACA,UACA,SACA,OACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO,KAAK,YAAY;EAC7B,KAAK,OAAO;EACZ,KAAK,WAAW;EAChB,KAAK,UAAU;EACf,KAAK,QAAQ;EAGb,IAAI,MAAM,mBACR,MAAM,kBAAkB,MAAM,KAAK,WAAW;CAElD;;;;CAKA,SAAS;EACP,OAAO;GACL,MAAM,KAAK;GACX,SAAS,KAAK;GACd,MAAM,KAAK;GACX,UAAU,KAAK;GACf,SAAS,KAAK;GACd,OAAO,KAAK;GACZ,OAAO,KAAK,QACR;IACE,MAAM,KAAK,MAAM;IACjB,SAAS,KAAK,MAAM;IACpB,OAAO,KAAK,MAAM;GACpB,IACA,KAAA;EACN;CACF;AACF;AASA,SAAS,qBACP,OACA,UACA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OAAO,gBAAgB,aACrB,WACA,OACA,QAAQ,iBAAiB,0BAC3B;EAEJ,SAAS,OAAO;GACd,OAAO,gBAAgB,aACrB,WACA,OACA,4BAA4B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACnF;EACF;EAGF,OAAO;CACT;;;;CAKA,OAAO,iBACL,WACA,OACA,aAAqB,UACG;EACxB,IAAI,UAAU,QAAQ,UAAU,KAAA,KAAa,UAAU,IACrD,OAAO,gBAAgB,cAAc,WAAW,UAAU;EAE5D,OAAO;CACT;;;;CAKA,OAAO,cACL,WACA,OACA,KACA,KACwB;EACxB,IAAI,QAAQ,KAAA,KAAa,QAAQ,KAC/B,OAAO,gBAAgB,WAAW,WAAW,OAAO,KAAK,GAAG;EAE9D,IAAI,QAAQ,KAAA,KAAa,QAAQ,KAC/B,OAAO,gBAAgB,WAAW,WAAW,OAAO,KAAK,GAAG;EAE9D,OAAO;CACT;;;;CAKA,OAAO,eACL,WACA,OACA,WACA,WACwB;EACxB,IAAI,cAAc,KAAA,KAAa,MAAM,SAAS,WAC5C,OAAO,gBAAgB,aACrB,WACA,OACA,8BAA8B,WAChC;EAEF,IAAI,cAAc,KAAA,KAAa,MAAM,SAAS,WAC5C,OAAO,gBAAgB,aACrB,WACA,OACA,8BAA8B,WAChC;EAEF,OAAO;CACT;;;;CAKA,OAAO,gBACL,WACA,OACA,SACwB;EAExB,IAAI,EADU,OAAO,YAAY,WAAW,IAAI,OAAO,OAAO,IAAI,QAAA,CACvD,KAAK,KAAK,GACnB,OAAO,gBAAgB,aACrB,WACA,OACA,2BAA2B,SAC7B;EAEF,OAAO;CACT;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
- import { existsSync, readFileSync, statSync } from "node:fs";
3
2
  import { isAbsolute, relative, resolve, sep } from "node:path";
3
+ import { existsSync, readFileSync, statSync } from "node:fs";
4
4
  //#region src/generation-snapshot.ts
5
5
  var SOURCE_ROOT_PREFIX = "@smrt/source-root/";
6
6
  function isInsideRoot(root, filePath) {
@@ -1,5 +1,5 @@
1
- import { CRUD_OPERATIONS, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, buildCustomActionInputSchema, buildCustomActionInvocationArgs, classifyMethodWireability, classifyParameterWireability, coerceCustomActionArgument, createClassNamePredicate, createManifestClassNamePredicate, customActionParameterInputName, declaredTypeAcceptsDate, declaresRuntimeRestRoute, declaresRuntimeRestRouteShape, isCrudOperation, isCrudToolAction, normalizeCustomActionFailure, queryStringDecoderFor, readMethodDecoratorConfig, resolveApiMethodExposure, resolveCustomActionMetadata, resolveDeclaredScopeMismatch, resolveEffectiveActionMetadata, toCustomActionBoolean, toCustomActionDate, toCustomActionNumber } from "./custom-action.js";
2
1
  import { PRIVATE_READ_CACHE_CONTROL, canonicalReadRepresentation, computeBodyEtag, computeTableVersionEtag, conditionalJsonResponse, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, resolveReadCacheControl, resolveTenantEtagDiscriminator, versionConditionalResponse, warnIfSharedCacheNeutralized } from "./conditional-get.js";
2
+ import { CRUD_OPERATIONS, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, buildCustomActionInputSchema, buildCustomActionInvocationArgs, classifyMethodWireability, classifyParameterWireability, coerceCustomActionArgument, createClassNamePredicate, createManifestClassNamePredicate, customActionParameterInputName, declaredTypeAcceptsDate, declaresRuntimeRestRoute, declaresRuntimeRestRouteShape, isCrudOperation, isCrudToolAction, normalizeCustomActionFailure, queryStringDecoderFor, readMethodDecoratorConfig, resolveApiMethodExposure, resolveCustomActionMetadata, resolveDeclaredScopeMismatch, resolveEffectiveActionMetadata, toCustomActionBoolean, toCustomActionDate, toCustomActionNumber } from "./custom-action.js";
3
3
  import { DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, buildChangeEventStream, changeEventSubscribersAtCapacity, eventStreamCapacityExceededResponse, normalizeEventsMaxSubscribers, signalVisibleToTenant, tryReserveChangeEventSubscriberSlot } from "./events-route.js";
4
4
  import { runWithTenantGate, setTenantEntryPointRunner } from "./tenant-gate.js";
5
5
  import { MCPGenerator, MCP_STABLE_CATALOG_TTL_MS, resolveMCPToolListCacheHint, sortMCPTools } from "./mcp.js";
@@ -1,18 +1,18 @@
1
1
  import { buildDefaultListOrderBy, resolveListLimit, resolveListOffset } from "../query-bounds.js";
2
2
  import { SmrtCollection } from "../collection.js";
3
3
  import { isQualifiedName } from "../utils/qualified-names.js";
4
- import { SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, buildCustomActionInvocationArgs, customActionParameterInputName, isCrudOperation, isCrudToolAction, isFrameworkLifecycleMethod, normalizeCustomActionFailure, resolveCustomActionMetadata } from "./custom-action.js";
5
- import { resolveDisplayLabelField } from "../ui-metadata.js";
6
4
  import { isFrameworkBaseClass } from "../registry/framework-base-classes.js";
7
5
  import { readFieldEnum } from "../registry/manifest-field-merge.js";
8
6
  import { ObjectRegistry } from "../registry.js";
7
+ import { SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, buildCustomActionInvocationArgs, customActionParameterInputName, isCrudOperation, isCrudToolAction, isFrameworkLifecycleMethod, normalizeCustomActionFailure, resolveCustomActionMetadata } from "./custom-action.js";
8
+ import { resolveDisplayLabelField } from "../ui-metadata.js";
9
9
  import { generatedSiblingExtension, renderGeneratedSource, resolveGeneratedSourceLanguage } from "./mcp-emit.js";
10
10
  import { generateClaudeConfig, generateMCPDocumentation, generateMCPScript, generateRuntimeBootstrap } from "./mcp-runtime-template.js";
11
11
  import { canonicalMcpToolNames } from "./mcp-tool-name.js";
12
12
  import { runWithTenantGate } from "./tenant-gate.js";
13
13
  import { assertMcpJsonSchemaSafety, buildToolInputSchema, describeAction, fieldTypeToJsonSchema, finalizeMcpJsonSchema, isCrudAction, resolveToolSemantics } from "./tool-schema.js";
14
- import { dirname, resolve } from "node:path";
15
14
  import { mkdir, writeFile } from "node:fs/promises";
15
+ import { dirname, resolve } from "node:path";
16
16
  //#region src/generators/mcp.ts
17
17
  /**
18
18
  * MCP (Model Context Protocol) server generator for smrt objects
@@ -1,6 +1,6 @@
1
- import { declaresRuntimeRestRoute, readMethodDecoratorConfig, resolveEffectiveActionMetadata } from "./custom-action.js";
2
1
  import { ObjectRegistry } from "../registry.js";
3
2
  import { PRIVATE_READ_CACHE_CONTROL } from "./conditional-get.js";
3
+ import { declaresRuntimeRestRoute, readMethodDecoratorConfig, resolveEffectiveActionMetadata } from "./custom-action.js";
4
4
  //#region src/generators/preflight-route.ts
5
5
  /**
6
6
  * Generated `_preflight` HTTP route for browser-plane playbook preflight
@@ -1,11 +1,11 @@
1
1
  import { isTenantScopedClassResolved, resolveDispatchTenantScope } from "../dispatch/tenant-resolver.js";
2
2
  import { getTableVersion } from "../change-feed.js";
3
3
  import { buildDefaultListOrderBy, resolveListLimit, resolveListOffset } from "../query-bounds.js";
4
- import { buildCustomActionInvocationArgs, declaresRuntimeRestRouteShape, normalizeCustomActionFailure, readMethodDecoratorConfig, resolveCustomActionMetadata, resolveEffectiveActionMetadata } from "./custom-action.js";
5
4
  import { isFrameworkBaseClass } from "../registry/framework-base-classes.js";
6
5
  import { ObjectRegistry } from "../registry.js";
7
6
  import "../dispatch/index.js";
8
7
  import { canonicalReadRepresentation, computeTableVersionEtag, conditionalJsonResponse, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, resolveReadCacheControl, resolveTenantEtagDiscriminator, versionConditionalResponse, warnIfSharedCacheNeutralized, warnIfTenantScopedPublicRead } from "./conditional-get.js";
8
+ import { buildCustomActionInvocationArgs, declaresRuntimeRestRouteShape, normalizeCustomActionFailure, readMethodDecoratorConfig, resolveCustomActionMetadata, resolveEffectiveActionMetadata } from "./custom-action.js";
9
9
  import { handleChangesRoute } from "./changes-route.js";
10
10
  import { handleEventsRoute } from "./events-route.js";
11
11
  import { handlePlaybookPreflightRoute, isApiActionEnabledForObject, isRestRoutePublic } from "./preflight-route.js";
@@ -1,5 +1,5 @@
1
- import { CRUD_OPERATIONS, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, buildCustomActionInputSchema, buildCustomActionInvocationArgs, classifyMethodWireability, classifyParameterWireability, coerceCustomActionArgument, createClassNamePredicate, createManifestClassNamePredicate, customActionParameterInputName, declaredTypeAcceptsDate, declaresRuntimeRestRoute, declaresRuntimeRestRouteShape, isCrudOperation, isCrudToolAction, normalizeCustomActionFailure, queryStringDecoderFor, readMethodDecoratorConfig, resolveApiMethodExposure, resolveCustomActionMetadata, resolveDeclaredScopeMismatch, resolveEffectiveActionMetadata, toCustomActionBoolean, toCustomActionDate, toCustomActionNumber } from "./generators/custom-action.js";
2
1
  import { PRIVATE_READ_CACHE_CONTROL, canonicalReadRepresentation, computeBodyEtag, computeTableVersionEtag, conditionalJsonResponse, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, resolveReadCacheControl, resolveTenantEtagDiscriminator, versionConditionalResponse, warnIfSharedCacheNeutralized } from "./generators/conditional-get.js";
2
+ import { CRUD_OPERATIONS, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, buildCustomActionInputSchema, buildCustomActionInvocationArgs, classifyMethodWireability, classifyParameterWireability, coerceCustomActionArgument, createClassNamePredicate, createManifestClassNamePredicate, customActionParameterInputName, declaredTypeAcceptsDate, declaresRuntimeRestRoute, declaresRuntimeRestRouteShape, isCrudOperation, isCrudToolAction, normalizeCustomActionFailure, queryStringDecoderFor, readMethodDecoratorConfig, resolveApiMethodExposure, resolveCustomActionMetadata, resolveDeclaredScopeMismatch, resolveEffectiveActionMetadata, toCustomActionBoolean, toCustomActionDate, toCustomActionNumber } from "./generators/custom-action.js";
3
3
  import { DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, buildChangeEventStream, changeEventSubscribersAtCapacity, eventStreamCapacityExceededResponse, normalizeEventsMaxSubscribers, signalVisibleToTenant, tryReserveChangeEventSubscriberSlot } from "./generators/events-route.js";
4
4
  import { runWithTenantGate, setTenantEntryPointRunner } from "./generators/tenant-gate.js";
5
5
  import { MCPGenerator, MCP_STABLE_CATALOG_TTL_MS, resolveMCPToolListCacheHint, sortMCPTools } from "./generators/mcp.js";
@@ -0,0 +1,12 @@
1
+ import type * as NodeHost from './host.js';
2
+ /**
3
+ * Opens a PGlite database. Rejects the other engines, which are Node-only,
4
+ * instead of silently opening something different from what was asked.
5
+ */
6
+ export declare const getDatabase: typeof NodeHost.getDatabase;
7
+ export declare const buildWhere: typeof NodeHost.buildWhere;
8
+ export declare const raw: typeof NodeHost.raw;
9
+ export declare const NestedTransactionError: typeof NodeHost.NestedTransactionError;
10
+ export declare const importAI: typeof NodeHost.importAI;
11
+ export declare const discoverInstalledSmrtPackages: typeof NodeHost.discoverInstalledSmrtPackages;
12
+ //# sourceMappingURL=host.browser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.browser.d.ts","sourceRoot":"","sources":["../src/host.browser.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,KAAK,QAAQ,MAAM,WAAW,CAAC;AAE3C;;;GAGG;AACH,eAAO,MAAM,WAAW,EAAE,OAAO,QAAQ,CAAC,WAQzC,CAAC;AAEF,eAAO,MAAM,UAAU,EAAE,OAAO,QAAQ,CAAC,UAA0B,CAAC;AACpE,eAAO,MAAM,GAAG,EAAE,OAAO,QAAQ,CAAC,GAAY,CAAC;AAC/C,eAAO,MAAM,sBAAsB,EAAE,OAAO,QAAQ,CAAC,sBAC1B,CAAC;AAE5B,eAAO,MAAM,QAAQ,EAAE,OAAO,QAAQ,CAAC,QAGpC,CAAC;AAEJ,eAAO,MAAM,6BAA6B,EAAE,OAAO,QAAQ,CAAC,6BAC5C,CAAC"}
@@ -0,0 +1,30 @@
1
+ import { getDatabase as getDatabase$1 } from "@happyvertical/sql/pglite";
2
+ import { NestedTransactionError as NestedTransactionError$1, buildWhere as buildWhere$1, raw as raw$1 } from "@happyvertical/sql/query";
3
+ //#region src/host.browser.ts
4
+ /**
5
+ * Browser build of `host.ts` (#2838): selected through `package.json#browser`.
6
+ *
7
+ * Persistence runs on `@happyvertical/sql/pglite`, the SDK's browser-safe
8
+ * adapter. Driver-independent query helpers come from `@happyvertical/sql/query`.
9
+ * The AI SDK and installed-package discovery have no browser build either.
10
+ *
11
+ * Every export is typed against `host.ts`, so the two cannot drift.
12
+ */
13
+ /**
14
+ * Opens a PGlite database. Rejects the other engines, which are Node-only,
15
+ * instead of silently opening something different from what was asked.
16
+ */
17
+ var getDatabase = (options) => {
18
+ const requested = options?.type;
19
+ if (requested !== void 0 && requested !== "pglite") throw new Error(`[smrt-core] Database type "${requested}" is not available in the browser; use type "pglite"`);
20
+ return getDatabase$1(options);
21
+ };
22
+ var buildWhere = buildWhere$1;
23
+ var raw = raw$1;
24
+ var NestedTransactionError = NestedTransactionError$1;
25
+ var importAI = () => Promise.reject(/* @__PURE__ */ new Error("[smrt-core] AI providers are not available in the browser"));
26
+ var discoverInstalledSmrtPackages = async () => [];
27
+ //#endregion
28
+ export { NestedTransactionError, buildWhere, discoverInstalledSmrtPackages, getDatabase, importAI, raw };
29
+
30
+ //# sourceMappingURL=host.browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.browser.js","names":[],"sources":["../src/host.browser.ts"],"sourcesContent":["/**\n * Browser build of `host.ts` (#2838): selected through `package.json#browser`.\n *\n * Persistence runs on `@happyvertical/sql/pglite`, the SDK's browser-safe\n * adapter. Driver-independent query helpers come from `@happyvertical/sql/query`.\n * The AI SDK and installed-package discovery have no browser build either.\n *\n * Every export is typed against `host.ts`, so the two cannot drift.\n */\nimport { getDatabase as getPGliteDatabase } from '@happyvertical/sql/pglite';\nimport {\n NestedTransactionError as SdkNestedTransactionError,\n buildWhere as sdkBuildWhere,\n raw as sdkRaw,\n} from '@happyvertical/sql/query';\nimport type * as NodeHost from './host.js';\n\n/**\n * Opens a PGlite database. Rejects the other engines, which are Node-only,\n * instead of silently opening something different from what was asked.\n */\nexport const getDatabase: typeof NodeHost.getDatabase = (options) => {\n const requested = (options as { type?: string } | undefined)?.type;\n if (requested !== undefined && requested !== 'pglite') {\n throw new Error(\n `[smrt-core] Database type \"${requested}\" is not available in the browser; use type \"pglite\"`,\n );\n }\n return getPGliteDatabase(options as Parameters<typeof getPGliteDatabase>[0]);\n};\n\nexport const buildWhere: typeof NodeHost.buildWhere = sdkBuildWhere;\nexport const raw: typeof NodeHost.raw = sdkRaw;\nexport const NestedTransactionError: typeof NodeHost.NestedTransactionError =\n SdkNestedTransactionError;\n\nexport const importAI: typeof NodeHost.importAI = () =>\n Promise.reject(\n new Error('[smrt-core] AI providers are not available in the browser'),\n );\n\nexport const discoverInstalledSmrtPackages: typeof NodeHost.discoverInstalledSmrtPackages =\n async () => [];\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,IAAa,eAA4C,YAAY;CACnE,MAAM,YAAa,SAA2C;CAC9D,IAAI,cAAc,KAAA,KAAa,cAAc,UAC3C,MAAM,IAAI,MACR,8BAA8B,UAAU,qDAC1C;CAEF,OAAO,cAAkB,OAAkD;AAC7E;AAEA,IAAa,aAAyC;AACtD,IAAa,MAA2B;AACxC,IAAa,yBACX;AAEF,IAAa,iBACX,QAAQ,uBACN,IAAI,MAAM,2DAA2D,CACvE;AAEF,IAAa,gCACX,YAAY,CAAC"}
package/dist/host.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Node host services (#2838).
3
+ *
4
+ * The modules that need a Node-only dependency reach it through this file so
5
+ * the browser build can swap it: `package.json#browser` maps
6
+ * `./dist/host.js` to `./dist/host.browser.js`, which exposes the same names
7
+ * without importing `pg`, the `@happyvertical/sql` root, the AI SDK's CLI
8
+ * providers, or the filesystem-backed package discovery. Node consumers and
9
+ * every test resolve this file, so their behaviour is unchanged. A new
10
+ * export here needs a counterpart in `host.browser.ts` (it is typechecked
11
+ * against this module).
12
+ */
13
+ export { buildWhere, getDatabase, NestedTransactionError, raw, } from '@happyvertical/sql';
14
+ /** The AI SDK, loaded on first use to keep it off the cold-start path (#2894). */
15
+ export declare function importAI(): Promise<typeof import('@happyvertical/ai')>;
16
+ /** Names of the installed SMRT packages whose manifest declares `moduleType: "smrt"`. */
17
+ export declare function discoverInstalledSmrtPackages(): Promise<string[]>;
18
+ //# sourceMappingURL=host.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EACL,UAAU,EACV,WAAW,EACX,sBAAsB,EACtB,GAAG,GACJ,MAAM,oBAAoB,CAAC;AAE5B,kFAAkF;AAClF,wBAAgB,QAAQ,IAAI,OAAO,CAAC,cAAc,mBAAmB,CAAC,CAAC,CAEtE;AAED,yFAAyF;AACzF,wBAAsB,6BAA6B,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC,CAOvE"}
package/dist/host.js ADDED
@@ -0,0 +1,15 @@
1
+ import { NestedTransactionError, buildWhere, getDatabase as getDatabase$1, raw } from "@happyvertical/sql";
2
+ //#region src/host.ts
3
+ /** The AI SDK, loaded on first use to keep it off the cold-start path (#2894). */
4
+ function importAI() {
5
+ return import("@happyvertical/ai");
6
+ }
7
+ /** Names of the installed SMRT packages whose manifest declares `moduleType: "smrt"`. */
8
+ async function discoverInstalledSmrtPackages() {
9
+ const { discoverSmrtPackages } = await (import.meta.url.endsWith(".ts") ? import("./manifest/discover-smrt-packages.js") : import("./manifest/discover-smrt-packages.js"));
10
+ return discoverSmrtPackages();
11
+ }
12
+ //#endregion
13
+ export { NestedTransactionError, buildWhere, discoverInstalledSmrtPackages, getDatabase$1 as getDatabase, importAI, raw };
14
+
15
+ //# sourceMappingURL=host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.js","names":[],"sources":["../src/host.ts"],"sourcesContent":["/**\n * Node host services (#2838).\n *\n * The modules that need a Node-only dependency reach it through this file so\n * the browser build can swap it: `package.json#browser` maps\n * `./dist/host.js` to `./dist/host.browser.js`, which exposes the same names\n * without importing `pg`, the `@happyvertical/sql` root, the AI SDK's CLI\n * providers, or the filesystem-backed package discovery. Node consumers and\n * every test resolve this file, so their behaviour is unchanged. A new\n * export here needs a counterpart in `host.browser.ts` (it is typechecked\n * against this module).\n */\n\nexport {\n buildWhere,\n getDatabase,\n NestedTransactionError,\n raw,\n} from '@happyvertical/sql';\n\n/** The AI SDK, loaded on first use to keep it off the cold-start path (#2894). */\nexport function importAI(): Promise<typeof import('@happyvertical/ai')> {\n return import('@happyvertical/ai');\n}\n\n/** Names of the installed SMRT packages whose manifest declares `moduleType: \"smrt\"`. */\nexport async function discoverInstalledSmrtPackages(): Promise<string[]> {\n const discoverSpecifier = import.meta.url.endsWith('.ts')\n ? './manifest/discover-smrt-packages.ts'\n : './manifest/discover-smrt-packages.js';\n\n const { discoverSmrtPackages } = await import(discoverSpecifier);\n return discoverSmrtPackages();\n}\n"],"mappings":";;;AAqBA,SAAgB,WAAwD;CACtE,OAAO,OAAO;AAChB;;AAGA,eAAsB,gCAAmD;CAKvE,MAAM,EAAE,yBAAyB,OAJP,OAAO,KAAK,IAAI,SAAS,KAAK,IAAA,OACpD,0CAAA,OACA;CAGJ,OAAO,qBAAqB;AAC9B"}
package/dist/index.d.ts CHANGED
@@ -62,6 +62,7 @@ export { applyPostgresPermissions, type PostgresPermissionContract, type Postgre
62
62
  export { applyPostgresRuntimeTimeouts, DEFAULT_POSTGRES_TIMEOUTS, POSTGRES_TIMEOUT_ENV_VARS, type PostgresTimeoutConfig, type ResolvedPostgresTimeouts, resolvePostgresTimeouts, } from "./postgres-timeouts.js";
63
63
  export { buildDefaultListOrderBy, DEFAULT_LIST_LIMIT, DEFAULT_LIST_ORDER_BY, type ListBoundOptions, MAX_LIST_LIMIT, QueryBoundsError, QueryOrderByError, resolveListLimit, resolveListOffset, } from "./query-bounds.js";
64
64
  export { SmrtRecipe, type SmrtRecipeModel, type SmrtRecipeModelOptions, type SmrtRecipeNavEntry, } from "./recipe.js";
65
+ export { deriveRecipeDemo, effectiveRecipeDemo, hasBrowserOption, isMockableProvider, isServerProvider, MOCK_PROVIDER_OPTION, type PackageBrowserCapability, RECIPE_DEMO_MODES, type RecipeDemo, type RecipeDemoDerivation, type RecipeDemoMode, } from "./recipe-demo.js";
65
66
  export { buildConnectSection, buildGlossary, type ConnectSection, type ConnectSurface, createRecipeHelp, extractFieldRefs, findField, type GlossaryEntry, type HelpBlock, type HelpField, type HelpModel, helpToMarkdown, type Inline, parseHelp, type RecipeHelp, type RenderedHelp, type RenderHelpOptions, renderHelp, resolveHelp, validateHelp, } from "./recipe-help.js";
66
67
  export * from "./registry.js";
67
68
  export { smrt as smrtRegistry } from "./registry.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAGH,cAAc,qBAAkB,CAAC;AACjC,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EACL,gBAAgB,EAChB,KAAK,WAAW,EAChB,KAAK,2BAA2B,EAChC,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACxB,KAAK,aAAa,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,KAAK,cAAc,EACnB,gBAAgB,GACjB,MAAM,cAAW,CAAC;AAGnB,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,iBAAiB,EACtB,YAAY,EACZ,aAAa,EACb,cAAc,EACd,4BAA4B,EAC5B,iBAAiB,EACjB,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,eAAe,EACpB,qBAAqB,EACrB,eAAe,EACf,qBAAqB,EACrB,KAAK,iBAAiB,EACtB,eAAe,EACf,eAAe,EACf,2BAA2B,EAC3B,iBAAiB,EACjB,eAAe,EACf,wBAAwB,EACxB,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