@rebasepro/server-core 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/package.json +14 -14
  2. package/src/api/errors.ts +16 -2
  3. package/src/api/graphql/graphql-schema-generator.ts +45 -10
  4. package/src/api/server.ts +10 -2
  5. package/src/api/types.ts +6 -0
  6. package/src/auth/adapter-middleware.ts +10 -2
  7. package/src/auth/admin-roles-route.ts +36 -0
  8. package/src/auth/admin-users-route.ts +302 -0
  9. package/src/auth/api-keys/api-key-middleware.ts +4 -3
  10. package/src/auth/api-keys/api-key-routes.ts +12 -2
  11. package/src/auth/api-keys/api-key-store.ts +83 -66
  12. package/src/auth/api-keys/api-key-types.ts +8 -0
  13. package/src/auth/apple-oauth.ts +2 -1
  14. package/src/auth/auth-hooks.ts +21 -0
  15. package/src/auth/bitbucket-oauth.ts +2 -1
  16. package/src/auth/builtin-auth-adapter.ts +28 -4
  17. package/src/auth/custom-auth-adapter.ts +2 -0
  18. package/src/auth/discord-oauth.ts +2 -1
  19. package/src/auth/facebook-oauth.ts +2 -1
  20. package/src/auth/github-oauth.ts +2 -1
  21. package/src/auth/gitlab-oauth.ts +2 -1
  22. package/src/auth/google-oauth.ts +8 -4
  23. package/src/auth/index.ts +2 -0
  24. package/src/auth/interfaces.ts +27 -0
  25. package/src/auth/linkedin-oauth.ts +2 -1
  26. package/src/auth/magic-link-routes.ts +167 -0
  27. package/src/auth/mfa-crypto.ts +91 -0
  28. package/src/auth/mfa-routes.ts +34 -10
  29. package/src/auth/microsoft-oauth.ts +2 -1
  30. package/src/auth/middleware.ts +10 -1
  31. package/src/auth/reset-password-admin.ts +17 -1
  32. package/src/auth/routes.ts +77 -8
  33. package/src/auth/session-routes.ts +15 -3
  34. package/src/auth/slack-oauth.ts +2 -1
  35. package/src/auth/spotify-oauth.ts +2 -1
  36. package/src/auth/twitter-oauth.ts +8 -1
  37. package/src/cron/cron-store.ts +25 -23
  38. package/src/email/index.ts +3 -2
  39. package/src/email/templates.ts +82 -0
  40. package/src/email/types.ts +16 -0
  41. package/src/init.ts +137 -5
  42. package/src/services/routed-realtime-service.ts +113 -0
  43. package/src/utils/dev-port.ts +13 -7
  44. package/test/auth-routes.test.ts +54 -4
  45. package/test/custom-auth-adapter.test.ts +20 -1
  46. package/test/env.test.ts +9 -19
  47. package/test/multi-datasource-routing.test.ts +113 -0
  48. package/test/routed-realtime-service.test.ts +86 -0
  49. package/test/transform-auth-response.test.ts +305 -0
  50. package/build-errors.txt +0 -52
  51. package/dist/api/ast-schema-editor.d.ts +0 -21
  52. package/dist/api/collections_for_test/callbacks_test_collection.d.ts +0 -2
  53. package/dist/api/errors.d.ts +0 -53
  54. package/dist/api/graphql/graphql-schema-generator.d.ts +0 -35
  55. package/dist/api/graphql/index.d.ts +0 -1
  56. package/dist/api/index.d.ts +0 -9
  57. package/dist/api/logs-routes.d.ts +0 -37
  58. package/dist/api/openapi-generator.d.ts +0 -16
  59. package/dist/api/rest/api-generator.d.ts +0 -88
  60. package/dist/api/rest/index.d.ts +0 -1
  61. package/dist/api/rest/query-parser.d.ts +0 -11
  62. package/dist/api/schema-editor-routes.d.ts +0 -3
  63. package/dist/api/server.d.ts +0 -40
  64. package/dist/api/types.d.ts +0 -98
  65. package/dist/auth/adapter-middleware.d.ts +0 -37
  66. package/dist/auth/admin-user-ops.d.ts +0 -79
  67. package/dist/auth/api-keys/api-key-middleware.d.ts +0 -39
  68. package/dist/auth/api-keys/api-key-permission-guard.d.ts +0 -32
  69. package/dist/auth/api-keys/api-key-routes.d.ts +0 -20
  70. package/dist/auth/api-keys/api-key-store.d.ts +0 -35
  71. package/dist/auth/api-keys/api-key-types.d.ts +0 -88
  72. package/dist/auth/api-keys/index.d.ts +0 -17
  73. package/dist/auth/apple-oauth.d.ts +0 -30
  74. package/dist/auth/auth-hooks.d.ts +0 -225
  75. package/dist/auth/bitbucket-oauth.d.ts +0 -11
  76. package/dist/auth/builtin-auth-adapter.d.ts +0 -49
  77. package/dist/auth/crypto-utils.d.ts +0 -16
  78. package/dist/auth/custom-auth-adapter.d.ts +0 -39
  79. package/dist/auth/discord-oauth.d.ts +0 -14
  80. package/dist/auth/facebook-oauth.d.ts +0 -14
  81. package/dist/auth/github-oauth.d.ts +0 -15
  82. package/dist/auth/gitlab-oauth.d.ts +0 -13
  83. package/dist/auth/google-oauth.d.ts +0 -47
  84. package/dist/auth/index.d.ts +0 -36
  85. package/dist/auth/interfaces.d.ts +0 -401
  86. package/dist/auth/jwt.d.ts +0 -55
  87. package/dist/auth/linkedin-oauth.d.ts +0 -18
  88. package/dist/auth/mfa-routes.d.ts +0 -6
  89. package/dist/auth/mfa.d.ts +0 -49
  90. package/dist/auth/microsoft-oauth.d.ts +0 -16
  91. package/dist/auth/middleware.d.ts +0 -106
  92. package/dist/auth/password.d.ts +0 -22
  93. package/dist/auth/rate-limiter.d.ts +0 -50
  94. package/dist/auth/reset-password-admin.d.ts +0 -29
  95. package/dist/auth/rls-scope.d.ts +0 -31
  96. package/dist/auth/routes.d.ts +0 -33
  97. package/dist/auth/session-routes.d.ts +0 -25
  98. package/dist/auth/slack-oauth.d.ts +0 -12
  99. package/dist/auth/spotify-oauth.d.ts +0 -12
  100. package/dist/auth/twitter-oauth.d.ts +0 -18
  101. package/dist/backend-CIxN4FVm.js +0 -15
  102. package/dist/backend-CIxN4FVm.js.map +0 -1
  103. package/dist/chunk-Dze3rakg.js +0 -42
  104. package/dist/collections/BackendCollectionRegistry.d.ts +0 -13
  105. package/dist/collections/loader.d.ts +0 -5
  106. package/dist/cron/cron-loader.d.ts +0 -17
  107. package/dist/cron/cron-routes.d.ts +0 -14
  108. package/dist/cron/cron-scheduler.d.ts +0 -106
  109. package/dist/cron/cron-store.d.ts +0 -32
  110. package/dist/cron/index.d.ts +0 -6
  111. package/dist/db/interfaces.d.ts +0 -18
  112. package/dist/dist-CZKP-Xz4.js +0 -832
  113. package/dist/dist-CZKP-Xz4.js.map +0 -1
  114. package/dist/email/index.d.ts +0 -6
  115. package/dist/email/smtp-email-service.d.ts +0 -25
  116. package/dist/email/templates.d.ts +0 -42
  117. package/dist/email/types.d.ts +0 -108
  118. package/dist/env.d.ts +0 -102
  119. package/dist/from-VbwD7xRf.js +0 -3849
  120. package/dist/from-VbwD7xRf.js.map +0 -1
  121. package/dist/functions/function-loader.d.ts +0 -17
  122. package/dist/functions/function-routes.d.ts +0 -10
  123. package/dist/functions/index.d.ts +0 -3
  124. package/dist/history/history-routes.d.ts +0 -23
  125. package/dist/history/index.d.ts +0 -1
  126. package/dist/index.d.ts +0 -33
  127. package/dist/index.es.js +0 -61731
  128. package/dist/index.es.js.map +0 -1
  129. package/dist/index.umd.js +0 -73221
  130. package/dist/index.umd.js.map +0 -1
  131. package/dist/init/docs.d.ts +0 -4
  132. package/dist/init/health.d.ts +0 -2
  133. package/dist/init/middlewares.d.ts +0 -10
  134. package/dist/init/shutdown.d.ts +0 -11
  135. package/dist/init/storage.d.ts +0 -5
  136. package/dist/init.d.ts +0 -258
  137. package/dist/jwt-DHcQRGC3.js +0 -4168
  138. package/dist/jwt-DHcQRGC3.js.map +0 -1
  139. package/dist/logger-BYU66ENZ.js +0 -94
  140. package/dist/logger-BYU66ENZ.js.map +0 -1
  141. package/dist/ms-BeBSuOXN.js +0 -125
  142. package/dist/ms-BeBSuOXN.js.map +0 -1
  143. package/dist/multipart-parser-CedBDOeC.js +0 -299
  144. package/dist/multipart-parser-CedBDOeC.js.map +0 -1
  145. package/dist/serve-spa.d.ts +0 -30
  146. package/dist/services/driver-registry.d.ts +0 -78
  147. package/dist/services/webhook-service.d.ts +0 -29
  148. package/dist/singleton.d.ts +0 -35
  149. package/dist/src-COaj0G3P.js +0 -1182
  150. package/dist/src-COaj0G3P.js.map +0 -1
  151. package/dist/storage/LocalStorageController.d.ts +0 -46
  152. package/dist/storage/S3StorageController.d.ts +0 -36
  153. package/dist/storage/image-transform.d.ts +0 -50
  154. package/dist/storage/index.d.ts +0 -28
  155. package/dist/storage/routes.d.ts +0 -38
  156. package/dist/storage/storage-registry.d.ts +0 -78
  157. package/dist/storage/tus-handler.d.ts +0 -51
  158. package/dist/storage/types.d.ts +0 -103
  159. package/dist/types/index.d.ts +0 -11
  160. package/dist/utils/dev-port.d.ts +0 -35
  161. package/dist/utils/logger.d.ts +0 -31
  162. package/dist/utils/logging.d.ts +0 -9
  163. package/dist/utils/request-id.d.ts +0 -4
  164. package/dist/utils/request-logger.d.ts +0 -19
  165. package/dist/utils/sql.d.ts +0 -27
