@rebasepro/server-core 0.7.0 → 0.9.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 (300) hide show
  1. package/README.md +2 -2
  2. package/dist/api/ast-schema-editor.d.ts +21 -0
  3. package/dist/api/collections_for_test/callbacks_test_collection.d.ts +2 -0
  4. package/dist/api/errors.d.ts +53 -0
  5. package/dist/api/index.d.ts +7 -0
  6. package/dist/api/logs-routes.d.ts +37 -0
  7. package/dist/api/openapi-generator.d.ts +16 -0
  8. package/dist/api/rest/api-generator.d.ts +68 -0
  9. package/{src/api/rest/index.ts → dist/api/rest/index.d.ts} +0 -1
  10. package/dist/api/rest/query-parser.d.ts +6 -0
  11. package/dist/api/schema-editor-routes.d.ts +3 -0
  12. package/dist/api/types.d.ts +56 -0
  13. package/dist/auth/adapter-middleware.d.ts +43 -0
  14. package/dist/auth/admin-roles-route.d.ts +18 -0
  15. package/dist/auth/admin-user-ops.d.ts +79 -0
  16. package/dist/auth/admin-users-route.d.ts +28 -0
  17. package/dist/auth/api-keys/api-key-middleware.d.ts +39 -0
  18. package/{src/auth/api-keys/api-key-permission-guard.ts → dist/auth/api-keys/api-key-permission-guard.d.ts} +2 -34
  19. package/dist/auth/api-keys/api-key-routes.d.ts +20 -0
  20. package/dist/auth/api-keys/api-key-store.d.ts +35 -0
  21. package/{src/auth/api-keys/api-key-types.ts → dist/auth/api-keys/api-key-types.d.ts} +0 -6
  22. package/{src/auth/api-keys/index.ts → dist/auth/api-keys/index.d.ts} +2 -22
  23. package/dist/auth/apple-oauth.d.ts +30 -0
  24. package/{src/auth/auth-hooks.ts → dist/auth/auth-hooks.d.ts} +15 -73
  25. package/dist/auth/bitbucket-oauth.d.ts +11 -0
  26. package/dist/auth/builtin-auth-adapter.d.ts +55 -0
  27. package/dist/auth/cookie-utils.d.ts +32 -0
  28. package/{src/auth/crypto-utils.ts → dist/auth/crypto-utils.d.ts} +1 -16
  29. package/dist/auth/custom-auth-adapter.d.ts +39 -0
  30. package/dist/auth/discord-oauth.d.ts +14 -0
  31. package/dist/auth/facebook-oauth.d.ts +14 -0
  32. package/dist/auth/github-oauth.d.ts +15 -0
  33. package/dist/auth/gitlab-oauth.d.ts +13 -0
  34. package/dist/auth/google-oauth.d.ts +47 -0
  35. package/{src/auth/index.ts → dist/auth/index.d.ts} +4 -22
  36. package/{src/auth/interfaces.ts → dist/auth/interfaces.d.ts} +20 -89
  37. package/dist/auth/jwt.d.ts +67 -0
  38. package/dist/auth/linkedin-oauth.d.ts +18 -0
  39. package/dist/auth/magic-link-routes.d.ts +32 -0
  40. package/dist/auth/mfa-crypto.d.ts +23 -0
  41. package/dist/auth/mfa-routes.d.ts +7 -0
  42. package/dist/auth/mfa.d.ts +49 -0
  43. package/dist/auth/microsoft-oauth.d.ts +16 -0
  44. package/dist/auth/middleware.d.ts +158 -0
  45. package/dist/auth/password.d.ts +22 -0
  46. package/dist/auth/rate-limiter.d.ts +50 -0
  47. package/dist/auth/reset-password-admin.d.ts +29 -0
  48. package/dist/auth/rls-scope.d.ts +31 -0
  49. package/dist/auth/routes.d.ts +66 -0
  50. package/dist/auth/session-routes.d.ts +29 -0
  51. package/dist/auth/slack-oauth.d.ts +12 -0
  52. package/dist/auth/spotify-oauth.d.ts +12 -0
  53. package/dist/auth/twitter-oauth.d.ts +18 -0
  54. package/dist/collections/BackendCollectionRegistry.d.ts +13 -0
  55. package/dist/collections/loader.d.ts +5 -0
  56. package/dist/cron/cron-loader.d.ts +18 -0
  57. package/dist/cron/cron-routes.d.ts +14 -0
  58. package/dist/cron/cron-scheduler.d.ts +106 -0
  59. package/dist/cron/cron-store.d.ts +32 -0
  60. package/dist/cron/define-cron.d.ts +28 -0
  61. package/{src/cron/index.ts → dist/cron/index.d.ts} +1 -0
  62. package/dist/db/interfaces.d.ts +18 -0
  63. package/dist/dynamic-import-Dvh-K5fl.js +22 -0
  64. package/dist/dynamic-import-Dvh-K5fl.js.map +1 -0
  65. package/dist/email/index.d.ts +6 -0
  66. package/dist/email/smtp-email-service.d.ts +30 -0
  67. package/dist/email/templates.d.ts +50 -0
  68. package/{src/email/types.ts → dist/email/types.d.ts} +40 -36
  69. package/dist/env.d.ts +102 -0
  70. package/dist/functions/define-function.d.ts +55 -0
  71. package/dist/functions/function-loader.d.ts +18 -0
  72. package/dist/functions/function-routes.d.ts +10 -0
  73. package/{src/functions/index.ts → dist/functions/index.d.ts} +2 -0
  74. package/dist/history/history-routes.d.ts +23 -0
  75. package/{src/history/index.ts → dist/history/index.d.ts} +0 -1
  76. package/dist/index.d.ts +35 -0
  77. package/dist/index.es.js +18184 -0
  78. package/dist/index.es.js.map +1 -0
  79. package/dist/index.umd.js +48629 -0
  80. package/dist/index.umd.js.map +1 -0
  81. package/dist/init/docs.d.ts +4 -0
  82. package/dist/init/health.d.ts +2 -0
  83. package/dist/init/middlewares.d.ts +10 -0
  84. package/dist/init/shutdown.d.ts +65 -0
  85. package/dist/init/storage.d.ts +5 -0
  86. package/dist/init.d.ts +344 -0
  87. package/dist/jwt-BwIn8xmk.js +4200 -0
  88. package/dist/jwt-BwIn8xmk.js.map +1 -0
  89. package/dist/logger-BYU66ENZ.js +94 -0
  90. package/dist/logger-BYU66ENZ.js.map +1 -0
  91. package/dist/ms-DnYXB-Wd.js +162 -0
  92. package/dist/ms-DnYXB-Wd.js.map +1 -0
  93. package/dist/openapi-generator-Z9oYWLf_.js +586 -0
  94. package/dist/openapi-generator-Z9oYWLf_.js.map +1 -0
  95. package/dist/schema-editor-routes-D3ef8zu1.js +219 -0
  96. package/dist/schema-editor-routes-D3ef8zu1.js.map +1 -0
  97. package/dist/serve-spa.d.ts +36 -0
  98. package/dist/services/driver-registry.d.ts +78 -0
  99. package/dist/services/routed-realtime-service.d.ts +43 -0
  100. package/dist/services/webhook-service.d.ts +29 -0
  101. package/dist/singleton.d.ts +51 -0
  102. package/dist/src-B4OLmNVa.js +437 -0
  103. package/dist/src-B4OLmNVa.js.map +1 -0
  104. package/dist/src-B5WkP1Rv.js +24778 -0
  105. package/dist/src-B5WkP1Rv.js.map +1 -0
  106. package/dist/storage/GCSStorageController.d.ts +43 -0
  107. package/dist/storage/LocalStorageController.d.ts +46 -0
  108. package/dist/storage/S3StorageController.d.ts +40 -0
  109. package/dist/storage/image-transform.d.ts +50 -0
  110. package/{src/storage/index.ts → dist/storage/index.d.ts} +6 -21
  111. package/dist/storage/routes.d.ts +70 -0
  112. package/dist/storage/storage-registry.d.ts +78 -0
  113. package/dist/storage/tus-handler.d.ts +53 -0
  114. package/{src/storage/types.ts → dist/storage/types.d.ts} +32 -38
  115. package/dist/types/index.d.ts +11 -0
  116. package/dist/utils/dev-port.d.ts +45 -0
  117. package/dist/utils/dynamic-import.d.ts +25 -0
  118. package/dist/utils/logger.d.ts +31 -0
  119. package/dist/utils/logging.d.ts +9 -0
  120. package/dist/utils/request-id.d.ts +4 -0
  121. package/dist/utils/request-logger.d.ts +19 -0
  122. package/{src/utils/sql.ts → dist/utils/sql.d.ts} +5 -16
  123. package/package.json +49 -22
  124. package/coverage/clover.xml +0 -3739
  125. package/coverage/coverage-final.json +0 -31
  126. package/coverage/lcov-report/base.css +0 -224
  127. package/coverage/lcov-report/block-navigation.js +0 -87
  128. package/coverage/lcov-report/favicon.png +0 -0
  129. package/coverage/lcov-report/index.html +0 -266
  130. package/coverage/lcov-report/prettify.css +0 -1
  131. package/coverage/lcov-report/prettify.js +0 -2
  132. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  133. package/coverage/lcov-report/sorter.js +0 -210
  134. package/coverage/lcov-report/src/api/ast-schema-editor.ts.html +0 -952
  135. package/coverage/lcov-report/src/api/errors.ts.html +0 -472
  136. package/coverage/lcov-report/src/api/graphql/graphql-schema-generator.ts.html +0 -1069
  137. package/coverage/lcov-report/src/api/graphql/index.html +0 -116
  138. package/coverage/lcov-report/src/api/index.html +0 -176
  139. package/coverage/lcov-report/src/api/openapi-generator.ts.html +0 -565
  140. package/coverage/lcov-report/src/api/rest/api-generator.ts.html +0 -994
  141. package/coverage/lcov-report/src/api/rest/index.html +0 -131
  142. package/coverage/lcov-report/src/api/rest/query-parser.ts.html +0 -550
  143. package/coverage/lcov-report/src/api/schema-editor-routes.ts.html +0 -202
  144. package/coverage/lcov-report/src/api/server.ts.html +0 -823
  145. package/coverage/lcov-report/src/auth/admin-routes.ts.html +0 -973
  146. package/coverage/lcov-report/src/auth/index.html +0 -176
  147. package/coverage/lcov-report/src/auth/jwt.ts.html +0 -574
  148. package/coverage/lcov-report/src/auth/middleware.ts.html +0 -745
  149. package/coverage/lcov-report/src/auth/password.ts.html +0 -310
  150. package/coverage/lcov-report/src/auth/services.ts.html +0 -2074
  151. package/coverage/lcov-report/src/collections/index.html +0 -116
  152. package/coverage/lcov-report/src/collections/loader.ts.html +0 -232
  153. package/coverage/lcov-report/src/db/auth-schema.ts.html +0 -523
  154. package/coverage/lcov-report/src/db/data-transformer.ts.html +0 -1753
  155. package/coverage/lcov-report/src/db/entityService.ts.html +0 -700
  156. package/coverage/lcov-report/src/db/index.html +0 -146
  157. package/coverage/lcov-report/src/db/services/EntityFetchService.ts.html +0 -4048
  158. package/coverage/lcov-report/src/db/services/EntityPersistService.ts.html +0 -883
  159. package/coverage/lcov-report/src/db/services/RelationService.ts.html +0 -3121
  160. package/coverage/lcov-report/src/db/services/entity-helpers.ts.html +0 -442
  161. package/coverage/lcov-report/src/db/services/index.html +0 -176
  162. package/coverage/lcov-report/src/db/services/index.ts.html +0 -124
  163. package/coverage/lcov-report/src/generate-drizzle-schema-logic.ts.html +0 -1960
  164. package/coverage/lcov-report/src/index.html +0 -116
  165. package/coverage/lcov-report/src/services/driver-registry.ts.html +0 -631
  166. package/coverage/lcov-report/src/services/index.html +0 -131
  167. package/coverage/lcov-report/src/services/postgresDataDriver.ts.html +0 -3025
  168. package/coverage/lcov-report/src/storage/LocalStorageController.ts.html +0 -1189
  169. package/coverage/lcov-report/src/storage/S3StorageController.ts.html +0 -970
  170. package/coverage/lcov-report/src/storage/index.html +0 -161
  171. package/coverage/lcov-report/src/storage/storage-registry.ts.html +0 -646
  172. package/coverage/lcov-report/src/storage/types.ts.html +0 -451
  173. package/coverage/lcov-report/src/utils/drizzle-conditions.ts.html +0 -3082
  174. package/coverage/lcov-report/src/utils/index.html +0 -116
  175. package/coverage/lcov.info +0 -7179
  176. package/jest.config.cjs +0 -19
  177. package/src/api/ast-schema-editor.ts +0 -289
  178. package/src/api/collections_for_test/callbacks_test_collection.ts +0 -61
  179. package/src/api/errors.ts +0 -278
  180. package/src/api/graphql/graphql-schema-generator.ts +0 -383
  181. package/src/api/graphql/index.ts +0 -2
  182. package/src/api/index.ts +0 -11
  183. package/src/api/logs-routes.ts +0 -132
  184. package/src/api/openapi-generator.ts +0 -727
  185. package/src/api/rest/api-generator-count.test.ts +0 -126
  186. package/src/api/rest/api-generator.ts +0 -747
  187. package/src/api/rest/query-parser.ts +0 -300
  188. package/src/api/schema-editor-routes.ts +0 -41
  189. package/src/api/server.ts +0 -271
  190. package/src/api/types.ts +0 -104
  191. package/src/auth/adapter-middleware.ts +0 -114
  192. package/src/auth/admin-roles-route.ts +0 -36
  193. package/src/auth/admin-user-ops.ts +0 -236
  194. package/src/auth/admin-users-route.ts +0 -302
  195. package/src/auth/api-keys/api-key-middleware.ts +0 -133
  196. package/src/auth/api-keys/api-key-routes.ts +0 -193
  197. package/src/auth/api-keys/api-key-store.ts +0 -340
  198. package/src/auth/apple-oauth.ts +0 -122
  199. package/src/auth/bitbucket-oauth.ts +0 -84
  200. package/src/auth/builtin-auth-adapter.ts +0 -380
  201. package/src/auth/custom-auth-adapter.ts +0 -86
  202. package/src/auth/discord-oauth.ts +0 -85
  203. package/src/auth/facebook-oauth.ts +0 -74
  204. package/src/auth/github-oauth.ts +0 -112
  205. package/src/auth/gitlab-oauth.ts +0 -72
  206. package/src/auth/google-oauth.ts +0 -223
  207. package/src/auth/jwt.ts +0 -208
  208. package/src/auth/linkedin-oauth.ts +0 -83
  209. package/src/auth/magic-link-routes.ts +0 -167
  210. package/src/auth/mfa-crypto.ts +0 -91
  211. package/src/auth/mfa-routes.ts +0 -323
  212. package/src/auth/mfa.ts +0 -161
  213. package/src/auth/microsoft-oauth.ts +0 -90
  214. package/src/auth/middleware.ts +0 -369
  215. package/src/auth/password.ts +0 -77
  216. package/src/auth/rate-limiter.ts +0 -225
  217. package/src/auth/reset-password-admin.ts +0 -160
  218. package/src/auth/rls-scope.ts +0 -58
  219. package/src/auth/routes.ts +0 -802
  220. package/src/auth/session-routes.ts +0 -353
  221. package/src/auth/slack-oauth.ts +0 -73
  222. package/src/auth/spotify-oauth.ts +0 -69
  223. package/src/auth/twitter-oauth.ts +0 -128
  224. package/src/collections/BackendCollectionRegistry.ts +0 -20
  225. package/src/collections/loader.ts +0 -50
  226. package/src/cron/cron-loader.ts +0 -84
  227. package/src/cron/cron-routes.test.ts +0 -265
  228. package/src/cron/cron-routes.ts +0 -85
  229. package/src/cron/cron-scheduler.test.ts +0 -559
  230. package/src/cron/cron-scheduler.ts +0 -581
  231. package/src/cron/cron-store.ts +0 -166
  232. package/src/db/interfaces.ts +0 -60
  233. package/src/email/index.ts +0 -19
  234. package/src/email/smtp-email-service.ts +0 -123
  235. package/src/email/templates.ts +0 -470
  236. package/src/env.ts +0 -227
  237. package/src/functions/function-loader.ts +0 -116
  238. package/src/functions/function-routes.ts +0 -31
  239. package/src/history/history-routes.ts +0 -129
  240. package/src/index.ts +0 -70
  241. package/src/init/docs.ts +0 -47
  242. package/src/init/health.ts +0 -37
  243. package/src/init/middlewares.ts +0 -61
  244. package/src/init/shutdown.ts +0 -56
  245. package/src/init/storage.ts +0 -57
  246. package/src/init.ts +0 -1041
  247. package/src/serve-spa.ts +0 -89
  248. package/src/services/driver-registry.ts +0 -183
  249. package/src/services/routed-realtime-service.ts +0 -113
  250. package/src/services/webhook-service.ts +0 -155
  251. package/src/singleton.ts +0 -70
  252. package/src/storage/LocalStorageController.ts +0 -389
  253. package/src/storage/S3StorageController.ts +0 -300
  254. package/src/storage/image-transform.ts +0 -218
  255. package/src/storage/routes.ts +0 -368
  256. package/src/storage/storage-registry.ts +0 -188
  257. package/src/storage/tus-handler.ts +0 -315
  258. package/src/types/index.ts +0 -27
  259. package/src/utils/dev-port.ts +0 -196
  260. package/src/utils/logger.ts +0 -143
  261. package/src/utils/logging.ts +0 -40
  262. package/src/utils/request-id.ts +0 -40
  263. package/src/utils/request-logger.ts +0 -72
  264. package/test/api-generator.test.ts +0 -588
  265. package/test/api-key-permission-guard.test.ts +0 -144
  266. package/test/ast-schema-editor.test.ts +0 -89
  267. package/test/auth-middleware-hono.test.ts +0 -556
  268. package/test/auth-routes.test.ts +0 -1098
  269. package/test/backend-hooks-data.test.ts +0 -477
  270. package/test/custom-auth-adapter.test.ts +0 -189
  271. package/test/driver-registry.test.ts +0 -282
  272. package/test/email-templates.test.ts +0 -174
  273. package/test/env.test.ts +0 -128
  274. package/test/error-propagation.test.ts +0 -226
  275. package/test/errors-hono.test.ts +0 -133
  276. package/test/errors.test.ts +0 -155
  277. package/test/function-loader.test.ts +0 -127
  278. package/test/graphql-schema-generator.test.ts +0 -554
  279. package/test/jwt-security.test.ts +0 -182
  280. package/test/jwt.test.ts +0 -326
  281. package/test/mfa.test.ts +0 -197
  282. package/test/middleware.test.ts +0 -305
  283. package/test/multi-datasource-routing.test.ts +0 -113
  284. package/test/password.test.ts +0 -165
  285. package/test/query-parser.test.ts +0 -233
  286. package/test/rate-limiter.test.ts +0 -102
  287. package/test/reset-password-admin.test.ts +0 -113
  288. package/test/routed-realtime-service.test.ts +0 -86
  289. package/test/safe-compare.test.ts +0 -66
  290. package/test/singleton.test.ts +0 -59
  291. package/test/smtp-email-service.test.ts +0 -169
  292. package/test/storage-local.test.ts +0 -271
  293. package/test/storage-registry.test.ts +0 -282
  294. package/test/storage-routes.test.ts +0 -222
  295. package/test/storage-s3.test.ts +0 -304
  296. package/test/transform-auth-response.test.ts +0 -305
  297. package/test/webhook-service.test.ts +0 -260
  298. package/tsconfig.json +0 -54
  299. package/tsconfig.prod.json +0 -23
  300. package/vite.config.ts +0 -86
