@rebasepro/server-core 0.0.1-canary.4d4fb3e

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 (254) hide show
  1. package/LICENSE +6 -0
  2. package/README.md +40 -0
  3. package/build-errors.txt +52 -0
  4. package/coverage/clover.xml +3739 -0
  5. package/coverage/coverage-final.json +31 -0
  6. package/coverage/lcov-report/base.css +224 -0
  7. package/coverage/lcov-report/block-navigation.js +87 -0
  8. package/coverage/lcov-report/favicon.png +0 -0
  9. package/coverage/lcov-report/index.html +266 -0
  10. package/coverage/lcov-report/prettify.css +1 -0
  11. package/coverage/lcov-report/prettify.js +2 -0
  12. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  13. package/coverage/lcov-report/sorter.js +210 -0
  14. package/coverage/lcov-report/src/api/ast-schema-editor.ts.html +952 -0
  15. package/coverage/lcov-report/src/api/errors.ts.html +472 -0
  16. package/coverage/lcov-report/src/api/graphql/graphql-schema-generator.ts.html +1069 -0
  17. package/coverage/lcov-report/src/api/graphql/index.html +116 -0
  18. package/coverage/lcov-report/src/api/index.html +176 -0
  19. package/coverage/lcov-report/src/api/openapi-generator.ts.html +565 -0
  20. package/coverage/lcov-report/src/api/rest/api-generator.ts.html +994 -0
  21. package/coverage/lcov-report/src/api/rest/index.html +131 -0
  22. package/coverage/lcov-report/src/api/rest/query-parser.ts.html +550 -0
  23. package/coverage/lcov-report/src/api/schema-editor-routes.ts.html +202 -0
  24. package/coverage/lcov-report/src/api/server.ts.html +823 -0
  25. package/coverage/lcov-report/src/auth/admin-routes.ts.html +973 -0
  26. package/coverage/lcov-report/src/auth/index.html +176 -0
  27. package/coverage/lcov-report/src/auth/jwt.ts.html +574 -0
  28. package/coverage/lcov-report/src/auth/middleware.ts.html +745 -0
  29. package/coverage/lcov-report/src/auth/password.ts.html +310 -0
  30. package/coverage/lcov-report/src/auth/services.ts.html +2074 -0
  31. package/coverage/lcov-report/src/collections/index.html +116 -0
  32. package/coverage/lcov-report/src/collections/loader.ts.html +232 -0
  33. package/coverage/lcov-report/src/db/auth-schema.ts.html +523 -0
  34. package/coverage/lcov-report/src/db/data-transformer.ts.html +1753 -0
  35. package/coverage/lcov-report/src/db/entityService.ts.html +700 -0
  36. package/coverage/lcov-report/src/db/index.html +146 -0
  37. package/coverage/lcov-report/src/db/services/EntityFetchService.ts.html +4048 -0
  38. package/coverage/lcov-report/src/db/services/EntityPersistService.ts.html +883 -0
  39. package/coverage/lcov-report/src/db/services/RelationService.ts.html +3121 -0
  40. package/coverage/lcov-report/src/db/services/entity-helpers.ts.html +442 -0
  41. package/coverage/lcov-report/src/db/services/index.html +176 -0
  42. package/coverage/lcov-report/src/db/services/index.ts.html +124 -0
  43. package/coverage/lcov-report/src/generate-drizzle-schema-logic.ts.html +1960 -0
  44. package/coverage/lcov-report/src/index.html +116 -0
  45. package/coverage/lcov-report/src/services/driver-registry.ts.html +631 -0
  46. package/coverage/lcov-report/src/services/index.html +131 -0
  47. package/coverage/lcov-report/src/services/postgresDataDriver.ts.html +3025 -0
  48. package/coverage/lcov-report/src/storage/LocalStorageController.ts.html +1189 -0
  49. package/coverage/lcov-report/src/storage/S3StorageController.ts.html +970 -0
  50. package/coverage/lcov-report/src/storage/index.html +161 -0
  51. package/coverage/lcov-report/src/storage/storage-registry.ts.html +646 -0
  52. package/coverage/lcov-report/src/storage/types.ts.html +451 -0
  53. package/coverage/lcov-report/src/utils/drizzle-conditions.ts.html +3082 -0
  54. package/coverage/lcov-report/src/utils/index.html +116 -0
  55. package/coverage/lcov.info +7179 -0
  56. package/dist/common/src/collections/CollectionRegistry.d.ts +48 -0
  57. package/dist/common/src/collections/index.d.ts +1 -0
  58. package/dist/common/src/data/buildRebaseData.d.ts +14 -0
  59. package/dist/common/src/index.d.ts +3 -0
  60. package/dist/common/src/util/builders.d.ts +57 -0
  61. package/dist/common/src/util/callbacks.d.ts +6 -0
  62. package/dist/common/src/util/collections.d.ts +11 -0
  63. package/dist/common/src/util/common.d.ts +2 -0
  64. package/dist/common/src/util/conditions.d.ts +26 -0
  65. package/dist/common/src/util/entities.d.ts +36 -0
  66. package/dist/common/src/util/enums.d.ts +3 -0
  67. package/dist/common/src/util/index.d.ts +16 -0
  68. package/dist/common/src/util/navigation_from_path.d.ts +34 -0
  69. package/dist/common/src/util/navigation_utils.d.ts +20 -0
  70. package/dist/common/src/util/parent_references_from_path.d.ts +6 -0
  71. package/dist/common/src/util/paths.d.ts +14 -0
  72. package/dist/common/src/util/permissions.d.ts +5 -0
  73. package/dist/common/src/util/references.d.ts +2 -0
  74. package/dist/common/src/util/relations.d.ts +12 -0
  75. package/dist/common/src/util/resolutions.d.ts +72 -0
  76. package/dist/common/src/util/storage.d.ts +24 -0
  77. package/dist/index-BeMqpmfQ.js +239 -0
  78. package/dist/index-BeMqpmfQ.js.map +1 -0
  79. package/dist/index-bl4J3lNb.js +55823 -0
  80. package/dist/index-bl4J3lNb.js.map +1 -0
  81. package/dist/index.es.js +58 -0
  82. package/dist/index.es.js.map +1 -0
  83. package/dist/index.umd.js +56062 -0
  84. package/dist/index.umd.js.map +1 -0
  85. package/dist/server-core/src/api/ast-schema-editor.d.ts +21 -0
  86. package/dist/server-core/src/api/collections_for_test/callbacks_test_collection.d.ts +2 -0
  87. package/dist/server-core/src/api/errors.d.ts +35 -0
  88. package/dist/server-core/src/api/graphql/graphql-schema-generator.d.ts +35 -0
  89. package/dist/server-core/src/api/graphql/index.d.ts +1 -0
  90. package/dist/server-core/src/api/index.d.ts +9 -0
  91. package/dist/server-core/src/api/openapi-generator.d.ts +2 -0
  92. package/dist/server-core/src/api/rest/api-generator.d.ts +64 -0
  93. package/dist/server-core/src/api/rest/index.d.ts +1 -0
  94. package/dist/server-core/src/api/rest/query-parser.d.ts +9 -0
  95. package/dist/server-core/src/api/schema-editor-routes.d.ts +3 -0
  96. package/dist/server-core/src/api/server.d.ts +40 -0
  97. package/dist/server-core/src/api/types.d.ts +90 -0
  98. package/dist/server-core/src/auth/admin-routes.d.ts +7 -0
  99. package/dist/server-core/src/auth/google-oauth.d.ts +20 -0
  100. package/dist/server-core/src/auth/index.d.ts +12 -0
  101. package/dist/server-core/src/auth/interfaces.d.ts +270 -0
  102. package/dist/server-core/src/auth/jwt.d.ts +42 -0
  103. package/dist/server-core/src/auth/middleware.d.ts +56 -0
  104. package/dist/server-core/src/auth/password.d.ts +22 -0
  105. package/dist/server-core/src/auth/rate-limiter.d.ts +31 -0
  106. package/dist/server-core/src/auth/routes.d.ts +17 -0
  107. package/dist/server-core/src/bootstrappers/index.d.ts +0 -0
  108. package/dist/server-core/src/collections/BackendCollectionRegistry.d.ts +13 -0
  109. package/dist/server-core/src/collections/loader.d.ts +5 -0
  110. package/dist/server-core/src/db/interfaces.d.ts +18 -0
  111. package/dist/server-core/src/email/index.d.ts +6 -0
  112. package/dist/server-core/src/email/smtp-email-service.d.ts +25 -0
  113. package/dist/server-core/src/email/templates.d.ts +33 -0
  114. package/dist/server-core/src/email/types.d.ts +110 -0
  115. package/dist/server-core/src/functions/function-loader.d.ts +17 -0
  116. package/dist/server-core/src/functions/function-routes.d.ts +10 -0
  117. package/dist/server-core/src/functions/index.d.ts +3 -0
  118. package/dist/server-core/src/history/history-routes.d.ts +23 -0
  119. package/dist/server-core/src/history/index.d.ts +1 -0
  120. package/dist/server-core/src/index.d.ts +24 -0
  121. package/dist/server-core/src/init.d.ts +49 -0
  122. package/dist/server-core/src/serve-spa.d.ts +30 -0
  123. package/dist/server-core/src/services/driver-registry.d.ts +78 -0
  124. package/dist/server-core/src/storage/LocalStorageController.d.ts +46 -0
  125. package/dist/server-core/src/storage/S3StorageController.d.ts +36 -0
  126. package/dist/server-core/src/storage/index.d.ts +18 -0
  127. package/dist/server-core/src/storage/routes.d.ts +38 -0
  128. package/dist/server-core/src/storage/storage-registry.d.ts +78 -0
  129. package/dist/server-core/src/storage/types.d.ts +91 -0
  130. package/dist/server-core/src/types/index.d.ts +11 -0
  131. package/dist/server-core/src/utils/logging.d.ts +9 -0
  132. package/dist/server-core/src/utils/sql.d.ts +27 -0
  133. package/dist/types/src/controllers/analytics_controller.d.ts +7 -0
  134. package/dist/types/src/controllers/auth.d.ts +117 -0
  135. package/dist/types/src/controllers/client.d.ts +58 -0
  136. package/dist/types/src/controllers/collection_registry.d.ts +44 -0
  137. package/dist/types/src/controllers/customization_controller.d.ts +54 -0
  138. package/dist/types/src/controllers/data.d.ts +141 -0
  139. package/dist/types/src/controllers/data_driver.d.ts +168 -0
  140. package/dist/types/src/controllers/database_admin.d.ts +11 -0
  141. package/dist/types/src/controllers/dialogs_controller.d.ts +36 -0
  142. package/dist/types/src/controllers/effective_role.d.ts +4 -0
  143. package/dist/types/src/controllers/index.d.ts +17 -0
  144. package/dist/types/src/controllers/local_config_persistence.d.ts +20 -0
  145. package/dist/types/src/controllers/navigation.d.ts +213 -0
  146. package/dist/types/src/controllers/registry.d.ts +51 -0
  147. package/dist/types/src/controllers/side_dialogs_controller.d.ts +67 -0
  148. package/dist/types/src/controllers/side_entity_controller.d.ts +89 -0
  149. package/dist/types/src/controllers/snackbar.d.ts +24 -0
  150. package/dist/types/src/controllers/storage.d.ts +173 -0
  151. package/dist/types/src/index.d.ts +4 -0
  152. package/dist/types/src/rebase_context.d.ts +101 -0
  153. package/dist/types/src/types/backend.d.ts +533 -0
  154. package/dist/types/src/types/builders.d.ts +14 -0
  155. package/dist/types/src/types/chips.d.ts +5 -0
  156. package/dist/types/src/types/collections.d.ts +812 -0
  157. package/dist/types/src/types/data_source.d.ts +64 -0
  158. package/dist/types/src/types/entities.d.ts +145 -0
  159. package/dist/types/src/types/entity_actions.d.ts +98 -0
  160. package/dist/types/src/types/entity_callbacks.d.ts +173 -0
  161. package/dist/types/src/types/entity_link_builder.d.ts +7 -0
  162. package/dist/types/src/types/entity_overrides.d.ts +9 -0
  163. package/dist/types/src/types/entity_views.d.ts +61 -0
  164. package/dist/types/src/types/export_import.d.ts +21 -0
  165. package/dist/types/src/types/index.d.ts +22 -0
  166. package/dist/types/src/types/locales.d.ts +4 -0
  167. package/dist/types/src/types/modify_collections.d.ts +5 -0
  168. package/dist/types/src/types/plugins.d.ts +225 -0
  169. package/dist/types/src/types/properties.d.ts +1091 -0
  170. package/dist/types/src/types/property_config.d.ts +70 -0
  171. package/dist/types/src/types/relations.d.ts +336 -0
  172. package/dist/types/src/types/slots.d.ts +228 -0
  173. package/dist/types/src/types/translations.d.ts +826 -0
  174. package/dist/types/src/types/user_management_delegate.d.ts +120 -0
  175. package/dist/types/src/types/websockets.d.ts +78 -0
  176. package/dist/types/src/users/index.d.ts +2 -0
  177. package/dist/types/src/users/roles.d.ts +22 -0
  178. package/dist/types/src/users/user.d.ts +46 -0
  179. package/history_diff.log +385 -0
  180. package/jest.config.cjs +16 -0
  181. package/package.json +86 -0
  182. package/scratch.ts +8 -0
  183. package/src/api/ast-schema-editor.ts +289 -0
  184. package/src/api/collections_for_test/callbacks_test_collection.ts +57 -0
  185. package/src/api/errors.ts +155 -0
  186. package/src/api/graphql/graphql-schema-generator.ts +334 -0
  187. package/src/api/graphql/index.ts +2 -0
  188. package/src/api/index.ts +11 -0
  189. package/src/api/openapi-generator.ts +160 -0
  190. package/src/api/rest/api-generator.ts +466 -0
  191. package/src/api/rest/index.ts +2 -0
  192. package/src/api/rest/query-parser.ts +155 -0
  193. package/src/api/schema-editor-routes.ts +39 -0
  194. package/src/api/server.ts +245 -0
  195. package/src/api/types.ts +90 -0
  196. package/src/auth/admin-routes.ts +488 -0
  197. package/src/auth/google-oauth.ts +60 -0
  198. package/src/auth/index.ts +21 -0
  199. package/src/auth/interfaces.ts +316 -0
  200. package/src/auth/jwt.ts +164 -0
  201. package/src/auth/middleware.ts +235 -0
  202. package/src/auth/password.ts +75 -0
  203. package/src/auth/rate-limiter.ts +129 -0
  204. package/src/auth/routes.ts +730 -0
  205. package/src/bootstrappers/index.ts +1 -0
  206. package/src/collections/BackendCollectionRegistry.ts +20 -0
  207. package/src/collections/loader.ts +49 -0
  208. package/src/db/interfaces.ts +60 -0
  209. package/src/email/index.ts +17 -0
  210. package/src/email/smtp-email-service.ts +88 -0
  211. package/src/email/templates.ts +301 -0
  212. package/src/email/types.ts +112 -0
  213. package/src/functions/function-loader.ts +91 -0
  214. package/src/functions/function-routes.ts +31 -0
  215. package/src/functions/index.ts +3 -0
  216. package/src/history/history-routes.ts +128 -0
  217. package/src/history/index.ts +2 -0
  218. package/src/index.ts +56 -0
  219. package/src/init.ts +309 -0
  220. package/src/serve-spa.ts +81 -0
  221. package/src/services/driver-registry.ts +182 -0
  222. package/src/storage/LocalStorageController.ts +368 -0
  223. package/src/storage/S3StorageController.ts +295 -0
  224. package/src/storage/index.ts +32 -0
  225. package/src/storage/routes.ts +247 -0
  226. package/src/storage/storage-registry.ts +187 -0
  227. package/src/storage/types.ts +122 -0
  228. package/src/types/index.ts +27 -0
  229. package/src/utils/logging.ts +35 -0
  230. package/src/utils/sql.ts +38 -0
  231. package/test/admin-routes.test.ts +591 -0
  232. package/test/api-generator.test.ts +458 -0
  233. package/test/ast-schema-editor.test.ts +61 -0
  234. package/test/auth-middleware-hono.test.ts +321 -0
  235. package/test/auth-routes.test.ts +868 -0
  236. package/test/driver-registry.test.ts +280 -0
  237. package/test/errors-hono.test.ts +133 -0
  238. package/test/errors.test.ts +150 -0
  239. package/test/jwt-security.test.ts +173 -0
  240. package/test/jwt.test.ts +311 -0
  241. package/test/middleware.test.ts +295 -0
  242. package/test/password.test.ts +165 -0
  243. package/test/query-parser.test.ts +258 -0
  244. package/test/rate-limiter.test.ts +102 -0
  245. package/test/storage-local.test.ts +278 -0
  246. package/test/storage-registry.test.ts +280 -0
  247. package/test/storage-routes.test.ts +218 -0
  248. package/test/storage-s3.test.ts +301 -0
  249. package/test-ast.ts +28 -0
  250. package/test_output.txt +1133 -0
  251. package/tsconfig.json +49 -0
  252. package/tsconfig.prod.json +20 -0
  253. package/vite.config.ts +78 -0
  254. package/vite.config.ts.timestamp-1775065397568-8a853255edf6e.mjs +46 -0