@@ -1,50 +0,0 @@
1
- import { MiddlewareHandler } from "hono";
2
- import { HonoEnv } from "../api/types";
3
- interface RateLimiterOptions {
4
- /** Time window in milliseconds (default: 15 minutes) */
5
- windowMs?: number;
6
- /** Maximum requests per window (default: 100) */
7
- limit?: number;
8
- /** Key generator function. Defaults to IP-based keying. */
9
- keyGenerator?: (c: Parameters<MiddlewareHandler<HonoEnv>>[0]) => string;
10
- /** Custom message for rate limit responses */
11
- message?: string;
12
- }
13
- /**
14
- * Create a rate-limiting middleware.
15
- *
16
- * Uses a sliding window algorithm: only timestamps within the last
17
- * `windowMs` milliseconds are counted. Old entries are garbage-collected
18
- * every `windowMs` to prevent unbounded memory growth.
19
- */
20
- export declare function createRateLimiter(options?: RateLimiterOptions): MiddlewareHandler<HonoEnv>;
21
- /**
22
- * Pre-configured rate limiter for general auth endpoints (login, register).
23
- * 200 requests per 15 minutes per IP.
24
- */
25
- export declare const defaultAuthLimiter: MiddlewareHandler<HonoEnv>;
26
- /**
27
- * Pre-configured strict rate limiter for sensitive endpoints (password reset, verification).
28
- * 50 requests per 15 minutes per IP.
29
- */
30
- export declare const strictAuthLimiter: MiddlewareHandler<HonoEnv>;
31
- /**
32
- * Key generator for API-key-based rate limiting.
33
- *
34
- * Uses the API key ID (from `c.get("apiKey")`) as the rate limit key.
35
- * Falls back to IP-based keying when the request is not authenticated
36
- * via an API key.
37
- */
38
- export declare function apiKeyKeyGenerator(c: Parameters<MiddlewareHandler<HonoEnv>>[0]): string;
39
- /**
40
- * Create a rate limiter specifically for API key requests.
41
- *
42
- * When a request is authenticated via an API key that has a `rate_limit`
43
- * configured, this limiter enforces per-key limits using the key's ID
44
- * as the rate limit bucket.
45
- *
46
- * @param defaultLimit - Fallback limit when the key has no `rate_limit` set.
47
- * @param windowMs - Time window in milliseconds (default: 15 minutes).
48
- */
49
- export declare function createApiKeyRateLimiter(defaultLimit?: number, windowMs?: number): MiddlewareHandler<HonoEnv>;
50
- export {};
@@ -1,29 +0,0 @@
1
- /**
2
- * Standalone admin endpoint for resetting a user's password.
3
- *
4
- * Hook resolution order:
5
- * 1. Collection-level hook (`auth.onResetPassword` on the collection)
6
- * 2. Backend-level hook (`AuthHooks.onAdminResetPassword`)
7
- * 3. Built-in default (send reset email, or generate temp password)
8
- */
9
- import { Hono } from "hono";
10
- import type { AuthRepository } from "./interfaces";
11
- import type { AuthHooks } from "./auth-hooks";
12
- import type { EmailService, EmailConfig } from "../email";
13
- import type { HonoEnv } from "../api/types";
14
- import type { AuthCollectionConfig } from "@rebasepro/types";
15
- export interface ResetPasswordRouteConfig {
16
- authRepo: AuthRepository;
17
- emailService?: EmailService;
18
- emailConfig?: EmailConfig;
19
- serviceKey?: string;
20
- authHooks?: AuthHooks;
21
- /** The parsed auth config from the collection, if available. */
22
- collectionAuthConfig?: AuthCollectionConfig;
23
- }
24
- /**
25
- * Create a standalone admin route for resetting user passwords.
26
- *
27
- * Mounts: POST /users/:userId/reset-password
28
- */
29
- export declare function createResetPasswordRoute(config: ResetPasswordRouteConfig): Hono<HonoEnv>;
@@ -1,31 +0,0 @@
1
- /**
2
- * Shared RLS (Row-Level Security) scoping helper.
3
- *
4
- * DataDrivers may implement a `withAuth()` method that returns a scoped
5
- * clone of the driver with RLS policies applied for the given user.
6
- * This is database-specific (e.g. Postgres SET LOCAL ROLE) and is not
7
- * part of the core DataDriver interface.
8
- *
9
- * This module provides the shared duck-typing logic used by the
10
- * adapter-aware middleware.
11
- *
12
- * @module
13
- */
14
- import type { DataDriver } from "@rebasepro/types";
15
- /**
16
- * Scope a DataDriver via `withAuth()` for RLS.
17
- *
18
- * SECURITY: If `withAuth()` is available but fails, the error is re-thrown
19
- * so the request is **denied** rather than proceeding with unscoped access
20
- * (fail-closed behavior).
21
- *
22
- * If the driver does not support RLS, the original driver is returned.
23
- *
24
- * @param driver - The DataDriver to scope.
25
- * @param user - The authenticated user identity for RLS.
26
- * @returns The RLS-scoped DataDriver (or the original if RLS is unsupported).
27
- */
28
- export declare function scopeDataDriver(driver: DataDriver, user: {
29
- uid: string;
30
- roles?: string[];
31
- }): Promise<DataDriver>;
@@ -1,33 +0,0 @@
1
- import { Hono } from "hono";
2
- import type { AuthRepository, OAuthProvider } from "./interfaces";
3
- import type { AuthHooks } from "./auth-hooks";
4
- import { EmailService, EmailConfig } from "../email";
5
- import { HonoEnv } from "../api/types";
6
- /**
7
- * Shared configuration for auth and admin route factories.
8
- */
9
- export interface AuthModuleConfig {
10
- authRepo: AuthRepository;
11
- emailService?: EmailService;
12
- emailConfig?: EmailConfig;
13
- /** Allow new user registration (default: false). */
14
- allowRegistration?: boolean;
15
- /** Default role ID to assign to new users (default: none). Must NOT be "admin". */
16
- defaultRole?: string;
17
- /** Optional array of OAuth providers */
18
- oauthProviders?: OAuthProvider<any>[];
19
- /** When true, blocks all self-registration regardless of `allowRegistration`. */
20
- disableSelfRegistration?: boolean;
21
- /**
22
- * Auth hooks for customizing password hashing, credential
23
- * verification, lifecycle hooks, etc.
24
- */
25
- authHooks?: AuthHooks;
26
- /**
27
- * Callback that checks if bootstrap has already been completed.
28
- * Used by GET /auth/config to report `needsSetup` status.
29
- * When not provided, falls back to checking if any users exist.
30
- */
31
- isBootstrapCompleted?: () => Promise<boolean>;
32
- }
33
- export declare function createAuthRoutes(config: AuthModuleConfig): Hono<HonoEnv>;
@@ -1,25 +0,0 @@
1
- import { Hono } from "hono";
2
- import { z } from "zod";
3
- import { HonoEnv } from "../api/types";
4
- import type { AuthModuleConfig } from "./routes";
5
- import { resolveAuthHooks } from "./auth-hooks";
6
- interface SessionRoutesConfig {
7
- router: Hono<HonoEnv>;
8
- config: AuthModuleConfig;
9
- ops: ReturnType<typeof resolveAuthHooks>;
10
- parseBody: <T>(schema: z.ZodSchema<T>, body: unknown) => T;
11
- buildAuthResponse: (user: {
12
- id: string;
13
- email: string;
14
- displayName?: string | null;
15
- photoUrl?: string | null;
16
- metadata?: Record<string, unknown> | null;
17
- }, roleIds: string[], accessToken: string, refreshToken: string) => unknown;
18
- createSessionAndTokens: (userId: string, userAgent: string, ipAddress: string) => Promise<{
19
- roleIds: string[];
20
- accessToken: string;
21
- refreshToken: string;
22
- }>;
23
- }
24
- export declare function mountSessionRoutes(opts: SessionRoutesConfig): void;
25
- export {};
@@ -1,12 +0,0 @@
1
- import type { OAuthProvider } from "./interfaces";
2
- /**
3
- * Creates a Slack OAuth Provider integration (OAuth 2.0 / "Sign in with Slack").
4
- * Uses the OpenID Connect flow with the "openid,email,profile" scopes.
5
- */
6
- export declare function createSlackProvider(config: {
7
- clientId: string;
8
- clientSecret: string;
9
- }): OAuthProvider<{
10
- code: string;
11
- redirectUri: string;
12
- }>;
@@ -1,12 +0,0 @@
1
- import type { OAuthProvider } from "./interfaces";
2
- /**
3
- * Creates a Spotify OAuth Provider integration.
4
- * Uses the authorization code flow with the "user-read-email" scope.
5
- */
6
- export declare function createSpotifyProvider(config: {
7
- clientId: string;
8
- clientSecret: string;
9
- }): OAuthProvider<{
10
- code: string;
11
- redirectUri: string;
12
- }>;
@@ -1,18 +0,0 @@
1
- import type { OAuthProvider } from "./interfaces";
2
- /**
3
- * Creates a Twitter/X OAuth 2.0 Provider integration.
4
- *
5
- * Uses OAuth 2.0 with PKCE (authorization code flow). The frontend must include
6
- * the PKCE `code_verifier` when sending the authorization code.
7
- *
8
- * Twitter API v2 requires the "tweet.read" and "users.read" scopes at minimum,
9
- * plus "offline.access" if refresh tokens are needed on Twitter's side.
10
- */
11
- export declare function createTwitterProvider(config: {
12
- clientId: string;
13
- clientSecret: string;
14
- }): OAuthProvider<{
15
- code: string;
16
- redirectUri: string;
17
- codeVerifier: string;
18
- }>;
@@ -1,15 +0,0 @@
1
- import { createRequire as __createRequire } from "module";
2
- import "process";
3
- __createRequire(import.meta.url);
4
- //#region ../types/src/types/backend.ts
5
- /**
6
- * Type guard: does this admin support SQL operations?
7
- * @group Admin
8
- */
9
- function isSQLAdmin(admin) {
10
- return !!admin && typeof admin.executeSql === "function";
11
- }
12
- //#endregion
13
- export { isSQLAdmin as t };
14
-
15
- //# sourceMappingURL=backend-CIxN4FVm.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"backend-CIxN4FVm.js","names":[],"sources":["../../types/src/types/backend.ts"],"sourcesContent":["import type { Entity } from \"./entities\";\nimport type { EntityCollection, FilterValues, WhereFilterOp } from \"./collections\";\nimport type { AuthAdapter } from \"./auth_adapter\";\n\n// =============================================================================\n// DATABASE CONNECTION INTERFACES\n// =============================================================================\n\n/**\n * Abstract database connection interface.\n * Represents a connection to any database system.\n */\nexport interface DatabaseConnection {\n /**\n * Type identifier for this database (e.g., 'postgres', 'mongodb', 'mysql')\n */\n readonly type: string;\n\n /**\n * Whether the connection is currently active\n */\n readonly isConnected?: boolean;\n\n /**\n * Close the database connection and release resources.\n */\n close?(): Promise<void>;\n}\n\n// =============================================================================\n// QUERY BUILDING INTERFACES\n// =============================================================================\n\n/**\n * A single filter condition for database queries\n */\nexport interface QueryFilter {\n field: string;\n operator: WhereFilterOp;\n value: unknown;\n}\n\n/**\n * Options for fetching a collection of entities\n */\nexport interface FetchCollectionOptions<M extends Record<string, unknown> = Record<string, unknown>> {\n filter?: FilterValues<Extract<keyof M, string>>;\n orderBy?: string;\n order?: \"desc\" | \"asc\";\n limit?: number;\n offset?: number;\n startAfter?: unknown;\n searchString?: string;\n databaseId?: string;\n collection?: EntityCollection;\n}\n\n/**\n * Options for searching entities\n */\nexport interface SearchOptions<M extends Record<string, unknown> = Record<string, unknown>> {\n filter?: FilterValues<Extract<keyof M, string>>;\n orderBy?: string;\n order?: \"desc\" | \"asc\";\n limit?: number;\n databaseId?: string;\n collection?: EntityCollection;\n}\n\n/**\n * Options for counting entities\n */\nexport interface CountOptions<M extends Record<string, unknown> = Record<string, unknown>> {\n filter?: FilterValues<Extract<keyof M, string>>;\n searchString?: string;\n databaseId?: string;\n}\n\n/**\n * Abstract condition builder interface.\n * Implementations translate Rebase filter conditions to database-specific queries.\n *\n * Note: This interface can be implemented as instance methods or as a class with static methods.\n * For static implementations (like DrizzleConditionBuilder), use the ConditionBuilderStatic type.\n *\n * @template T The type of condition returned by the builder (e.g., SQL for PostgreSQL, Filter<Document> for MongoDB)\n */\nexport interface ConditionBuilder<T = unknown> {\n /**\n * Build filter conditions from Rebase FilterValues\n */\n buildFilterConditions<M extends Record<string, unknown>>(\n filter: FilterValues<Extract<keyof M, string>>,\n collectionPath: string,\n ...args: unknown[]\n ): T[];\n\n /**\n * Build search conditions for text search\n */\n buildSearchConditions(\n searchString: string,\n properties: Record<string, unknown>,\n ...args: unknown[]\n ): T[];\n\n /**\n * Combine multiple conditions with AND operator\n */\n combineConditionsWithAnd(conditions: T[]): T | undefined;\n\n /**\n * Combine multiple conditions with OR operator\n */\n combineConditionsWithOr(conditions: T[]): T | undefined;\n}\n\n/**\n * Static condition builder type for implementations using static methods.\n * Use this type when the class provides static methods rather than instance methods.\n *\n * @example\n * // DrizzleConditionBuilder satisfies this type\n * const builder: ConditionBuilderStatic<SQL> = DrizzleConditionBuilder;\n */\nexport type ConditionBuilderStatic<T = unknown> = {\n buildFilterConditions<M extends Record<string, unknown>>(\n filter: FilterValues<Extract<keyof M, string>>,\n ...args: unknown[]\n ): T[];\n buildSearchConditions(\n searchString: string,\n properties: Record<string, unknown>,\n ...args: unknown[]\n ): T[];\n combineConditionsWithAnd(conditions: T[]): T | undefined;\n combineConditionsWithOr(conditions: T[]): T | undefined;\n};\n\n// =============================================================================\n// ENTITY REPOSITORY INTERFACES\n// =============================================================================\n\n/**\n * Abstract entity repository interface.\n * Handles all CRUD operations for entities in the database.\n *\n * Implementations should handle:\n * - Entity serialization/deserialization\n * - Relation resolution\n * - ID generation and conversion\n */\nexport interface EntityRepository {\n /**\n * Fetch a single entity by ID\n */\n fetchEntity<M extends Record<string, unknown>>(\n collectionPath: string,\n entityId: string | number,\n databaseId?: string\n ): Promise<Entity<M> | undefined>;\n\n /**\n * Fetch a collection of entities with optional filtering, ordering, and pagination\n */\n fetchCollection<M extends Record<string, unknown>>(\n collectionPath: string,\n options?: FetchCollectionOptions<M>\n ): Promise<Entity<M>[]>;\n\n /**\n * Search entities by text\n */\n searchEntities<M extends Record<string, unknown>>(\n collectionPath: string,\n searchString: string,\n options?: SearchOptions<M>\n ): Promise<Entity<M>[]>;\n\n /**\n * Count entities in a collection\n */\n countEntities<M extends Record<string, unknown>>(\n collectionPath: string,\n options?: CountOptions<M>\n ): Promise<number>;\n\n /**\n * Save an entity (create or update)\n */\n saveEntity<M extends Record<string, unknown>>(\n collectionPath: string,\n values: Partial<M>,\n entityId?: string | number,\n databaseId?: string\n ): Promise<Entity<M>>;\n\n /**\n * Delete an entity by ID\n */\n deleteEntity(\n collectionPath: string,\n entityId: string | number,\n databaseId?: string\n ): Promise<void>;\n\n /**\n * Check if a field value is unique in a collection\n */\n checkUniqueField(\n collectionPath: string,\n fieldName: string,\n value: unknown,\n excludeEntityId?: string,\n databaseId?: string\n ): Promise<boolean>;\n\n}\n\n// =============================================================================\n// REALTIME INTERFACES\n// =============================================================================\n\n/**\n * Configuration for subscribing to a collection\n */\nexport interface CollectionSubscriptionConfig {\n clientId: string;\n path: string;\n filter?: unknown;\n orderBy?: string;\n order?: \"desc\" | \"asc\";\n limit?: number;\n startAfter?: unknown;\n databaseId?: string;\n searchString?: string;\n}\n\n/**\n * Configuration for subscribing to a single entity\n */\nexport interface EntitySubscriptionConfig {\n clientId: string;\n path: string;\n entityId: string | number;\n}\n\n/**\n * Abstract realtime provider interface.\n * Handles real-time subscriptions and notifications for entity changes.\n */\nexport interface RealtimeProvider {\n /**\n * Subscribe to collection changes\n */\n subscribeToCollection(\n subscriptionId: string,\n config: CollectionSubscriptionConfig,\n callback?: (entities: Entity[]) => void\n ): void;\n\n /**\n * Subscribe to single entity changes\n */\n subscribeToEntity(\n subscriptionId: string,\n config: EntitySubscriptionConfig,\n callback?: (entity: Entity | null) => void\n ): void;\n\n /**\n * Unsubscribe from a subscription\n */\n unsubscribe(subscriptionId: string): void;\n\n /**\n * Notify all relevant subscribers of an entity update\n */\n notifyEntityUpdate(\n path: string,\n entityId: string,\n entity: Entity | null,\n databaseId?: string\n ): Promise<void>;\n\n /**\n * Called when the HTTP server is ready and listening.\n * Useful for providers that need the server address for callbacks.\n */\n onServerReady?(serverInfo: { port: number; hostname?: string }): void;\n\n /**\n * Gracefully shut down the realtime provider.\n * Called during server shutdown to clean up resources.\n */\n destroy?(): Promise<void>;\n\n /**\n * Stop the internal LISTEN client (e.g., PostgreSQL LISTEN/NOTIFY).\n * Called during graceful shutdown before closing database connections.\n */\n stopListening?(): Promise<void>;\n}\n\n// =============================================================================\n// COLLECTION REGISTRY INTERFACES\n// =============================================================================\n\n/**\n * Abstract collection registry interface.\n * Manages registration and lookup of entity collections.\n */\nexport interface CollectionRegistryInterface {\n /**\n * Register a collection\n */\n register(collection: EntityCollection): void;\n\n /**\n * Get a collection by its path\n */\n getCollectionByPath(path: string): EntityCollection | undefined;\n\n /**\n * Get all registered collections\n */\n getCollections(): EntityCollection[];\n}\n\n// =============================================================================\n// DATA TRANSFORMER INTERFACES\n// =============================================================================\n\n/**\n * Abstract data transformer interface.\n * Handles serialization/deserialization between frontend and database formats.\n */\nexport interface DataTransformer {\n /**\n * Transform entity data for storage in the database\n */\n serializeToDatabase<M extends Record<string, unknown>>(\n entity: M,\n collection: EntityCollection\n ): Record<string, unknown>;\n\n /**\n * Transform database data back to entity format\n */\n deserializeFromDatabase<M extends Record<string, unknown>>(\n data: Record<string, unknown>,\n collection: EntityCollection\n ): Promise<M>;\n}\n\n// =============================================================================\n// DATABASE ADMIN — CAPABILITY-SPECIFIC INTERFACES (1.3)\n// =============================================================================\n\n/**\n * Administrative operations for SQL-based databases (PostgreSQL, MySQL, etc.).\n * Used by the SQL Editor, RLS Editor, and schema browser.\n *\n * @group Admin\n */\nexport interface SQLAdmin {\n /**\n * Execute raw SQL against the database.\n */\n executeSql(sql: string, options?: { database?: string; role?: string }): Promise<Record<string, unknown>[]>;\n\n /**\n * Fetch the available databases on the server.\n */\n fetchAvailableDatabases?(): Promise<string[]>;\n\n /**\n * Fetch the available database roles.\n */\n fetchAvailableRoles?(): Promise<string[]>;\n\n /**\n * Fetch the current database name.\n */\n fetchCurrentDatabase?(): Promise<string | undefined>;\n}\n\n/**\n * Administrative operations for document-based databases (MongoDB, Firestore, etc.).\n * Used by future document administration tools.\n *\n * @group Admin\n */\nexport interface DocumentAdmin {\n /**\n * Execute an aggregation pipeline or equivalent query.\n */\n executeAggregate?(pipeline: Record<string, unknown>[]): Promise<Record<string, unknown>[]>;\n\n /**\n * Fetch statistics for a collection (document count, size, etc.).\n */\n fetchCollectionStats?(collectionName: string): Promise<{ count: number; sizeBytes?: number }>;\n}\n\n/**\n * Administrative operations for schema management.\n * Shared across SQL and document databases.\n *\n * @group Admin\n */\nexport interface SchemaAdmin {\n /**\n * Fetch database tables/collections not yet mapped to a Rebase collection.\n */\n fetchUnmappedTables?(mappedPaths?: string[]): Promise<string[]>;\n\n /**\n * Fetch column/field metadata for a single table/collection.\n * The return type is generic — SQL backends return TableMetadata,\n * document backends may return a different shape.\n */\n fetchTableMetadata?(tableName: string): Promise<unknown>;\n}\n\n/**\n * Metadata for a database branch.\n * @group Admin\n */\nexport interface BranchInfo {\n /** Branch name (without prefix). */\n name: string;\n /** The database this branch was created from. */\n parentDatabase: string;\n /** When the branch was created. */\n createdAt: Date;\n /** Size in bytes, if available from the server. */\n sizeBytes?: number;\n}\n\n/**\n * Administrative operations for database branching.\n * Allows creating isolated database copies for development/preview workflows.\n *\n * @group Admin\n */\nexport interface BranchAdmin {\n /** Create a new branch (database copy) from the current or specified source database. */\n createBranch(name: string, options?: { source?: string }): Promise<BranchInfo>;\n\n /** Delete a branch database. Cannot delete the main/default database. */\n deleteBranch(name: string): Promise<void>;\n\n /** List all branches (databases that were created via branching). */\n listBranches(): Promise<BranchInfo[]>;\n\n /** Get info about a specific branch. */\n getBranchInfo(name: string): Promise<BranchInfo | undefined>;\n}\n\n/**\n * Union type for all admin capabilities.\n * A backend may implement any combination of these interfaces.\n *\n * Use type guards (`isSQLAdmin`, `isDocumentAdmin`, `isSchemaAdmin`, `isBranchAdmin`)\n * to safely narrow the type before calling methods.\n *\n * @group Admin\n */\nexport type DatabaseAdmin = Partial<SQLAdmin> & Partial<DocumentAdmin> & Partial<SchemaAdmin> & Partial<BranchAdmin>;\n\n/**\n * Type guard: does this admin support SQL operations?\n * @group Admin\n */\nexport function isSQLAdmin(admin: DatabaseAdmin | undefined): admin is SQLAdmin {\n return !!admin && typeof (admin as SQLAdmin).executeSql === \"function\";\n}\n\n/**\n * Type guard: does this admin support document operations?\n * @group Admin\n */\nexport function isDocumentAdmin(admin: DatabaseAdmin | undefined): admin is DocumentAdmin {\n return !!admin && (\n typeof (admin as DocumentAdmin).executeAggregate === \"function\" ||\n typeof (admin as DocumentAdmin).fetchCollectionStats === \"function\"\n );\n}\n\n/**\n * Type guard: does this admin support schema management?\n * @group Admin\n */\nexport function isSchemaAdmin(admin: DatabaseAdmin | undefined): admin is SchemaAdmin {\n return !!admin && (\n typeof (admin as SchemaAdmin).fetchUnmappedTables === \"function\" ||\n typeof (admin as SchemaAdmin).fetchTableMetadata === \"function\"\n );\n}\n\n/**\n * Type guard: does this admin support database branching?\n * @group Admin\n */\nexport function isBranchAdmin(admin: DatabaseAdmin | undefined): admin is BranchAdmin {\n return !!admin && typeof (admin as BranchAdmin).createBranch === \"function\";\n}\n\n// =============================================================================\n// LIFECYCLE INTERFACES (1.4)\n// =============================================================================\n\n/**\n * Health check result returned by `healthCheck()`.\n * @group Lifecycle\n */\nexport interface HealthCheckResult {\n /** Whether the backend is healthy and able to serve requests. */\n healthy: boolean;\n /** Round-trip latency to the database in milliseconds. */\n latencyMs: number;\n /** Optional details (e.g., pool stats, replication lag). */\n details?: Record<string, unknown>;\n}\n\n/**\n * Lifecycle contract for backend components that hold resources\n * (database connections, WebSocket pools, timers, etc.).\n *\n * All methods are optional — simple backends (e.g., in-memory) can skip them.\n * @group Lifecycle\n */\nexport interface BackendLifecycle {\n /**\n * Initialize the backend: open connections, run migrations, seed data.\n * Called once during startup. Idempotent.\n */\n initialize?(): Promise<void>;\n\n /**\n * Check whether the backend is healthy and reachable.\n * Should be fast (< 1 s) and safe to call frequently.\n */\n healthCheck?(): Promise<HealthCheckResult>;\n\n /**\n * Gracefully shut down: close connections, flush buffers, cancel timers.\n * After calling `destroy()`, no other methods should be called.\n */\n destroy?(): Promise<void>;\n}\n\n// =============================================================================\n// BACKEND FACTORY INTERFACES\n// =============================================================================\n\n/**\n * Configuration for creating a database backend\n */\nexport interface BackendConfig {\n /**\n * Type of database backend\n */\n type: string;\n\n /**\n * Database connection (implementation-specific)\n */\n connection: unknown;\n\n /**\n * Schema definition (implementation-specific, e.g., Drizzle schema for PostgreSQL)\n */\n schema?: unknown;\n}\n\n/**\n * A complete backend instance with all required services.\n *\n * Now includes optional lifecycle management and admin capabilities.\n */\nexport interface BackendInstance extends BackendLifecycle {\n /**\n * Entity repository for CRUD operations\n */\n entityRepository: EntityRepository;\n\n /**\n * Realtime provider for subscriptions\n */\n realtimeProvider: RealtimeProvider;\n\n /**\n * Collection registry\n */\n collectionRegistry: CollectionRegistryInterface;\n\n /**\n * The underlying database connection\n */\n connection: DatabaseConnection;\n\n /**\n * Administrative operations (SQL, schema, documents).\n * What's available depends on the backend type — use type guards\n * (`isSQLAdmin`, `isSchemaAdmin`, etc.) to narrow.\n */\n admin?: DatabaseAdmin;\n}\n\n/**\n * Factory function type for creating backend instances\n */\nexport type BackendFactory<TConfig extends BackendConfig = BackendConfig> =\n (config: TConfig) => BackendInstance;\n\n// =============================================================================\n// BACKEND BOOTSTRAPPER (1.2)\n// =============================================================================\n\n/**\n * A `BackendBootstrapper` encapsulates all driver-specific initialization logic.\n *\n * Instead of hard-coding Postgres setup into `initializeRebaseBackend()`,\n * each database backend provides its own bootstrapper that knows how to:\n * - Create the DataDriver from a config object\n * - Optionally initialize auth tables\n * - Optionally create a realtime service\n * - Mount driver-specific API routes\n *\n * The main `initializeRebaseBackend()` becomes a **coordinator** that iterates\n * registered bootstrappers, calls their hooks, and wires the results together.\n *\n * @group Backend\n *\n * @example\n * ```typescript\n * // Third-party MySQL bootstrapper\n * const mysqlBootstrapper: BackendBootstrapper = {\n * type: \"mysql\",\n * initializeDriver: async (config) => new MySQLDataDriver(config.connection),\n * initializeRealtime: async (config) => new MySQLChangeStreamRealtime(config.connection),\n * };\n *\n * initializeRebaseBackend({\n * ...config,\n * bootstrappers: [postgresBootstrapper, mysqlBootstrapper]\n * });\n * ```\n */\nexport interface BackendBootstrapper {\n /**\n * Which driver type this bootstrapper handles.\n * Must match the `type` field on the driver config object\n * (e.g., `\"postgres\"`, `\"mongodb\"`, `\"mysql\"`).\n */\n type: string;\n\n /**\n * Unique identifier for this bootstrapper instance.\n * Used to register the driver in the driver registry.\n * Defaults to `type` if not set.\n */\n id?: string;\n\n /**\n * Whether this bootstrapper provides the default driver.\n * When true, the coordinator uses this driver as the primary one.\n */\n isDefault?: boolean;\n\n /**\n * Run database migrations for this driver.\n * Called by the coordinator after all drivers are initialized.\n */\n runMigrations?(config: unknown, driverResult: InitializedDriver): Promise<void>;\n\n /**\n * Create a DataDriver from the given config.\n * This is the only **required** method.\n */\n initializeDriver(config: unknown): Promise<InitializedDriver>;\n\n /**\n * Initialize auth tables / services if this driver supports them.\n * Return undefined if auth is not supported by this backend.\n */\n initializeAuth?(config: unknown, driverResult: InitializedDriver): Promise<BootstrappedAuth | undefined>;\n\n /**\n * Initialize history tables / services if this driver supports them.\n * Return undefined if history is not supported by this backend.\n */\n initializeHistory?(config: unknown, driverResult: InitializedDriver): Promise<{ historyService: unknown } | undefined>;\n\n /**\n * Create a realtime provider for this driver.\n * Return undefined if the driver does not support realtime.\n */\n initializeRealtime?(config: unknown, driverResult: InitializedDriver): Promise<RealtimeProvider | undefined>;\n\n /**\n * Mount any driver-specific HTTP routes (e.g., custom admin endpoints).\n * Called after all drivers are initialized.\n */\n mountRoutes?(app: unknown, basePath: string, driverResult: InitializedDriver): void;\n\n /**\n * Return admin capabilities for this driver.\n */\n getAdmin?(driverResult: InitializedDriver): DatabaseAdmin | undefined;\n\n /**\n * Initialize WebSocket server for realtime operations.\n */\n initializeWebsockets?(server: unknown, realtimeService: RealtimeProvider, driver: import(\"../controllers/data_driver\").DataDriver, config?: unknown, authAdapter?: AuthAdapter): Promise<void> | void;\n}\n\n/**\n * Result of `BackendBootstrapper.initializeDriver()`.\n * @group Backend\n */\nexport interface InitializedDriver {\n /** The DataDriver instance, ready for use. */\n driver: import(\"../controllers/data_driver\").DataDriver;\n\n /** The realtime service, if the driver created one during init. */\n realtimeProvider?: RealtimeProvider;\n\n /** A collection registry to register schema / tables into. */\n collectionRegistry?: CollectionRegistryInterface;\n\n /** The underlying database connection (for lifecycle management). */\n connection?: DatabaseConnection;\n\n /**\n * Opaque handle that the bootstrapper can use in subsequent hooks\n * (e.g., `initializeAuth`, `mountRoutes`) to access driver internals.\n * Not used by the coordinator.\n */\n internals?: unknown;\n}\n\n/**\n * Result of `BackendBootstrapper.initializeAuth()`.\n * @group Backend\n */\nexport interface BootstrappedAuth {\n /** User management service. */\n userService: unknown;\n /** Role management service (optional, roles are now simple strings). */\n roleService?: unknown;\n /** Email service (optional). */\n emailService?: unknown;\n /** Combined Auth Repository for unified token and user management. */\n authRepository?: unknown;\n}\n"],"mappings":";;;;;;;;AA2dA,SAAgB,WAAW,OAAqD;CAC5E,OAAO,CAAC,CAAC,SAAS,OAAQ,MAAmB,eAAe;AAChE"}
@@ -1,42 +0,0 @@
1
- import { createRequire as __createRequire } from "module";
2
- import "process";
3
- const require = __createRequire(import.meta.url);
4
- //#region \0rolldown/runtime.js
5
- var __create = Object.create;
6
- var __defProp = Object.defineProperty;
7
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
- var __getOwnPropNames = Object.getOwnPropertyNames;
9
- var __getProtoOf = Object.getPrototypeOf;
10
- var __hasOwnProp = Object.prototype.hasOwnProperty;
11
- var __esmMin = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
12
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
13
- var __exportAll = (all, no_symbols) => {
14
- let target = {};
15
- for (var name in all) __defProp(target, name, {
16
- get: all[name],
17
- enumerable: true
18
- });
19
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
20
- return target;
21
- };
22
- var __copyProps = (to, from, except, desc) => {
23
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
24
- key = keys[i];
25
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
26
- get: ((k) => from[k]).bind(null, key),
27
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
28
- });
29
- }
30
- return to;
31
- };
32
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
33
- value: mod,
34
- enumerable: true
35
- }) : target, mod));
36
- var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) {
38
- if (typeof require !== "undefined") return require.apply(this, arguments);
39
- throw Error("Calling `require` for \"" + x + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.");
40
- });
41
- //#endregion
42
- export { __toCommonJS as a, __require as i, __esmMin as n, __toESM as o, __exportAll as r, __commonJSMin as t };
@@ -1,13 +0,0 @@
1
- import { CollectionRegistry } from "@rebasepro/common";
2
- import { CollectionRegistryInterface } from "../db/interfaces";
3
- /**
4
- * Backend-agnostic collection registry.
5
- * Satisfies CollectionRegistryInterface through inheritance from CollectionRegistry.
6
- */
7
- export declare class BackendCollectionRegistry extends CollectionRegistry implements CollectionRegistryInterface {
8
- /**
9
- * Get the available relation keys for a given collection path.
10
- * Maps from the collection's relation property names to the relation names.
11
- */
12
- getRelationKeysForCollection(collectionPath: string): string[];
13
- }
@@ -1,5 +0,0 @@
1
- import { EntityCollection } from "@rebasepro/types";
2
- /**
3
- * Asynchronously load collection files from a directory for backend initialization
4
- */
5
- export declare function loadCollectionsFromDirectory(directory: string): Promise<EntityCollection[]>;
@@ -1,17 +0,0 @@
1
- import type { CronJobDefinition } from "@rebasepro/types";
2
- export interface LoadedCronJob {
3
- /** Job ID derived from filename (e.g. "cleanup-sessions"). */
4
- id: string;
5
- /** The full definition. */
6
- definition: CronJobDefinition;
7
- }
8
- /**
9
- * Auto-discover cron job files from a directory.
10
- *
11
- * Each file should default-export a `CronJobDefinition`.
12
- * The filename (without extension) becomes the job ID:
13
- * `crons/cleanup-sessions.ts` → id = "cleanup-sessions"
14
- *
15
- * Follows the same discovery pattern as `loadFunctionsFromDirectory`.
16
- */
17
- export declare function loadCronJobsFromDirectory(directory: string): Promise<LoadedCronJob[]>;
@@ -1,14 +0,0 @@
1
- import { Hono } from "hono";
2
- import type { HonoEnv } from "../api/types";
3
- import type { CronScheduler } from "./cron-scheduler";
4
- /**
5
- * Create admin REST routes for managing cron jobs.
6
- *
7
- * Routes:
8
- * GET / → list all cron jobs
9
- * GET /:id → get a single job's status
10
- * POST /:id/trigger → manually trigger a job
11
- * GET /:id/logs → get execution logs for a job
12
- * PUT /:id → update job (enable/disable)
13
- */
14
- export declare function createCronRoutes(scheduler: CronScheduler): Hono<HonoEnv>;
@@ -1,106 +0,0 @@
1
- import type { CronJobStatus, CronJobLogEntry } from "@rebasepro/types";
2
- import type { RebaseClient } from "@rebasepro/types";
3
- import type { LoadedCronJob } from "./cron-loader";
4
- import type { CronStore } from "./cron-store";
5
- /**
6
- * Validates a standard 5-field cron expression structurally and semantically.
7
- * Returns `{ valid: true }` or `{ valid: false, reason: string }`.
8
- */
9
- export declare function validateCronExpression(schedule: string): {
10
- valid: true;
11
- } | {
12
- valid: false;
13
- reason: string;
14
- };
15
- export declare class CronScheduler {
16
- private jobs;
17
- private started;
18
- private store?;
19
- private client?;
20
- /**
21
- * Set the RebaseClient instance to make it available to cron job handlers.
22
- */
23
- setClient(client: RebaseClient): void;
24
- /**
25
- * Attach a persistence store for cron logs.
26
- * When set, execution logs are written to the database after each run,
27
- * and counters are seeded from the database on start.
28
- */
29
- setStore(store: CronStore): void;
30
- /**
31
- * Register a batch of loaded cron jobs.
32
- *
33
- * If the scheduler is already started, newly registered jobs are
34
- * automatically scheduled (so late-registered jobs don't sit idle).
35
- *
36
- * Validates the cron schedule on registration — invalid schedules
37
- * are rejected with a warning and the job is NOT registered.
38
- */
39
- registerJobs(loadedJobs: LoadedCronJob[]): void;
40
- /**
41
- * Start the scheduler — begins ticking all enabled jobs.
42
- */
43
- start(): void;
44
- /**
45
- * Stop the scheduler and clear all timers.
46
- *
47
- * Currently-executing handlers run to completion (they are async),
48
- * but no further scheduling occurs after stop.
49
- */
50
- stop(): void;
51
- /**
52
- * List all registered jobs with their current status.
53
- */
54
- listJobs(): CronJobStatus[];
55
- /**
56
- * Get a single job status by ID.
57
- */
58
- getJob(id: string): CronJobStatus | undefined;
59
- /**
60
- * Get log entries for a job.
61
- */
62
- getJobLogs(id: string, limit?: number): CronJobLogEntry[];
63
- /**
64
- * Get log entries for a job from the database (if store is available).
65
- * Falls back to in-memory logs if no store is configured.
66
- */
67
- getJobLogsFromDb(id: string, limit?: number): Promise<CronJobLogEntry[]>;
68
- /**
69
- * Enable or disable a job at runtime.
70
- */
71
- setJobEnabled(id: string, enabled: boolean): CronJobStatus | undefined;
72
- /**
73
- * Manually trigger a job execution immediately.
74
- *
75
- * Returns `undefined` if the job doesn't exist.
76
- * If the job is currently executing, returns the log entry with
77
- * a `skipped: true` result rather than running concurrently.
78
- */
79
- triggerJob(id: string): Promise<CronJobLogEntry | undefined>;
80
- /**
81
- * Schedule the next execution for a job.
82
- *
83
- * Safety guarantees:
84
- * 1. Clears any existing timer first (prevents leaked/duplicate timers)
85
- * 2. Enforces a minimum delay to prevent tight loops from jitter
86
- * 3. Unref's the timer so it doesn't prevent process exit
87
- * 4. Re-checks enabled & started state before executing
88
- * 5. Concurrency guard prevents overlapping handler executions
89
- */
90
- private scheduleNext;
91
- /**
92
- * Stop a single job's timer and clear its next run state.
93
- */
94
- private stopJob;
95
- /**
96
- * Execute a job's handler with full isolation and safety.
97
- *
98
- * - Sets a concurrency flag to prevent overlapping runs
99
- * - Wraps handler in a timeout race
100
- * - Captures all logs, errors, and results
101
- * - Persists to store (non-blocking) if available
102
- * - Always restores state even on catastrophic errors
103
- */
104
- private executeJob;
105
- private toStatus;
106
- }
@@ -1,32 +0,0 @@
1
- import type { CronJobLogEntry } from "@rebasepro/types";
2
- import type { DataDriver } from "@rebasepro/types";
3
- /**
4
- * Persistence layer for cron job execution logs.
5
- *
6
- * Uses the DataDriver's `admin.executeSql` capability to store logs in a
7
- * `rebase.cron_logs` table. Falls back gracefully if the driver doesn't
8
- * support SQL (e.g. MongoDB) — in that case, no persistence occurs.
9
- */
10
- export interface CronStore {
11
- /** Ensure the backing table exists. Called once on startup. */
12
- ensureTable(): Promise<void>;
13
- /** Persist a single log entry after execution. */
14
- insertLog(entry: CronJobLogEntry): Promise<void>;
15
- /**
16
- * Fetch the most recent logs for a job.
17
- * @param jobId The job identifier
18
- * @param limit Max entries to return (default 50)
19
- * @returns Logs sorted newest-first
20
- */
21
- fetchLogs(jobId: string, limit?: number): Promise<CronJobLogEntry[]>;
22
- /**
23
- * Fetch aggregate stats for all jobs (totalRuns, totalFailures, lastRunAt).
24
- * Used to seed in-memory counters on startup.
25
- */
26
- fetchJobStats(): Promise<Map<string, {
27
- totalRuns: number;
28
- totalFailures: number;
29
- lastRunAt?: string;
30
- }>>;
31
- }
32
- export declare function createCronStore(driver: DataDriver): CronStore | undefined;
@@ -1,6 +0,0 @@
1
- export { loadCronJobsFromDirectory } from "./cron-loader";
2
- export type { LoadedCronJob } from "./cron-loader";
3
- export { CronScheduler, validateCronExpression } from "./cron-scheduler";
4
- export { createCronRoutes } from "./cron-routes";
5
- export { createCronStore } from "./cron-store";
6
- export type { CronStore } from "./cron-store";
@@ -1,18 +0,0 @@
1
- /**
2
- * Database Abstraction Interfaces
3
- *
4
- * These interfaces define the contracts that any database backend must implement
5
- * to be used with Rebase. This allows for pluggable database backends like
6
- * PostgreSQL, MongoDB, MySQL, etc.
7
- */
8
- import { DatabaseConnection, QueryFilter, FetchCollectionOptions, SearchOptions, CountOptions, ConditionBuilder, ConditionBuilderStatic, EntityRepository, CollectionSubscriptionConfig, EntitySubscriptionConfig, RealtimeProvider, CollectionRegistryInterface, DataTransformer, BackendConfig, BackendInstance, BackendFactory } from "@rebasepro/types";
9
- import { NodePgDatabase } from "drizzle-orm/node-postgres";
10
- import { PgTransaction } from "drizzle-orm/pg-core";
11
- /**
12
- * Type representing either a direct database connection or a transaction.
13
- * Used to allow services to operate within a transaction context.
14
- * Note: `any` is intentional here — it represents a Drizzle client with
15
- * a dynamic schema, enabling `db.query[tableName]` access without casts.
16
- */
17
- export type DrizzleClient = NodePgDatabase<Record<string, unknown>> | PgTransaction<any, any, any>;
18
- export type { DatabaseConnection, QueryFilter, FetchCollectionOptions, SearchOptions, CountOptions, ConditionBuilder, ConditionBuilderStatic, EntityRepository, CollectionSubscriptionConfig, EntitySubscriptionConfig, RealtimeProvider, CollectionRegistryInterface, DataTransformer, BackendConfig, BackendInstance, BackendFactory };