package/jest.config.cjs DELETED
@@ -1,19 +0,0 @@
1
- /** @type {import("ts-jest").JestConfigWithTsJest} */
2
- module.exports = {
3
- preset: "ts-jest",
4
- testEnvironment: "node",
5
- // This pattern tells Jest to look for .test.ts files
6
- testMatch: [
7
- "**/__tests__/**/*.test.ts",
8
- "**/src/**/*.test.ts",
9
- "**/test/**/*.test.ts"
10
- ],
11
- // This helps Jest resolve monorepo packages
12
- moduleNameMapper: {
13
- "^@rebasepro/client$": "<rootDir>/../client/src/index.ts",
14
- "^@rebasepro/common$": "<rootDir>/../common/src/index.ts",
15
- "^@rebasepro/types$": "<rootDir>/../types/src/index.ts",
16
- "^@rebasepro/utils$": "<rootDir>/../utils/src/index.ts",
17
- "^(\\.{1,2}/.*)\\.js$": "$1"
18
- }
19
- };
@@ -1,289 +0,0 @@
1
- import { Project, SyntaxKind, ObjectLiteralExpression, ObjectLiteralElementLike, PropertyAssignment, VariableDeclaration, IndentationText } from "ts-morph";
2
- import * as path from "path";
3
- import * as fs from "fs";
4
-
5
- export class AstSchemaEditor {
6
- private project: Project;
7
- private collectionsDir: string;
8
-
9
- constructor(collectionsDir: string) {
10
- this.project = new Project({
11
- manipulationSettings: {
12
- indentationText: IndentationText.FourSpaces
13
- }
14
- });
15
- if (fs.existsSync(collectionsDir)) {
16
- this.project.addSourceFilesAtPaths(`${collectionsDir}/**/*.ts`);
17
- }
18
- this.collectionsDir = path.resolve(collectionsDir);
19
- }
20
-
21
- /**
22
- * Sanitize collectionId to prevent path traversal attacks.
23
- * Only allows alphanumeric characters, underscores, and hyphens.
24
- */
25
- private sanitizeCollectionId(collectionId: string): string {
26
- const sanitized = collectionId.replace(/[^a-zA-Z0-9_-]/g, "");
27
- if (!sanitized || sanitized !== collectionId) {
28
- throw new Error(`Invalid collection ID: "${collectionId}". Only alphanumeric characters, underscores, and hyphens are allowed.`);
29
- }
30
- return sanitized;
31
- }
32
-
33
- /**
34
- * Resolve a file path and ensure it falls within the collectionsDir.
35
- */
36
- private safePath(filename: string): string {
37
- const resolved = path.resolve(this.collectionsDir, filename);
38
- if (!resolved.startsWith(this.collectionsDir + path.sep) && resolved !== this.collectionsDir) {
39
- throw new Error("Path traversal detected: resolved path is outside the collections directory.");
40
- }
41
- return resolved;
42
- }
43
-
44
- private getCollectionFile(collectionId: string) {
45
- const safeId = this.sanitizeCollectionId(collectionId);
46
- const filePath = this.safePath(`${safeId}.ts`);
47
- let file = this.project.getSourceFile(filePath);
48
- if (!file && fs.existsSync(filePath)) {
49
- this.project.addSourceFilesAtPaths(`${this.collectionsDir}/**/*.ts`);
50
- file = this.project.getSourceFile(filePath);
51
- }
52
- return file;
53
- }
54
-
55
- private getCollectionObject(collectionId: string): ObjectLiteralExpression | null {
56
- const file = this.getCollectionFile(collectionId);
57
- if (!file) return null;
58
-
59
- const defaultExport = file.getDefaultExportSymbol();
60
- if (defaultExport) {
61
- const declaration = defaultExport.getDeclarations()[0];
62
- if (declaration && declaration.getKind() === SyntaxKind.ExportAssignment) {
63
- const expr = declaration.asKind(SyntaxKind.ExportAssignment)?.getExpression();
64
- if (expr && expr.getKind() === SyntaxKind.Identifier) {
65
- const varName = expr.getText();
66
- const varDecl = file.getVariableDeclaration(varName);
67
- return varDecl?.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression) || null;
68
- }
69
- }
70
- }
71
- // Fallback: Just get the first exported VariableDeclaration with an ObjectLiteral
72
- const varDecls = file.getVariableDeclarations();
73
- for (const varDecl of varDecls) {
74
- const init = varDecl.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
75
- if (init) return init;
76
- }
77
- return null;
78
- }
79
-
80
- private convertJsonToAstString(obj: unknown, indentLevel = 0, oldAstNode?: ObjectLiteralExpression): string {
81
- // Base TS-morph parses arrays as 2 levels deep from the property key:
82
- // PropertiesObject = level 1, PropertyConfig = level 2.
83
- // We calibrate the spacing multiples to keep the items flush with standard TS format.
84
- const indentStr = " ";
85
- const indent = indentStr.repeat(indentLevel);
86
- const innerIndent = indentStr.repeat(indentLevel + 1);
87
-
88
- if (obj === null || obj === undefined) {
89
- return "undefined";
90
- }
91
- if (typeof obj === "string") {
92
- return JSON.stringify(obj);
93
- }
94
- if (typeof obj === "number" || typeof obj === "boolean") {
95
- return String(obj);
96
- }
97
- if (Array.isArray(obj)) {
98
- if (obj.length === 0) return "[]";
99
- const items = obj.map(item => this.convertJsonToAstString(item, indentLevel + 1));
100
- return `[\n${innerIndent}${items.join(`,\n${innerIndent}`)}\n${indent}]`;
101
- }
102
- if (typeof obj === "object") {
103
- const record = obj as Record<string, unknown>;
104
- const keys = Object.keys(record);
105
-
106
- // Collect preserved AST properties
107
- const preservedProps: string[] = [];
108
- if (oldAstNode) {
109
- const oldProps = oldAstNode.getProperties();
110
- for (const oldProp of oldProps) {
111
- if (oldProp.isKind(SyntaxKind.PropertyAssignment)) {
112
- const nameNode = oldProp.getNameNode();
113
- let name = nameNode.getText();
114
- if (name.startsWith('"') && name.endsWith('"')) name = name.slice(1, -1);
115
- if (name.startsWith("'") && name.endsWith("'")) name = name.slice(1, -1);
116
-
117
- // If the JSON object doesn't have this key, check if we should preserve it
118
- if (!(name in record)) {
119
- const init = oldProp.getInitializer();
120
- if (init) {
121
- const kind = init.getKind();
122
- const isCode = kind === SyntaxKind.ArrowFunction ||
123
- kind === SyntaxKind.FunctionExpression ||
124
- kind === SyntaxKind.Identifier ||
125
- kind === SyntaxKind.CallExpression ||
126
- kind === SyntaxKind.JsxElement;
127
-
128
- if (isCode || name === "target" || name === "callbacks" || name === "permissions" || name === "securityRules") {
129
- // Preserve this property exactly as it was
130
- const keyStr = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
131
- preservedProps.push(`${keyStr}: ${init.getText()}`);
132
- }
133
- }
134
- }
135
- }
136
- }
137
- }
138
-
139
- if (keys.length === 0 && preservedProps.length === 0) return "{}";
140
-
141
- const props = keys.map(key => {
142
- const keyStr = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
143
-
144
- // If the value is an object, pass the old AST node to recurse
145
- let childAstNode: ObjectLiteralExpression | undefined;
146
- if (oldAstNode && typeof record[key] === "object" && record[key] !== null && !Array.isArray(record[key])) {
147
- const oldProp = oldAstNode.getProperty(
148
- (p: ObjectLiteralElementLike) => "getName" in p && typeof (p as PropertyAssignment).getName === "function" && ((p as PropertyAssignment).getName() === key || (p as PropertyAssignment).getName() === `"${key}"` || (p as PropertyAssignment).getName() === `'${key}'`)
149
- );
150
- if (oldProp && oldProp.isKind(SyntaxKind.PropertyAssignment)) {
151
- childAstNode = oldProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
152
- }
153
- }
154
-
155
- return `${keyStr}: ${this.convertJsonToAstString(record[key], indentLevel + 1, childAstNode)}`;
156
- });
157
-
158
- const allProps = [...props, ...preservedProps];
159
- return `{\n${innerIndent}${allProps.join(`,\n${innerIndent}`)}\n${indent}}`;
160
- }
161
- return "undefined";
162
- }
163
-
164
- public async saveProperty(collectionId: string, propertyKey: string, propertyConfig: Record<string, unknown>) {
165
- const collectionObj = this.getCollectionObject(collectionId);
166
- if (!collectionObj) throw new Error(`Collection ${collectionId} not found in ATS workspace.`);
167
-
168
- let propertiesProp = collectionObj.getProperty("properties") as PropertyAssignment;
169
- if (!propertiesProp) {
170
- propertiesProp = collectionObj.addPropertyAssignment({
171
- name: "properties",
172
- initializer: "{}"
173
- });
174
- }
175
-
176
- const propsObj = propertiesProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
177
- if (propsObj) {
178
- const existingProp = propsObj.getProperty(
179
- (p: ObjectLiteralElementLike) => "getName" in p && typeof (p as PropertyAssignment).getName === "function" && ((p as PropertyAssignment).getName() === propertyKey || (p as PropertyAssignment).getName() === `"${propertyKey}"`)
180
- );
181
-
182
- let oldPropAstNode: ObjectLiteralExpression | undefined;
183
- if (existingProp && existingProp.isKind(SyntaxKind.PropertyAssignment)) {
184
- oldPropAstNode = existingProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
185
- }
186
-
187
- const newInitializer = this.convertJsonToAstString(propertyConfig, 2, oldPropAstNode);
188
-
189
- if (existingProp) {
190
- if (existingProp.isKind(SyntaxKind.PropertyAssignment)) {
191
- existingProp.setInitializer(newInitializer);
192
- }
193
- } else {
194
- propsObj.addPropertyAssignment({
195
- name: /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(propertyKey) ? propertyKey : JSON.stringify(propertyKey),
196
- initializer: newInitializer
197
- });
198
- }
199
-
200
- const file = this.getCollectionFile(collectionId);
201
- if (file) {
202
- file.formatText();
203
- }
204
- await this.project.save();
205
- }
206
- }
207
-
208
- public async deleteProperty(collectionId: string, propertyKey: string) {
209
- const collectionObj = this.getCollectionObject(collectionId);
210
- if (!collectionObj) return;
211
-
212
- const propertiesProp = collectionObj.getProperty("properties") as PropertyAssignment;
213
- if (propertiesProp) {
214
- const propsObj = propertiesProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
215
- if (propsObj) {
216
- const existingProp = propsObj.getProperty(
217
- (p: ObjectLiteralElementLike) => "getName" in p && typeof (p as PropertyAssignment).getName === "function" && ((p as PropertyAssignment).getName() === propertyKey || (p as PropertyAssignment).getName() === `"${propertyKey}"`)
218
- );
219
- if (existingProp) {
220
- existingProp.remove();
221
- const file = this.getCollectionFile(collectionId);
222
- if (file) {
223
- file.formatText();
224
- }
225
- await this.project.save();
226
- }
227
- }
228
- }
229
- }
230
-
231
- public async saveCollection(collectionId: string, collectionData: Record<string, unknown>) {
232
- let file = this.getCollectionFile(collectionId);
233
- const collectionObj = this.getCollectionObject(collectionId);
234
-
235
- if (!file || !collectionObj) {
236
- // Create a new file
237
- const safeId = this.sanitizeCollectionId(collectionId);
238
- const newFilePath = this.safePath(`${safeId}.ts`);
239
- file = this.project.createSourceFile(newFilePath, `import { EntityCollection } from "@rebasepro/types";\n\nconst ${safeId}Collection: EntityCollection = ${this.convertJsonToAstString(collectionData)};\n\nexport default ${safeId}Collection;\n`, { overwrite: true });
240
- } else {
241
- // Update root level properties gracefully
242
-
243
- // Force delete securityRules if empty or undefined to handle Formex / serialization stripping
244
- if (!("securityRules" in collectionData) || collectionData.securityRules === undefined || (Array.isArray(collectionData.securityRules) && collectionData.securityRules.length === 0)) {
245
- const srProp = collectionObj.getProperty("securityRules");
246
- if (srProp) {
247
- srProp.remove();
248
- }
249
-
250
- // If it was in collectionData as an empty array, delete it so the loop below doesn't add it back as "[]"
251
- // Actually, if it's "[]", omitting it entirely from the TS file achieves the same logical effect (no RLS rules)
252
- // and correctly triggers "unmapped policies" if the DB still has them.
253
- delete collectionData["securityRules"];
254
- }
255
-
256
- for (const key of Object.keys(collectionData)) {
257
- if (key === "relations") continue; // Kept via other AST functions or handled separately.
258
-
259
- const prop = collectionObj.getProperty(key) as PropertyAssignment;
260
-
261
- let oldAstNode: ObjectLiteralExpression | undefined;
262
- if (prop && prop.isKind(SyntaxKind.PropertyAssignment)) {
263
- oldAstNode = prop.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
264
- }
265
-
266
- const newInit = this.convertJsonToAstString(collectionData[key], 1, oldAstNode);
267
- if (prop) {
268
- prop.setInitializer(newInit);
269
- } else {
270
- collectionObj.addPropertyAssignment({
271
- name: key,
272
- initializer: newInit
273
- });
274
- }
275
- }
276
- }
277
- if (file) {
278
- file.formatText();
279
- }
280
- await this.project.save();
281
- }
282
-
283
- public async deleteCollection(collectionId: string) {
284
- const file = this.getCollectionFile(collectionId);
285
- if (file) {
286
- file.deleteImmediatelySync();
287
- }
288
- }
289
- }
@@ -1,61 +0,0 @@
1
- import { EntityCollection, EntityBeforeSaveProps, EntityAfterSaveProps, EntityAfterSaveErrorProps, EntityAfterReadProps, EntityBeforeDeleteProps, EntityAfterDeleteProps, PostgresCollection } from "@rebasepro/types";
2
- import { logger } from "../../utils/logger";
3
-
4
- export const callbacksTestCollection: PostgresCollection = {
5
- name: "Callback Tests",
6
- slug: "callback_tests",
7
- table: "callback_tests",
8
- description: "A collection to test backend callbacks",
9
- properties: {
10
- name: {
11
- name: "Name",
12
- validation: { required: true },
13
- type: "string"
14
- },
15
- hasSaveSuccessTriggered: {
16
- name: "Save Success Triggered",
17
- type: "boolean"
18
- },
19
- hasPreSaveTriggered: {
20
- name: "Pre Save Triggered",
21
- type: "boolean"
22
- },
23
- hasFetchTriggered: {
24
- name: "Fetch Triggered",
25
- type: "boolean"
26
- }
27
- },
28
- callbacks: {
29
- beforeSave: (props: EntityBeforeSaveProps) => {
30
- logger.info("🔥 [BACKEND_CALLBACK] beforeSave Triggered!", { detail: props });
31
- return {
32
- ...props.values,
33
- hasPreSaveTriggered: true,
34
- name: props.values.name + " (PreSaved)" // Modifying value before save
35
- };
36
- },
37
- afterSave: (props: EntityAfterSaveProps) => {
38
- logger.info("🔥 [BACKEND_CALLBACK] afterSave Triggered!", { detail: props });
39
- // This usually triggers other side effects (emails, notifications), log for now
40
- },
41
- afterSaveError: (props: EntityAfterSaveErrorProps) => {
42
- logger.error("🔥 [BACKEND_CALLBACK] afterSaveError Triggered!", { detail: props });
43
- },
44
- afterRead: (props: EntityAfterReadProps) => {
45
- logger.info("🔥 [BACKEND_CALLBACK] afterRead Triggered!", { detail: props });
46
- return {
47
- ...props.entity,
48
- values: {
49
- ...props.entity.values,
50
- hasFetchTriggered: true
51
- }
52
- };
53
- },
54
- beforeDelete: (props: EntityBeforeDeleteProps) => {
55
- logger.info("🔥 [BACKEND_CALLBACK] beforeDelete Triggered!", { detail: props });
56
- },
57
- afterDelete: (props: EntityAfterDeleteProps) => {
58
- logger.info("🔥 [BACKEND_CALLBACK] afterDelete Triggered!", { detail: props });
59
- }
60
- }
61
- };
package/src/api/errors.ts DELETED
@@ -1,278 +0,0 @@
1
- import type { ErrorHandler } from "hono";
2
- import type { ContentfulStatusCode } from "hono/utils/http-status";
3
- import type { HonoEnv } from "./types";
4
- import { logger } from "../utils/logger";
5
-
6
- /** Tracks whether we've already shown the doctor hint (once per process). */
7
- let _schemaDriftHinted = false;
8
-
9
- /** Shape of Postgres / network errors with diagnostic codes */
10
- interface PgLikeError {
11
- code?: string;
12
- address?: string;
13
- port?: number;
14
- message?: string;
15
- table?: string;
16
- column?: string;
17
- schema?: string;
18
- }
19
-
20
- /**
21
- * Extract the missing table or column name from a PG error.
22
- * PG 42P01 messages look like: 'relation "my_table" does not exist'
23
- * PG 42703 messages look like: 'column "my_col" does not exist' or 'column my_table.my_col does not exist'
24
- */
25
- function extractMissingIdentifier(pgMessage?: string): string | null {
26
- if (!pgMessage) return null;
27
- // Match quoted identifier: relation "xxx" / column "xxx"
28
- const quoted = pgMessage.match(/(?:relation|column|table)\s+"([^"]+)"/i);
29
- if (quoted) return quoted[1];
30
- // Match unquoted: column table.col does not exist
31
- const unquoted = pgMessage.match(/(?:relation|column|table)\s+([\w.]+)\s+does not exist/i);
32
- if (unquoted) return unquoted[1];
33
- return null;
34
- }
35
-
36
- /**
37
- * Standardized API error class.
38
- * Throw this from any route handler — the errorHandler middleware
39
- * will format it into `{ error: { message, code, details? } }`.
40
- */
41
- export class ApiError extends Error {
42
- public readonly statusCode: number;
43
- public readonly code: string;
44
- public readonly details?: unknown;
45
-
46
- constructor(statusCode: number, code: string, message: string, details?: unknown) {
47
- super(message);
48
- this.name = "ApiError";
49
- this.statusCode = statusCode;
50
- this.code = code;
51
- this.details = details;
52
- }
53
-
54
- // ── Factory methods ──────────────────────────────────────────────
55
-
56
- static badRequest(message: string, code = "BAD_REQUEST", details?: unknown): ApiError {
57
- return new ApiError(400, code, message, details);
58
- }
59
-
60
- static unauthorized(message: string, code = "UNAUTHORIZED"): ApiError {
61
- return new ApiError(401, code, message);
62
- }
63
-
64
- static forbidden(message: string, code = "FORBIDDEN"): ApiError {
65
- return new ApiError(403, code, message);
66
- }
67
-
68
- static notFound(message: string, code = "NOT_FOUND"): ApiError {
69
- return new ApiError(404, code, message);
70
- }
71
-
72
- static conflict(message: string, code = "CONFLICT"): ApiError {
73
- return new ApiError(409, code, message);
74
- }
75
-
76
- static internal(message: string, code = "INTERNAL_ERROR"): ApiError {
77
- return new ApiError(500, code, message);
78
- }
79
-
80
- static serviceUnavailable(message: string, code = "SERVICE_UNAVAILABLE"): ApiError {
81
- return new ApiError(503, code, message);
82
- }
83
- }
84
-
85
- /**
86
- * Canonical error response shape:
87
- * `{ error: { message: string, code: string, details?: unknown } }`
88
- */
89
- export interface ErrorResponse {
90
- error: {
91
- message: string;
92
- code: string;
93
- details?: unknown;
94
- /** Request correlation ID for tracing (echoes X-Request-ID). */
95
- requestId?: string;
96
- };
97
- }
98
-
99
- /**
100
- * General shape of errors that flow through the API error handler.
101
- * Extends Error with optional HTTP status, error code, and details.
102
- */
103
- export interface RebaseApiError extends Error {
104
- statusCode?: number;
105
- code?: string;
106
- details?: unknown;
107
- }
108
-
109
- /**
110
- * Type guard for errors that carry optional API metadata (statusCode, code, details).
111
- * Returns true for any Error instance — the optional properties are then
112
- * checked via normal property access.
113
- */
114
- export function isRebaseApiError(error: unknown): error is RebaseApiError {
115
- return error instanceof Error;
116
- }
117
-
118
- /**
119
- * Hono error-handling middleware (`app.onError`).
120
- * Converts any error into the canonical `{ error: { message, code } }` shape.
121
- */
122
- export const errorHandler: ErrorHandler<HonoEnv> = (err, c) => {
123
- // Typecast custom error properties
124
- const error: RebaseApiError = err;
125
- const reqId = typeof c.get === "function" ? c.get("requestId") : undefined;
126
-
127
- if (error instanceof ApiError || error.name === "ApiError") {
128
- // Operational errors — log at warn level
129
- logger.warn(
130
- `⚠️ [API] ${c.req.method} ${c.req.path} → ${error.statusCode} ${error.code}: ${error.message}` +
131
- (reqId ? ` [${reqId}]` : "")
132
- );
133
- return c.json({
134
- error: {
135
- message: error.message,
136
- code: error.code || "INTERNAL_ERROR",
137
- ...(error.details !== undefined && { details: error.details }),
138
- ...(reqId && { requestId: reqId })
139
- }
140
- } satisfies ErrorResponse, (error.statusCode || 500) as ContentfulStatusCode);
141
- }
142
-
143
- const statusCode = error.statusCode || codeToStatus(error.code) || 500;
144
- let code = error.code || "INTERNAL_ERROR";
145
-
146
- // Handle DB connection and specific system errors for better logging
147
- let logMessage = error.message;
148
-
149
- // Resolve the actual cause — Node's net module wraps dual-stack failures
150
- // in an AggregateError whose inner errors carry the real address/port.
151
- let resolvedCause: PgLikeError | undefined;
152
- if (error.cause && typeof error.cause === "object" && error.cause !== null && "code" in error.cause) {
153
- const cause = error.cause as PgLikeError & { errors?: PgLikeError[] };
154
- if (cause.code === "ECONNREFUSED" && !cause.address && Array.isArray(cause.errors)) {
155
- // AggregateError — pick the first inner error that has address info
156
- resolvedCause = cause.errors.find(e => e.address) || cause;
157
- } else {
158
- resolvedCause = cause;
159
- }
160
- }
161
-
162
- if (resolvedCause) {
163
- const cause = resolvedCause;
164
- if (cause.code === "ENETUNREACH") {
165
- logMessage = `Network unreachable. Cannot connect to database at ${cause.address}:${cause.port}.`;
166
- } else if (cause.code === "ECONNREFUSED") {
167
- logMessage = `Connection refused to database at ${cause.address}:${cause.port}. Is PostgreSQL running?`;
168
- } else if (cause.code === "42703" || cause.code === "42P01") {
169
- code = "SCHEMA_DRIFT";
170
- const issue = cause.code === "42703" ? "column" : "table";
171
- const identifier = cause.table || cause.column || extractMissingIdentifier(cause.message) || "unknown";
172
- logMessage = `Schema drift: ${issue} "${identifier}" does not exist in the database. Run \`pnpm db:push\` to sync your schema, or \`pnpm db:migrate\` to apply pending migrations.`;
173
- }
174
- } else if ("code" in error && error.code === "ENETUNREACH") {
175
- const netErr = error as PgLikeError;
176
- logMessage = `Network unreachable. Cannot connect to service at ${netErr.address}:${netErr.port}.`;
177
- } else if ("code" in error && (error.code === "42703" || error.code === "42P01")) {
178
- code = "SCHEMA_DRIFT";
179
- const issue = error.code === "42703" ? "column" : "table";
180
- const pgErr = error as PgLikeError;
181
- const identifier = pgErr.table || pgErr.column || extractMissingIdentifier(error.message) || "unknown";
182
- logMessage = `Schema drift: ${issue} "${identifier}" does not exist in the database. Run \`pnpm db:push\` to sync your schema, or \`pnpm db:migrate\` to apply pending migrations.`;
183
- }
184
-
185
- const causePg = (error.cause && typeof error.cause === "object") ? (error.cause as PgLikeError) : undefined;
186
- const pgErrorCode = causePg?.code || error.code;
187
- const isDbSchemaMismatch = code === "SCHEMA_DRIFT" || pgErrorCode === "42703" || pgErrorCode === "42P01";
188
-
189
- if (isDbSchemaMismatch) {
190
- // Database schema mismatch is logged as a warning instead of a fatal error
191
- logger.warn(
192
- `⚠️ [API] ${c.req.method} ${c.req.path} → ${statusCode} ${code}: ${logMessage}` +
193
- (reqId ? ` [${reqId}]` : "")
194
- );
195
- // In dev mode, show a one-time hint to run `rebase doctor`
196
- if (!_schemaDriftHinted && process.env.NODE_ENV !== "production") {
197
- _schemaDriftHinted = true;
198
- logger.warn([
199
- "",
200
- "┌──────────────────────────────────────────────────────────────┐",
201
- "│ 💡 TIP: Run `rebase doctor` for full schema diagnostics │",
202
- "│ │",
203
- "│ Quick fixes: │",
204
- "│ pnpm db:push sync schema to database (dev) │",
205
- "│ pnpm db:migrate generate + apply migration (prod) │",
206
- "│ rebase doctor full 3-way drift report │",
207
- "└──────────────────────────────────────────────────────────────┘",
208
- ""
209
- ].join("\n"));
210
- }
211
- } else {
212
- // Unexpected errors — log at error level
213
- logger.error(
214
- `❌ [API] ${c.req.method} ${c.req.path} → ${statusCode} ${code}: ${logMessage}` +
215
- (reqId ? ` [${reqId}]` : "")
216
- );
217
- }
218
-
219
- // Suppress the huge stack trace for known DB errors (it's noisy and leaks SQL)
220
- const suppressStack = isDbSchemaMismatch || (statusCode < 500 && code === "BAD_REQUEST");
221
- if (!suppressStack) {
222
- logger.error(String(error.stack || error));
223
- }
224
-
225
- // Sanitize the message for the client to prevent leaking sensitive details
226
- // like SQL queries or internal IP addresses.
227
- let clientMessage = "An unexpected error occurred";
228
- if (statusCode < 500 && error.message) {
229
- // If it's a 4xx error (e.g. from validation), it's generally safe to send the message
230
- clientMessage = error.message;
231
- } else if (error instanceof ApiError || error.name === "ApiError") {
232
- // We already handled ApiError above, but just in case
233
- clientMessage = error.message;
234
- } else if (code === "SCHEMA_DRIFT") {
235
- const pgErr = causePg || (error as PgLikeError);
236
- const issue = (pgErr.code === "42703" || pgErrorCode === "42703") ? "column" : "table";
237
- const identifier = pgErr.table || pgErr.column || extractMissingIdentifier(pgErr.message || error.message) || "unknown";
238
- clientMessage = `Schema drift: ${issue} "${identifier}" does not exist. Run \`pnpm db:push\` to sync your schema.`;
239
- } else if (code === "INTERNAL_ERROR") {
240
- clientMessage = "Internal Server Error";
241
- }
242
-
243
- return c.json({
244
- error: {
245
- message: clientMessage,
246
- code,
247
- ...(error.details !== undefined && { details: error.details }),
248
- ...(reqId && { requestId: reqId })
249
- }
250
- } satisfies ErrorResponse, statusCode as ContentfulStatusCode);
251
- };
252
-
253
- /**
254
- * Map known error codes to HTTP status codes.
255
- */
256
- function codeToStatus(code?: string): number | undefined {
257
- if (!code) return undefined;
258
- const map: Record<string, number> = {
259
- BAD_REQUEST: 400,
260
- INVALID_INPUT: 400,
261
- WEAK_PASSWORD: 400,
262
- UNAUTHORIZED: 401,
263
- INVALID_CREDENTIALS: 401,
264
- INVALID_TOKEN: 401,
265
- FORBIDDEN: 403,
266
- NOT_FOUND: 404,
267
- CONFLICT: 409,
268
- EMAIL_EXISTS: 409,
269
- ROLE_EXISTS: 409,
270
- SCHEMA_DRIFT: 500,
271
- INTERNAL_ERROR: 500,
272
- NOT_CONFIGURED: 503,
273
- SERVICE_UNAVAILABLE: 503
274
- };
275
- return map[code];
276
- }
277
-
278
-