package/package.json ADDED
@@ -0,0 +1,86 @@
1
+ {
2
+ "name": "@rebasepro/server-core",
3
+ "type": "module",
4
+ "version": "0.0.1-canary.4d4fb3e",
5
+ "description": "Database-Agnostic Backend Core for Rebase",
6
+ "funding": {
7
+ "url": "https://github.com/sponsors/rebaseco"
8
+ },
9
+ "author": "Rebase",
10
+ "license": "MIT",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "https://github.com/rebasepro/rebase.git",
14
+ "directory": "packages/backend"
15
+ },
16
+ "main": "./dist/index.umd.js",
17
+ "module": "./dist/index.es.js",
18
+ "types": "./dist/server-core/src/index.d.ts",
19
+ "source": "src/index.ts",
20
+ "engines": {
21
+ "node": ">=14"
22
+ },
23
+ "keywords": [
24
+ "firebase",
25
+ "cms",
26
+ "admin",
27
+ "admin panel",
28
+ "postgresql",
29
+ "drizzle",
30
+ "backend",
31
+ "database",
32
+ "rebase"
33
+ ],
34
+ "scripts": {
35
+ "watch": "vite build --watch",
36
+ "build": "vite build && tsc --emitDeclarationOnly -p tsconfig.prod.json",
37
+ "prepublishOnly": "pnpm run build",
38
+ "test:lint": "eslint \"src/**\" --quiet",
39
+ "test": "jest --passWithNoTests",
40
+ "clean": "rm -rf dist && find ./src -name '*.js' -type f | xargs rm -f"
41
+ },
42
+ "exports": {
43
+ ".": {
44
+ "types": "./dist/server-core/src/index.d.ts",
45
+ "development": "./src/index.ts",
46
+ "import": "./dist/index.es.js",
47
+ "require": "./dist/index.umd.js"
48
+ },
49
+ "./package.json": "./package.json"
50
+ },
51
+ "dependencies": {
52
+ "@aws-sdk/client-s3": "^3.654.0",
53
+ "@aws-sdk/s3-request-presigner": "^3.654.0",
54
+ "@hono/graphql-server": "0.7.0",
55
+ "@hono/node-server": "1.19.12",
56
+ "@rebasepro/common": "0.0.1-canary.4d4fb3e",
57
+ "@rebasepro/types": "0.0.1-canary.4d4fb3e",
58
+ "@rebasepro/utils": "0.0.1-canary.4d4fb3e",
59
+ "google-auth-library": "^9.0.0",
60
+ "graphql": "^16.8.1",
61
+ "hono": "4.12.10",
62
+ "jsonwebtoken": "^9.0.0",
63
+ "nodemailer": "^6.9.0",
64
+ "ws": "^8.16.0",
65
+ "zod": "^3.22.4"
66
+ },
67
+ "devDependencies": {
68
+ "@rebasepro/common": "workspace:*",
69
+ "@rebasepro/types": "workspace:*",
70
+ "@types/jest": "^29.5.14",
71
+ "@types/jsonwebtoken": "^9.0.0",
72
+ "@types/node": "^20.10.5",
73
+ "@types/nodemailer": "^6.4.0",
74
+ "@types/react": "^19.0.8",
75
+ "@types/react-dom": "^19.0.3",
76
+ "@types/ws": "^8.5.10",
77
+ "jest": "^29.7.0",
78
+ "ts-jest": "29.4.1",
79
+ "typescript": "^5.0.0",
80
+ "vite": "^5.0.0"
81
+ },
82
+ "gitHead": "71bcef3c51a458cd054f7924cc18efbbe515dcc8",
83
+ "publishConfig": {
84
+ "access": "public"
85
+ }
86
+ }
package/scratch.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { Hono } from 'hono';
2
+ const app = new Hono();
3
+ const child = new Hono();
4
+ child.get('/*', (c) => {
5
+ return c.json({ star: c.req.param('*'), path: c.req.path });
6
+ })
7
+ app.route('/api', child);
8
+ app.request(new Request('http://localhost/api/users/1/posts')).then(r => r.json()).then(console.log);
@@ -0,0 +1,289 @@
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: number = 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 `"${obj.replace(/"/g, '\\"')}"`;
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 : `"${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 : `"${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
+ let 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 : `"${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
+ let 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
+ let 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
+ }
@@ -0,0 +1,57 @@
1
+ import { EntityCollection, EntityBeforeSaveProps, EntityAfterSaveProps, EntityAfterSaveErrorProps, EntityAfterReadProps, EntityBeforeDeleteProps, EntityAfterDeleteProps, PostgresCollection } from "@rebasepro/types";
2
+
3
+ export const callbacksTestCollection: PostgresCollection = {
4
+ name: "Callback Tests",
5
+ slug: "callback_tests",
6
+ table: "callback_tests",
7
+ description: "A collection to test backend callbacks",
8
+ properties: {
9
+ name: {
10
+ name: "Name",
11
+ validation: { required: true },
12
+ type: "string"
13
+ },
14
+ hasSaveSuccessTriggered: {
15
+ name: "Save Success Triggered",
16
+ type: "boolean"
17
+ },
18
+ hasPreSaveTriggered: {
19
+ name: "Pre Save Triggered",
20
+ type: "boolean"
21
+ },
22
+ hasFetchTriggered: {
23
+ name: "Fetch Triggered",
24
+ type: "boolean"
25
+ }
26
+ },
27
+ callbacks: {
28
+ beforeSave: (props: EntityBeforeSaveProps) => {
29
+ console.log("🔥 [BACKEND_CALLBACK] beforeSave Triggered!", props);
30
+ return {
31
+ ...props.values,
32
+ hasPreSaveTriggered: true,
33
+ name: props.values.name + " (PreSaved)" // Modifying value before save
34
+ };
35
+ },
36
+ afterSave: (props: EntityAfterSaveProps) => {
37
+ console.log("🔥 [BACKEND_CALLBACK] afterSave Triggered!", props);
38
+ // This usually triggers other side effects (emails, notifications), log for now
39
+ },
40
+ afterSaveError: (props: EntityAfterSaveErrorProps) => {
41
+ console.error("🔥 [BACKEND_CALLBACK] afterSaveError Triggered!", props);
42
+ },
43
+ afterRead: (props: EntityAfterReadProps) => {
44
+ console.log("🔥 [BACKEND_CALLBACK] afterRead Triggered!", props);
45
+ return {
46
+ ...props.entity.values,
47
+ hasFetchTriggered: true
48
+ };
49
+ },
50
+ beforeDelete: (props: EntityBeforeDeleteProps) => {
51
+ console.log("🔥 [BACKEND_CALLBACK] beforeDelete Triggered!", props);
52
+ },
53
+ afterDelete: (props: EntityAfterDeleteProps) => {
54
+ console.log("🔥 [BACKEND_CALLBACK] afterDelete Triggered!", props);
55
+ }
56
+ }
57
+ };
@@ -0,0 +1,155 @@
1
+ import { ErrorHandler } from "hono";
2
+ import { ContentfulStatusCode } from "hono/utils/http-status";
3
+
4
+ /**
5
+ * Standardized API error class.
6
+ * Throw this from any route handler — the errorHandler middleware
7
+ * will format it into `{ error: { message, code, details? } }`.
8
+ */
9
+ export class ApiError extends Error {
10
+ public readonly statusCode: number;
11
+ public readonly code: string;
12
+ public readonly details?: unknown;
13
+
14
+ constructor(statusCode: number, code: string, message: string, details?: unknown) {
15
+ super(message);
16
+ this.name = "ApiError";
17
+ this.statusCode = statusCode;
18
+ this.code = code;
19
+ this.details = details;
20
+ }
21
+
22
+ // ── Factory methods ──────────────────────────────────────────────
23
+
24
+ static badRequest(message: string, code = "BAD_REQUEST", details?: unknown): ApiError {
25
+ return new ApiError(400, code, message, details);
26
+ }
27
+
28
+ static unauthorized(message: string, code = "UNAUTHORIZED"): ApiError {
29
+ return new ApiError(401, code, message);
30
+ }
31
+
32
+ static forbidden(message: string, code = "FORBIDDEN"): ApiError {
33
+ return new ApiError(403, code, message);
34
+ }
35
+
36
+ static notFound(message: string, code = "NOT_FOUND"): ApiError {
37
+ return new ApiError(404, code, message);
38
+ }
39
+
40
+ static conflict(message: string, code = "CONFLICT"): ApiError {
41
+ return new ApiError(409, code, message);
42
+ }
43
+
44
+ static internal(message: string, code = "INTERNAL_ERROR"): ApiError {
45
+ return new ApiError(500, code, message);
46
+ }
47
+
48
+ static serviceUnavailable(message: string, code = "SERVICE_UNAVAILABLE"): ApiError {
49
+ return new ApiError(503, code, message);
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Canonical error response shape:
55
+ * `{ error: { message: string, code: string, details?: unknown } }`
56
+ */
57
+ export interface ErrorResponse {
58
+ error: {
59
+ message: string;
60
+ code: string;
61
+ details?: unknown;
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Hono error-handling middleware (`app.onError`).
67
+ * Converts any error into the canonical `{ error: { message, code } }` shape.
68
+ */
69
+ export const errorHandler: ErrorHandler = (err, c) => {
70
+ // Typecast custom error properties
71
+ const error = err as Error & { statusCode?: number; code?: string; details?: unknown };
72
+
73
+ if (error instanceof ApiError) {
74
+ // Operational errors — log at warn level
75
+ console.warn(
76
+ `⚠️ [API] ${c.req.method} ${c.req.path} → ${error.statusCode} ${error.code}: ${error.message}`
77
+ );
78
+ return c.json({
79
+ error: {
80
+ message: error.message,
81
+ code: error.code,
82
+ ...(error.details !== undefined && { details: error.details })
83
+ }
84
+ } satisfies ErrorResponse, (error.statusCode || 500) as ContentfulStatusCode);
85
+ }
86
+
87
+ const statusCode = error.statusCode || codeToStatus(error.code) || 500;
88
+ const code = error.code || "INTERNAL_ERROR";
89
+
90
+ // Handle DB connection and specific system errors for better logging
91
+ let logMessage = error.message;
92
+ if (error.cause && typeof error.cause === 'object' && 'code' in error.cause) {
93
+ const cause = error.cause as any;
94
+ if (cause.code === 'ENETUNREACH') {
95
+ logMessage = `Network unreachable. Cannot connect to database at ${cause.address}:${cause.port}.`;
96
+ } else if (cause.code === 'ECONNREFUSED') {
97
+ logMessage = `Connection refused to database at ${cause.address}:${cause.port}.`;
98
+ }
99
+ } else if ('code' in error && error.code === 'ENETUNREACH') {
100
+ logMessage = `Network unreachable. Cannot connect to service at ${(error as any).address}:${(error as any).port}.`;
101
+ }
102
+
103
+ // Unexpected errors — log at error level with full stack
104
+ console.error(
105
+ `❌ [API] ${c.req.method} ${c.req.path} → ${statusCode} ${code}: ${logMessage}`
106
+ );
107
+ console.error(error.stack || error);
108
+
109
+ // Sanitize the message for the client to prevent leaking sensitive details
110
+ // like SQL queries or internal IP addresses.
111
+ let clientMessage = "An unexpected error occurred";
112
+ if (statusCode < 500 && error.message) {
113
+ // If it's a 4xx error (e.g. from validation), it's generally safe to send the message
114
+ clientMessage = error.message;
115
+ } else if (error instanceof ApiError) {
116
+ // We already handled ApiError above, but just in case
117
+ clientMessage = error.message;
118
+ } else if (code === 'INTERNAL_ERROR') {
119
+ clientMessage = "Internal Server Error";
120
+ }
121
+
122
+ return c.json({
123
+ error: {
124
+ message: clientMessage,
125
+ code,
126
+ ...(error.details !== undefined && { details: error.details })
127
+ }
128
+ } satisfies ErrorResponse, statusCode as ContentfulStatusCode);
129
+ };
130
+
131
+ /**
132
+ * Map known error codes to HTTP status codes.
133
+ */
134
+ function codeToStatus(code?: string): number | undefined {
135
+ if (!code) return undefined;
136
+ const map: Record<string, number> = {
137
+ BAD_REQUEST: 400,
138
+ INVALID_INPUT: 400,
139
+ WEAK_PASSWORD: 400,
140
+ UNAUTHORIZED: 401,
141
+ INVALID_CREDENTIALS: 401,
142
+ INVALID_TOKEN: 401,
143
+ FORBIDDEN: 403,
144
+ NOT_FOUND: 404,
145
+ CONFLICT: 409,
146
+ EMAIL_EXISTS: 409,
147
+ ROLE_EXISTS: 409,
148
+ INTERNAL_ERROR: 500,
149
+ NOT_CONFIGURED: 503,
150
+ SERVICE_UNAVAILABLE: 503,
151
+ };
152
+ return map[code];
153
+ }
154
+
155
+