@appweaver/core 1.0.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 (271) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +7 -0
  3. package/app/application.d.ts +43 -0
  4. package/app/application.js +112 -0
  5. package/app/create-app.d.ts +32 -0
  6. package/app/create-app.js +38 -0
  7. package/app/index.d.ts +2 -0
  8. package/app/index.js +18 -0
  9. package/app/lifecycle-manager.d.ts +20 -0
  10. package/app/lifecycle-manager.js +42 -0
  11. package/app/load-modules.d.ts +10 -0
  12. package/app/load-modules.js +50 -0
  13. package/app/load-providers.d.ts +8 -0
  14. package/app/load-providers.js +33 -0
  15. package/cache/cache-service.d.ts +72 -0
  16. package/cache/cache-service.js +202 -0
  17. package/cache/cache.d.ts +12 -0
  18. package/cache/cache.js +184 -0
  19. package/cache/caching.d.ts +8 -0
  20. package/cache/caching.js +72 -0
  21. package/cache/eviction/eviction-index.d.ts +35 -0
  22. package/cache/eviction/eviction-index.js +2 -0
  23. package/cache/eviction/fifo-eviction-index.d.ts +7 -0
  24. package/cache/eviction/fifo-eviction-index.js +28 -0
  25. package/cache/eviction/index.d.ts +4 -0
  26. package/cache/eviction/index.js +20 -0
  27. package/cache/eviction/lfu-eviction-index.d.ts +8 -0
  28. package/cache/eviction/lfu-eviction-index.js +82 -0
  29. package/cache/eviction/lru-eviction-index.d.ts +8 -0
  30. package/cache/eviction/lru-eviction-index.js +81 -0
  31. package/cache/index.d.ts +2 -0
  32. package/cache/index.js +18 -0
  33. package/cache/memory-cache.d.ts +4 -0
  34. package/cache/memory-cache.js +12 -0
  35. package/cache/redis-cache.d.ts +4 -0
  36. package/cache/redis-cache.js +12 -0
  37. package/context/context.d.ts +2 -0
  38. package/context/context.js +13 -0
  39. package/context/dependency-injection.d.ts +98 -0
  40. package/context/dependency-injection.js +276 -0
  41. package/context/index.d.ts +2 -0
  42. package/context/index.js +18 -0
  43. package/database/create-client.d.ts +11 -0
  44. package/database/create-client.js +142 -0
  45. package/database/index.d.ts +1 -0
  46. package/database/index.js +17 -0
  47. package/database/prisma-database.d.ts +15 -0
  48. package/database/prisma-database.js +53 -0
  49. package/errors/error-handler.d.ts +3 -0
  50. package/errors/error-handler.js +24 -0
  51. package/errors/error-schema.d.ts +32 -0
  52. package/errors/error-schema.js +31 -0
  53. package/errors/http-error.d.ts +21 -0
  54. package/errors/http-error.js +33 -0
  55. package/errors/index.d.ts +3 -0
  56. package/errors/index.js +19 -0
  57. package/events/node-events.d.ts +7 -0
  58. package/events/node-events.js +39 -0
  59. package/export/export-service.d.ts +19 -0
  60. package/export/export-service.js +154 -0
  61. package/export/index.d.ts +1 -0
  62. package/export/index.js +17 -0
  63. package/factory/create-model.d.ts +2 -0
  64. package/factory/create-model.js +366 -0
  65. package/factory/create-policy.d.ts +2 -0
  66. package/factory/create-policy.js +16 -0
  67. package/factory/create-routes.d.ts +2 -0
  68. package/factory/create-routes.js +21 -0
  69. package/factory/create-service.d.ts +3 -0
  70. package/factory/create-service.js +97 -0
  71. package/factory/index.d.ts +4 -0
  72. package/factory/index.js +20 -0
  73. package/health/health-routes.d.ts +2 -0
  74. package/health/health-routes.js +36 -0
  75. package/health/health-schema.d.ts +45 -0
  76. package/health/health-schema.js +52 -0
  77. package/health/health-service.d.ts +38 -0
  78. package/health/health-service.js +82 -0
  79. package/health/index.d.ts +2 -0
  80. package/health/index.js +18 -0
  81. package/index.d.ts +15 -0
  82. package/index.js +31 -0
  83. package/mailer/email-service.d.ts +36 -0
  84. package/mailer/email-service.js +89 -0
  85. package/mailer/index.d.ts +1 -0
  86. package/mailer/index.js +17 -0
  87. package/mailer/json-mailer.d.ts +7 -0
  88. package/mailer/json-mailer.js +32 -0
  89. package/mailer/smtp-mailer.d.ts +7 -0
  90. package/mailer/smtp-mailer.js +43 -0
  91. package/memory/in-memory.d.ts +24 -0
  92. package/memory/in-memory.js +164 -0
  93. package/memory/redis.d.ts +26 -0
  94. package/memory/redis.js +158 -0
  95. package/package.json +68 -0
  96. package/prisma/client/browser.d.ts +34 -0
  97. package/prisma/client/browser.js +56 -0
  98. package/prisma/client/client.d.ts +53 -0
  99. package/prisma/client/client.js +70 -0
  100. package/prisma/client/commonInputTypes.d.ts +395 -0
  101. package/prisma/client/commonInputTypes.js +11 -0
  102. package/prisma/client/enums.d.ts +1 -0
  103. package/prisma/client/enums.js +11 -0
  104. package/prisma/client/internal/class.d.ts +187 -0
  105. package/prisma/client/internal/class.js +85 -0
  106. package/prisma/client/internal/prismaNamespace.d.ts +987 -0
  107. package/prisma/client/internal/prismaNamespace.js +193 -0
  108. package/prisma/client/internal/prismaNamespaceBrowser.d.ts +125 -0
  109. package/prisma/client/internal/prismaNamespaceBrowser.js +164 -0
  110. package/prisma/client/models/ApiKey.d.ts +1167 -0
  111. package/prisma/client/models/ApiKey.js +2 -0
  112. package/prisma/client/models/File.d.ts +1248 -0
  113. package/prisma/client/models/File.js +2 -0
  114. package/prisma/client/models/OneTimeToken.d.ts +1083 -0
  115. package/prisma/client/models/OneTimeToken.js +2 -0
  116. package/prisma/client/models/Permission.d.ts +1209 -0
  117. package/prisma/client/models/Permission.js +2 -0
  118. package/prisma/client/models/Role.d.ts +1209 -0
  119. package/prisma/client/models/Role.js +2 -0
  120. package/prisma/client/models/Seeder.d.ts +1023 -0
  121. package/prisma/client/models/Seeder.js +2 -0
  122. package/prisma/client/models.d.ts +7 -0
  123. package/prisma/client/models.js +2 -0
  124. package/queue/bull-queue.d.ts +37 -0
  125. package/queue/bull-queue.js +207 -0
  126. package/queue/memory-queue.d.ts +54 -0
  127. package/queue/memory-queue.js +283 -0
  128. package/resource/index.d.ts +4 -0
  129. package/resource/index.js +20 -0
  130. package/resource/resource-loader.d.ts +26 -0
  131. package/resource/resource-loader.js +161 -0
  132. package/resource/resource-routes.d.ts +3 -0
  133. package/resource/resource-routes.js +174 -0
  134. package/resource/resource-schema.d.ts +33 -0
  135. package/resource/resource-schema.js +186 -0
  136. package/resource/resource-service.d.ts +89 -0
  137. package/resource/resource-service.js +772 -0
  138. package/resources.d.ts +9 -0
  139. package/resources.js +24 -0
  140. package/scheduler/cron-scheduler.d.ts +12 -0
  141. package/scheduler/cron-scheduler.js +73 -0
  142. package/security/account/account-routes.d.ts +2 -0
  143. package/security/account/account-routes.js +104 -0
  144. package/security/account/account-schema.d.ts +290 -0
  145. package/security/account/account-schema.js +166 -0
  146. package/security/account/account-service.d.ts +88 -0
  147. package/security/account/account-service.js +218 -0
  148. package/security/account/index.d.ts +3 -0
  149. package/security/account/index.js +19 -0
  150. package/security/api-key/api-key-auth.d.ts +4 -0
  151. package/security/api-key/api-key-auth.js +66 -0
  152. package/security/api-key/index.d.ts +1 -0
  153. package/security/api-key/index.js +17 -0
  154. package/security/auth-routes.d.ts +2 -0
  155. package/security/auth-routes.js +80 -0
  156. package/security/auth-schema.d.ts +215 -0
  157. package/security/auth-schema.js +129 -0
  158. package/security/auth-service.d.ts +117 -0
  159. package/security/auth-service.js +272 -0
  160. package/security/auth.d.ts +3 -0
  161. package/security/auth.js +127 -0
  162. package/security/basic/basic-auth.d.ts +4 -0
  163. package/security/basic/basic-auth.js +32 -0
  164. package/security/basic/index.d.ts +1 -0
  165. package/security/basic/index.js +17 -0
  166. package/security/create-auth-resources.d.ts +6 -0
  167. package/security/create-auth-resources.js +129 -0
  168. package/security/helper.d.ts +127 -0
  169. package/security/helper.js +329 -0
  170. package/security/index.d.ts +4 -0
  171. package/security/index.js +20 -0
  172. package/security/jwt/index.d.ts +2 -0
  173. package/security/jwt/index.js +18 -0
  174. package/security/jwt/jwt-auth.d.ts +4 -0
  175. package/security/jwt/jwt-auth.js +57 -0
  176. package/security/jwt/jwt-keys.d.ts +7 -0
  177. package/security/jwt/jwt-keys.js +43 -0
  178. package/security/oauth2/create-oauth2-plugin.d.ts +17 -0
  179. package/security/oauth2/create-oauth2-plugin.js +85 -0
  180. package/security/oauth2/index.d.ts +3 -0
  181. package/security/oauth2/index.js +19 -0
  182. package/security/oauth2/oauth2-custom.d.ts +7 -0
  183. package/security/oauth2/oauth2-custom.js +40 -0
  184. package/security/oauth2/oauth2-facebook.d.ts +1 -0
  185. package/security/oauth2/oauth2-facebook.js +30 -0
  186. package/security/oauth2/oauth2-google.d.ts +1 -0
  187. package/security/oauth2/oauth2-google.js +28 -0
  188. package/security/oauth2/oauth2-schema.d.ts +10 -0
  189. package/security/oauth2/oauth2-schema.js +53 -0
  190. package/security/recaptcha/index.d.ts +2 -0
  191. package/security/recaptcha/index.js +18 -0
  192. package/security/recaptcha/recaptcha-verify.d.ts +1 -0
  193. package/security/recaptcha/recaptcha-verify.js +33 -0
  194. package/security/recaptcha/recaptcha.d.ts +2 -0
  195. package/security/recaptcha/recaptcha.js +22 -0
  196. package/security/resources/api-key/model.d.ts +2 -0
  197. package/security/resources/api-key/model.js +63 -0
  198. package/security/resources/api-key/policy.d.ts +2 -0
  199. package/security/resources/api-key/policy.js +26 -0
  200. package/security/resources/api-key/routes.d.ts +2 -0
  201. package/security/resources/api-key/routes.js +15 -0
  202. package/security/resources/api-key/service.d.ts +3 -0
  203. package/security/resources/api-key/service.js +33 -0
  204. package/security/resources/one-time-token/model.d.ts +2 -0
  205. package/security/resources/one-time-token/model.js +32 -0
  206. package/security/resources/permission/model.d.ts +2 -0
  207. package/security/resources/permission/model.js +16 -0
  208. package/security/resources/role/model.d.ts +2 -0
  209. package/security/resources/role/model.js +22 -0
  210. package/security/store/database-security-store.d.ts +5 -0
  211. package/security/store/database-security-store.js +51 -0
  212. package/security/store/redis-security-store.d.ts +5 -0
  213. package/security/store/redis-security-store.js +32 -0
  214. package/seeder/create-seeder.d.ts +21 -0
  215. package/seeder/create-seeder.js +17 -0
  216. package/seeder/index.d.ts +2 -0
  217. package/seeder/index.js +18 -0
  218. package/seeder/resources/seeder/model.d.ts +2 -0
  219. package/seeder/resources/seeder/model.js +38 -0
  220. package/seeder/seeder.d.ts +20 -0
  221. package/seeder/seeder.js +175 -0
  222. package/server/create-server.d.ts +20 -0
  223. package/server/create-server.js +160 -0
  224. package/server/index.d.ts +4 -0
  225. package/server/index.js +20 -0
  226. package/server/info-route.d.ts +2 -0
  227. package/server/info-route.js +18 -0
  228. package/server/info-schema.d.ts +37 -0
  229. package/server/info-schema.js +19 -0
  230. package/server/register-model.d.ts +2 -0
  231. package/server/register-model.js +12 -0
  232. package/server/register-plugin.d.ts +2 -0
  233. package/server/register-plugin.js +13 -0
  234. package/server/register-route.d.ts +3 -0
  235. package/server/register-route.js +74 -0
  236. package/server/schemas.d.ts +3 -0
  237. package/server/schemas.js +30 -0
  238. package/server/swagger.d.ts +3 -0
  239. package/server/swagger.js +122 -0
  240. package/storage/file-route.d.ts +2 -0
  241. package/storage/file-route.js +39 -0
  242. package/storage/file-schema.d.ts +9 -0
  243. package/storage/file-schema.js +42 -0
  244. package/storage/file-service.d.ts +81 -0
  245. package/storage/file-service.js +384 -0
  246. package/storage/filesystem-storage.d.ts +10 -0
  247. package/storage/filesystem-storage.js +128 -0
  248. package/storage/index.d.ts +2 -0
  249. package/storage/index.js +18 -0
  250. package/storage/resources/file/model.d.ts +2 -0
  251. package/storage/resources/file/model.js +75 -0
  252. package/types/application-context.d.ts +20 -0
  253. package/types/application-context.js +2 -0
  254. package/types/auth.d.ts +31 -0
  255. package/types/auth.js +2 -0
  256. package/types/fastify-extensions.d.ts +24 -0
  257. package/types/fastify-extensions.js +4 -0
  258. package/types/generated.d.ts +193 -0
  259. package/types/generated.js +3 -0
  260. package/types/index.d.ts +4 -0
  261. package/types/index.js +20 -0
  262. package/types/server.d.ts +4 -0
  263. package/types/server.js +2 -0
  264. package/utils/export-util.d.ts +8 -0
  265. package/utils/export-util.js +25 -0
  266. package/utils/file-util.d.ts +64 -0
  267. package/utils/file-util.js +141 -0
  268. package/utils/index.d.ts +3 -0
  269. package/utils/index.js +19 -0
  270. package/utils/schema-util.d.ts +20 -0
  271. package/utils/schema-util.js +37 -0
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createClient = createClient;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const common_1 = require("@appweaver/common");
9
+ const options = {
10
+ transactionOptions: {
11
+ maxWait: common_1.config.DATABASE_TRANSACTION_MAX_WAIT,
12
+ timeout: common_1.config.DATABASE_TRANSACTION_TIMEOUT
13
+ },
14
+ log: common_1.config.DATABASE_LOG_EVENTS.map((e) => ({ emit: 'event', level: e }))
15
+ };
16
+ /**
17
+ * Creates and returns a PrismaClient instance based on the configured database type.
18
+ *
19
+ * The database type is determined by the `DATABASE_TYPE` configuration value or,
20
+ * if unspecified, by parsing the `DATABASE_URL` configuration.
21
+ * Supported database types include SQLite, PostgresSQL, and MySQL.
22
+ *
23
+ * @return {PrismaClient} A PrismaClient instance configured for the selected database type.
24
+ */
25
+ function createClient() {
26
+ const dbType = (0, common_1.resolveDatabaseType)(common_1.config.DATABASE_TYPE, common_1.config.DATABASE_URL);
27
+ switch (dbType) {
28
+ case common_1.DatabaseType.Sqlite:
29
+ return sqliteClient();
30
+ case common_1.DatabaseType.PostgresSQL:
31
+ return postgresClient();
32
+ case common_1.DatabaseType.MySQL:
33
+ return mysqlClient();
34
+ case common_1.DatabaseType.SQLServer:
35
+ return sqlServerClient();
36
+ default:
37
+ return sqliteClient();
38
+ }
39
+ }
40
+ /**
41
+ * Initializes and returns an instance of the PrismaClient configured with a Better SQLite3 adapter.
42
+ *
43
+ * This method sets up a database connection using the PrismaBetterSqlite3 adapter with the provided
44
+ * database URL and additional options.
45
+ *
46
+ * @return {PrismaClient} A configured instance of PrismaClient for interacting with the SQLite database.
47
+ */
48
+ function sqliteClient() {
49
+ let sqliteAdapter;
50
+ if (common_1.config.APP_RUNTIME === common_1.Runtime.Bun) {
51
+ const { PrismaLibSql } = (0, common_1.requireModule)('@prisma/adapter-libsql', true).value;
52
+ sqliteAdapter = PrismaLibSql;
53
+ }
54
+ else {
55
+ const { PrismaBetterSqlite3 } = (0, common_1.requireModule)('@prisma/adapter-better-sqlite3', true).value;
56
+ sqliteAdapter = PrismaBetterSqlite3;
57
+ }
58
+ const adapter = new sqliteAdapter({
59
+ url: common_1.config.DATABASE_URL || 'file:./sqlite.db'
60
+ });
61
+ return createPrismaClient(adapter);
62
+ }
63
+ /**
64
+ * Creates and returns an instance of PrismaClient configured with the specified options.
65
+ *
66
+ * @return {PrismaClient} An instance of PrismaClient used to interact with a PostgresSQL database.
67
+ */
68
+ function postgresClient() {
69
+ const { PrismaPg } = (0, common_1.requireModule)('@prisma/adapter-pg', true).value;
70
+ const adapter = new PrismaPg({
71
+ connectionString: common_1.config.DATABASE_URL
72
+ });
73
+ return createPrismaClient(adapter);
74
+ }
75
+ /**
76
+ * Initializes and returns an instance of PrismaClient configured to use
77
+ * a MariaDB adapter with the specified database connection settings.
78
+ *
79
+ * @return {PrismaClient} A PrismaClient instance configured for MariaDB.
80
+ */
81
+ function mysqlClient() {
82
+ const { PrismaMariaDb } = (0, common_1.requireModule)('@prisma/adapter-mariadb', true).value;
83
+ const dbUrl = new URL(common_1.config.DATABASE_URL);
84
+ const adapter = new PrismaMariaDb({
85
+ host: dbUrl.hostname,
86
+ port: parseInt(dbUrl.port || '3306', 10),
87
+ user: decodeURIComponent(dbUrl.username),
88
+ password: decodeURIComponent(dbUrl.password),
89
+ database: dbUrl.pathname.slice(1)
90
+ });
91
+ return createPrismaClient(adapter);
92
+ }
93
+ /**
94
+ * Creates and returns a PrismaClient configured to connect to a SQL Server database.
95
+ *
96
+ * This method uses the Prisma MSSQL adapter with the connection string from config.
97
+ *
98
+ * @return {PrismaClient} An instance of PrismaClient for interacting with the SQL Server database.
99
+ */
100
+ function sqlServerClient() {
101
+ const { PrismaMssql } = (0, common_1.requireModule)('@prisma/adapter-mssql', true).value;
102
+ const adapter = new PrismaMssql(common_1.config.DATABASE_URL);
103
+ return createPrismaClient(adapter);
104
+ }
105
+ /**
106
+ * Creates and returns an instance of PrismaClient configured with the specified SQL driver adapter.
107
+ * The PrismaClient class is loaded from the configured output path relative to the root directory.
108
+ *
109
+ * @param {SqlDriverAdapterFactory} adapter - The SQL driver adapter factory used to configure the PrismaClient.
110
+ * @return {PrismaClient} A configured PrismaClient instance.
111
+ */
112
+ function createPrismaClient(adapter) {
113
+ const cwd = process.cwd();
114
+ const mainPath = require.main?.filename || process.argv[1];
115
+ const relativeMainPath = mainPath.replace(`${cwd}${node_path_1.default.sep}`, '');
116
+ const distDirName = relativeMainPath.includes('node_modules')
117
+ ? 'dist'
118
+ : relativeMainPath.split(node_path_1.default.sep)[0];
119
+ const buildDirPath = (0, common_1.isTypeScriptRuntime)()
120
+ ? ''
121
+ : common_1.config.APP_BUILD_PATH || distDirName;
122
+ const testDirPath = !(0, common_1.isTypeScriptRuntime)() && common_1.config.APP_ENV === 'test' ? '..' : '';
123
+ // Construct the Prisma client path supporting multiple different ways of running
124
+ // application (JavaScript runtime, TypeScript runtime, tests, from CLI, ...)
125
+ const clientPath = node_path_1.default.join(cwd, buildDirPath, testDirPath, common_1.config.DATABASE_CLIENT_OUTPUT_DIR_PATH, 'client');
126
+ const { PrismaClient } = (0, common_1.requireModule)(clientPath, true).value;
127
+ const client = new PrismaClient({ adapter, ...options });
128
+ // Add configured Prisma event logging
129
+ for (const event of common_1.config.DATABASE_LOG_EVENTS) {
130
+ if (event === common_1.DatabaseEvent.Query) {
131
+ client.$on(event, (e) => {
132
+ common_1.logger.debug(e, 'Prisma query');
133
+ });
134
+ }
135
+ else {
136
+ client.$on(event, (e) => {
137
+ common_1.logger[event](e, `Prisma ${event} log`);
138
+ });
139
+ }
140
+ }
141
+ return client;
142
+ }
@@ -0,0 +1 @@
1
+ export * from './prisma-database';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./prisma-database"), exports);
@@ -0,0 +1,15 @@
1
+ import { Database, HealthCheckResult } from '@appweaver/common';
2
+ import { PrismaClient } from '../prisma/client/client';
3
+ /**
4
+ * Represents a database utility class that provides methods
5
+ * to connect to and disconnect from the database, as well as
6
+ * access to the database Prisma client instance.
7
+ */
8
+ export declare class PrismaDatabase extends Database {
9
+ onInit(): Promise<void>;
10
+ onDestroy(): Promise<void>;
11
+ connect(): Promise<void>;
12
+ disconnect(): Promise<void>;
13
+ client<T = PrismaClient>(): T;
14
+ checkHealth(): Promise<HealthCheckResult>;
15
+ }
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PrismaDatabase = void 0;
4
+ const common_1 = require("@appweaver/common");
5
+ const create_client_1 = require("./create-client");
6
+ /**
7
+ * Represents a database utility class that provides methods
8
+ * to connect to and disconnect from the database, as well as
9
+ * access to the database Prisma client instance.
10
+ */
11
+ class PrismaDatabase extends common_1.Database {
12
+ /** @internal */
13
+ _client;
14
+ async onInit() {
15
+ await this.connect();
16
+ }
17
+ async onDestroy() {
18
+ await this.disconnect();
19
+ }
20
+ async connect() {
21
+ if (this._client) {
22
+ return;
23
+ }
24
+ await this.client().$connect();
25
+ }
26
+ async disconnect() {
27
+ if (!this._client) {
28
+ return;
29
+ }
30
+ await this.client().$disconnect();
31
+ this._client = undefined;
32
+ }
33
+ client() {
34
+ return this.clientInstance();
35
+ }
36
+ async checkHealth() {
37
+ try {
38
+ await this.client().$queryRaw `SELECT 1`;
39
+ return { success: true };
40
+ }
41
+ catch (e) {
42
+ return { success: false, message: e.message };
43
+ }
44
+ }
45
+ /** @internal */
46
+ clientInstance() {
47
+ if (!this._client) {
48
+ this._client = (0, create_client_1.createClient)();
49
+ }
50
+ return this._client;
51
+ }
52
+ }
53
+ exports.PrismaDatabase = PrismaDatabase;
@@ -0,0 +1,3 @@
1
+ import { FastifyError, FastifyReply, FastifyRequest } from 'fastify';
2
+ import { HttpError } from './http-error';
3
+ export declare function errorHandler(err: FastifyError | HttpError, request: FastifyRequest, reply: FastifyReply): void;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.errorHandler = errorHandler;
4
+ function errorHandler(err, request, reply) {
5
+ const { message, statusCode, error, errorCode } = err;
6
+ if (!statusCode || statusCode >= 500) {
7
+ if (!error) {
8
+ request.log.error(err.stack);
9
+ }
10
+ else {
11
+ request.log.error(error);
12
+ }
13
+ }
14
+ const errorResponse = {
15
+ errorCode: errorCode || statusCode || 500,
16
+ message: message || 'Unknown error'
17
+ };
18
+ const contentType = reply.getHeader('Content-Type');
19
+ reply
20
+ .status(statusCode || 500)
21
+ .send(contentType && contentType !== 'application/json'
22
+ ? errorResponse.message
23
+ : errorResponse);
24
+ }
@@ -0,0 +1,32 @@
1
+ export declare const ClientErrorResponse: import("@sinclair/typebox").TObject<{
2
+ errorCode: import("@sinclair/typebox").TInteger;
3
+ message: import("@sinclair/typebox").TString;
4
+ }>;
5
+ export declare const ServerErrorResponse: import("@sinclair/typebox").TObject<{
6
+ errorCode: import("@sinclair/typebox").TInteger;
7
+ message: import("@sinclair/typebox").TString;
8
+ }>;
9
+ export declare const AllErrorResponses: {
10
+ '4xx': {
11
+ description: string;
12
+ content: {
13
+ 'application/json': {
14
+ schema: import("@sinclair/typebox").TObject<{
15
+ errorCode: import("@sinclair/typebox").TInteger;
16
+ message: import("@sinclair/typebox").TString;
17
+ }>;
18
+ };
19
+ };
20
+ };
21
+ '5xx': {
22
+ description: string;
23
+ content: {
24
+ 'application/json': {
25
+ schema: import("@sinclair/typebox").TObject<{
26
+ errorCode: import("@sinclair/typebox").TInteger;
27
+ message: import("@sinclair/typebox").TString;
28
+ }>;
29
+ };
30
+ };
31
+ };
32
+ };
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AllErrorResponses = exports.ServerErrorResponse = exports.ClientErrorResponse = void 0;
4
+ const typebox_1 = require("@sinclair/typebox");
5
+ const utils_1 = require("../utils");
6
+ exports.ClientErrorResponse = typebox_1.Type.Object({
7
+ errorCode: typebox_1.Type.Integer({ example: 400 }),
8
+ message: typebox_1.Type.String({ example: 'Client error description' })
9
+ }, { $id: 'ClientErrorResponse' });
10
+ exports.ServerErrorResponse = typebox_1.Type.Object({
11
+ errorCode: typebox_1.Type.Integer({ example: 500 }),
12
+ message: typebox_1.Type.String({ example: 'Server error description' })
13
+ }, { $id: 'ServerErrorResponse' });
14
+ exports.AllErrorResponses = {
15
+ '4xx': {
16
+ description: 'Client error',
17
+ content: {
18
+ 'application/json': {
19
+ schema: (0, utils_1.createSchemaModel)(exports.ClientErrorResponse)
20
+ }
21
+ }
22
+ },
23
+ '5xx': {
24
+ description: 'Server error',
25
+ content: {
26
+ 'application/json': {
27
+ schema: (0, utils_1.createSchemaModel)(exports.ServerErrorResponse)
28
+ }
29
+ }
30
+ }
31
+ };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Represents an HTTP error with additional contextual information.
3
+ * Extends the built-in `Error` class by including an HTTP status code,
4
+ * an optional error detail, and an optional error code.
5
+ *
6
+ * The error message may include additional details if the application
7
+ * is not running in the production environment.
8
+ *
9
+ * @class
10
+ * @extends Error
11
+ * @param {string} text - The main error message.
12
+ * @param {number} [statusCode=400] - The HTTP status code associated with the error.
13
+ * @param {unknown} [error] - Optional additional error detail, such as an error object or metadata.
14
+ * @param {number} [errorCode] - Optional application-specific error code.
15
+ */
16
+ export declare class HttpError extends Error {
17
+ statusCode: number;
18
+ error?: unknown | undefined;
19
+ errorCode?: number | undefined;
20
+ constructor(text: string, statusCode?: number, error?: unknown | undefined, errorCode?: number | undefined);
21
+ }
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpError = void 0;
4
+ const common_1 = require("@appweaver/common");
5
+ /**
6
+ * Represents an HTTP error with additional contextual information.
7
+ * Extends the built-in `Error` class by including an HTTP status code,
8
+ * an optional error detail, and an optional error code.
9
+ *
10
+ * The error message may include additional details if the application
11
+ * is not running in the production environment.
12
+ *
13
+ * @class
14
+ * @extends Error
15
+ * @param {string} text - The main error message.
16
+ * @param {number} [statusCode=400] - The HTTP status code associated with the error.
17
+ * @param {unknown} [error] - Optional additional error detail, such as an error object or metadata.
18
+ * @param {number} [errorCode] - Optional application-specific error code.
19
+ */
20
+ class HttpError extends Error {
21
+ statusCode;
22
+ error;
23
+ errorCode;
24
+ constructor(text, statusCode = 400, error, errorCode) {
25
+ super(common_1.config.APP_ENV !== common_1.Environment.Production && error
26
+ ? ` ${text} (${(0, common_1.errorMessage)(error)})`
27
+ : text);
28
+ this.statusCode = statusCode;
29
+ this.error = error;
30
+ this.errorCode = errorCode;
31
+ }
32
+ }
33
+ exports.HttpError = HttpError;
@@ -0,0 +1,3 @@
1
+ export * from './error-handler';
2
+ export * from './error-schema';
3
+ export * from './http-error';
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./error-handler"), exports);
18
+ __exportStar(require("./error-schema"), exports);
19
+ __exportStar(require("./http-error"), exports);
@@ -0,0 +1,7 @@
1
+ import { ActionType, EventData, EventListener, Events } from '@appweaver/common';
2
+ export declare class NodeEvents extends Events {
3
+ constructor();
4
+ onResourceEvent<T>(resourceName: string, event: ActionType, listener: EventListener<T>): string;
5
+ emitResourceEvent<T>(resourceName: string, event: ActionType, data: EventData<T>): boolean;
6
+ removeResourceEvent(listenerId: string): boolean;
7
+ }
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NodeEvents = void 0;
4
+ const common_1 = require("@appweaver/common");
5
+ class NodeEvents extends common_1.Events {
6
+ /** @internal */
7
+ _eventListeners = {};
8
+ constructor() {
9
+ super({ captureRejections: true });
10
+ this.setMaxListeners(common_1.config.EVENTS_MAX_LISTENERS);
11
+ this.on('error', (e) => {
12
+ common_1.logger.error(e, 'Event handler error');
13
+ });
14
+ }
15
+ onResourceEvent(resourceName, event, listener) {
16
+ const listenerId = (0, common_1.uuid)();
17
+ const eventName = this.resourceEventName(resourceName, event);
18
+ this._eventListeners[listenerId] = { eventName, listener };
19
+ this.on(eventName, listener);
20
+ return listenerId;
21
+ }
22
+ emitResourceEvent(resourceName, event, data) {
23
+ return this.emit(this.resourceEventName(resourceName, event), data);
24
+ }
25
+ removeResourceEvent(listenerId) {
26
+ const listener = this._eventListeners[listenerId];
27
+ if (!listener) {
28
+ return false;
29
+ }
30
+ this.off(listener.eventName, listener.listener);
31
+ delete this._eventListeners[listenerId];
32
+ return true;
33
+ }
34
+ /** @internal */
35
+ resourceEventName(resourceName, event) {
36
+ return `${resourceName}.${event}`;
37
+ }
38
+ }
39
+ exports.NodeEvents = NodeEvents;
@@ -0,0 +1,19 @@
1
+ import { Readable } from 'node:stream';
2
+ export type ExportStream = {
3
+ stream: Readable;
4
+ fileName: string;
5
+ mimeType: string;
6
+ };
7
+ export declare class ExportService {
8
+ /**
9
+ * Exports data as a CSV stream based on the provided filter and sort parameters.
10
+ * The method retrieves the data in batches and streams it in CSV format.
11
+ *
12
+ * @param {string} modelName - The resource name for which to export data.
13
+ * @param {Object} [filter={}] - The filter conditions to apply when retrieving the data. Default is an empty object.
14
+ * @param {string} [sort='-createdAt,id'] - The sorting criteria for the data. Default is `-createdAt, id`.
15
+ * @return {Promise<ExportStream>} A promise resolving to the export stream object, which includes the readable
16
+ * stream, MIME type, and file name for the CSV.
17
+ */
18
+ exportCsv(modelName: string, filter?: any, sort?: string): Promise<ExportStream>;
19
+ }
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ExportService = void 0;
4
+ const node_stream_1 = require("node:stream");
5
+ const common_1 = require("@appweaver/common");
6
+ const context_1 = require("../context");
7
+ const errors_1 = require("../errors");
8
+ const utils_1 = require("../utils");
9
+ class ExportService {
10
+ /**
11
+ * Exports data as a CSV stream based on the provided filter and sort parameters.
12
+ * The method retrieves the data in batches and streams it in CSV format.
13
+ *
14
+ * @param {string} modelName - The resource name for which to export data.
15
+ * @param {Object} [filter={}] - The filter conditions to apply when retrieving the data. Default is an empty object.
16
+ * @param {string} [sort='-createdAt,id'] - The sorting criteria for the data. Default is `-createdAt, id`.
17
+ * @return {Promise<ExportStream>} A promise resolving to the export stream object, which includes the readable
18
+ * stream, MIME type, and file name for the CSV.
19
+ */
20
+ async exportCsv(modelName, filter = {}, sort = '-createdAt,id') {
21
+ const service = (0, context_1.injectService)(modelName);
22
+ let exportStream;
23
+ try {
24
+ // Initial query is also useful to expose any errors before stream start.
25
+ const checkResult = await service.query(filter, 1, 0, sort);
26
+ const totalCount = checkResult.totalCount;
27
+ const batchSize = common_1.config.EXPORT_BATCH_SIZE;
28
+ let page = 0;
29
+ const mapValues = (items) => this.mapProperties(modelName, items);
30
+ exportStream = new node_stream_1.Readable({
31
+ async read() {
32
+ page++;
33
+ try {
34
+ const result = await service.query(filter, page, batchSize, sort);
35
+ if (result.resultCount > 0) {
36
+ const data = mapValues(result.items);
37
+ this.push((0, utils_1.toCsv)(data, common_1.config.EXPORT_CSV_ADD_HEADERS ? page === 1 : false));
38
+ }
39
+ }
40
+ catch (e) {
41
+ common_1.logger.error(e, `${modelName} export error`);
42
+ this.push(null);
43
+ return;
44
+ }
45
+ if (page * batchSize >= totalCount) {
46
+ this.push(null);
47
+ }
48
+ }
49
+ });
50
+ if (common_1.config.EXPORT_CSV_ADD_SEP_ROW) {
51
+ exportStream.push(`SEP=${common_1.config.EXPORT_CSV_DELIMITER}\n`);
52
+ }
53
+ }
54
+ catch (e) {
55
+ throw new errors_1.HttpError(`${modelName} export error`, 500, e);
56
+ }
57
+ const fileName = this.generateExportFileName(modelName, 'csv');
58
+ common_1.logger.debug({ modelName, filter, fileName }, 'CSV File export');
59
+ return { stream: exportStream, mimeType: 'text/csv', fileName };
60
+ }
61
+ /** @internal */
62
+ mapProperties(resourceName, items) {
63
+ const properties = [];
64
+ for (const item of items) {
65
+ const property = this.mapProperty(resourceName, item);
66
+ properties.push(property);
67
+ }
68
+ return properties;
69
+ }
70
+ /** @internal */
71
+ mapProperty(resourceName, item, resourceExportConfig, parentKey = '') {
72
+ const resourceModel = (0, context_1.injectModel)(resourceName);
73
+ const readModel = resourceModel.readModel;
74
+ const relationsModel = resourceModel.relationsModel;
75
+ const filesModel = resourceModel.filesModel;
76
+ const exportConfig = resourceExportConfig ?? resourceModel.config.export;
77
+ const property = {};
78
+ for (const key in item) {
79
+ let value = item[key];
80
+ const modelSchema = (0, common_1.extractSchemaProperties)(readModel, key);
81
+ const relationSchema = (0, common_1.extractSchemaProperties)(relationsModel, key);
82
+ const fileSchema = (0, common_1.extractSchemaProperties)(filesModel, key);
83
+ if (!modelSchema &&
84
+ !relationSchema &&
85
+ !fileSchema &&
86
+ !(0, common_1.isCountField)(key)) {
87
+ // Skip mapping for non-exposed fields.
88
+ continue;
89
+ }
90
+ let header = parentKey ? `${parentKey}.${key}` : key;
91
+ const isArrayValue = (0, common_1.isArray)(value);
92
+ const exportField = exportConfig?.[key];
93
+ if (exportField) {
94
+ if (exportField.exclude === true) {
95
+ // Skip mapping for excluded fields.
96
+ continue;
97
+ }
98
+ if ((0, common_1.isString)(exportField.headerName)) {
99
+ header = parentKey
100
+ ? `${parentKey}.${exportField.headerName}`
101
+ : exportField.headerName;
102
+ }
103
+ if (exportField.mapValue) {
104
+ const mappedValues = [];
105
+ // Transform value items using mapValue configuration.
106
+ const subItems = isArrayValue ? value : [value];
107
+ for (const subItem of subItems) {
108
+ if ((0, common_1.isFunction)(exportField.mapValue)) {
109
+ try {
110
+ mappedValues.push(exportField.mapValue(subItem));
111
+ }
112
+ catch (e) {
113
+ mappedValues.push('');
114
+ common_1.logger.error(e, 'Export value mapping error.');
115
+ }
116
+ }
117
+ else if (!(0, common_1.isObject)(exportField.mapValue)) {
118
+ mappedValues.push(subItem?.[exportField.mapValue]);
119
+ }
120
+ }
121
+ value = mappedValues.join(',');
122
+ }
123
+ }
124
+ // Recursively map relation and file fields if the value is an object.
125
+ if ((value && (0, common_1.isObject)(value)) || (isArrayValue && (0, common_1.isObject)(value[0]))) {
126
+ const relationName = (0, common_1.extractResourceName)(relationSchema ?? fileSchema);
127
+ if (!relationName) {
128
+ continue;
129
+ }
130
+ const subItems = isArrayValue ? value : [value];
131
+ for (const subItem of subItems) {
132
+ const mappedItem = this.mapProperty(relationName, subItem, exportField, header);
133
+ for (const subKey in mappedItem) {
134
+ if (subKey in property) {
135
+ property[subKey] = [property[subKey], mappedItem[subKey]].join(common_1.config.EXPORT_CSV_JOIN_DELIMITER);
136
+ }
137
+ else {
138
+ property[subKey] = mappedItem[subKey];
139
+ }
140
+ }
141
+ }
142
+ }
143
+ else {
144
+ property[header] = value;
145
+ }
146
+ }
147
+ return property;
148
+ }
149
+ /** @internal */
150
+ generateExportFileName(modelName, extension) {
151
+ return (0, utils_1.generateFileName)(`${(0, common_1.plural)(modelName)}.${extension}`, '{name}_{year}{month}{day}_{hours}{minutes}{seconds}.{extension}');
152
+ }
153
+ }
154
+ exports.ExportService = ExportService;
@@ -0,0 +1 @@
1
+ export * from './export-service';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./export-service"), exports);
@@ -0,0 +1,2 @@
1
+ import { ResourceModel, ResourceModelConfig } from '@appweaver/common';
2
+ export declare function createModel(config: ResourceModelConfig, override?: boolean): ResourceModel;