@africode/core 5.0.10 → 5.0.13

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 (222) hide show
  1. package/AGENTS.md +585 -585
  2. package/AGENT_INSTRUCTIONS.md +595 -595
  3. package/COMPONENT_SCHEMA.json +1826 -1800
  4. package/LICENSE +623 -623
  5. package/README.md +476 -476
  6. package/bin/africode.js +73 -73
  7. package/bin/cli.ts +82 -82
  8. package/bin/create-africode.js +220 -220
  9. package/bin/scaffold.ts +218 -218
  10. package/components/accordion.js +183 -183
  11. package/components/alert.js +131 -131
  12. package/components/auth-form.js +154 -154
  13. package/components/auth.js +172 -172
  14. package/components/avatar.js +117 -117
  15. package/components/badge.js +104 -104
  16. package/components/base.d.ts +139 -139
  17. package/components/base.js +234 -234
  18. package/components/breadcrumb.js +76 -72
  19. package/components/button.js +164 -164
  20. package/components/card.js +144 -137
  21. package/components/carousel.js +32 -32
  22. package/components/cart-drawer.js +28 -28
  23. package/components/code-block.js +20 -20
  24. package/components/contact-form.js +25 -25
  25. package/components/cookie-consent.js +23 -23
  26. package/components/cta-banner.js +38 -38
  27. package/components/cultural-card.js +243 -243
  28. package/components/dashboard-activity-list.js +103 -103
  29. package/components/dashboard-card.js +85 -85
  30. package/components/dashboard-metric.js +81 -81
  31. package/components/dashboard-shell.js +85 -85
  32. package/components/dashboard-topbar.js +84 -84
  33. package/components/divider.js +83 -83
  34. package/components/dropdown.js +171 -171
  35. package/components/error-boundary.js +155 -155
  36. package/components/faq-accordion.js +23 -23
  37. package/components/feature-grid.js +85 -85
  38. package/components/file-uploader.js +22 -22
  39. package/components/filter-bar.js +19 -19
  40. package/components/footer.js +113 -113
  41. package/components/form.js +131 -131
  42. package/components/gallery.js +22 -22
  43. package/components/hero.js +140 -138
  44. package/components/icon.js +36 -36
  45. package/components/index.js +128 -128
  46. package/components/input.js +252 -256
  47. package/components/kanga-card.js +185 -185
  48. package/components/kyc-upload.js +173 -173
  49. package/components/language-switcher.js +108 -108
  50. package/components/loader.js +80 -80
  51. package/components/modal.js +262 -262
  52. package/components/motion.js +84 -84
  53. package/components/nav-drawer.js +216 -216
  54. package/components/navbar.js +243 -236
  55. package/components/newsletter-signup.js +24 -24
  56. package/components/pagination.js +31 -31
  57. package/components/pattern-showcase.js +225 -225
  58. package/components/pricing-card.js +100 -100
  59. package/components/product-card.js +41 -41
  60. package/components/progress.js +132 -134
  61. package/components/react.js +111 -111
  62. package/components/search-box.js +24 -24
  63. package/components/section.js +54 -54
  64. package/components/select.js +321 -322
  65. package/components/sidebar.js +180 -180
  66. package/components/simple-chart.js +22 -22
  67. package/components/skeleton.js +85 -85
  68. package/components/stepper.js +28 -28
  69. package/components/table.js +181 -181
  70. package/components/tabs.js +202 -202
  71. package/components/team-grid.js +23 -23
  72. package/components/testimonial.js +94 -94
  73. package/components/theme-toggle.js +82 -82
  74. package/components/toast.js +139 -139
  75. package/components/tooltip.js +167 -167
  76. package/components/transaction-ledger.js +138 -138
  77. package/components/ui-avatar.js +79 -79
  78. package/components/ui-badge.js +61 -61
  79. package/components/ui-button.js +149 -149
  80. package/components/ui-card.js +74 -75
  81. package/components/ui-chip.js +87 -87
  82. package/components/ui-input.js +110 -110
  83. package/components/ui-popover.js +84 -84
  84. package/components/ui-progress-ring.js +60 -60
  85. package/components/ui-select.js +85 -85
  86. package/components/ui-stat.js +75 -75
  87. package/components/ui-switch.js +85 -85
  88. package/components/ui-table.js +69 -69
  89. package/components/ui-tabs.js +99 -99
  90. package/components/ui-tag.js +64 -64
  91. package/components/ui-textarea.js +84 -84
  92. package/components/ui-tooltip.js +66 -66
  93. package/components/video-player.js +22 -22
  94. package/components/wallet-balance.js +114 -114
  95. package/core/a2ui-schema-manager.js +351 -351
  96. package/core/a2ui.js +696 -696
  97. package/core/actions.js +27 -27
  98. package/core/bun-runtime.js +398 -397
  99. package/core/cli/commands/add.js +23 -23
  100. package/core/cli/commands/audit.js +58 -58
  101. package/core/cli/commands/build.js +193 -193
  102. package/core/cli/commands/create-plugin.js +241 -241
  103. package/core/cli/commands/dev.js +252 -285
  104. package/core/cli/commands/lint.js +23 -23
  105. package/core/cli/commands/test.js +33 -34
  106. package/core/cli/migrator.js +71 -71
  107. package/core/cli/ui.js +56 -56
  108. package/core/compliance.js +823 -823
  109. package/core/config.js +265 -265
  110. package/core/db-advanced.js +478 -481
  111. package/core/db.js +282 -284
  112. package/core/enhanced-hmr.js +406 -406
  113. package/core/errors.js +222 -222
  114. package/core/file-router.js +52 -50
  115. package/core/hmr-client.js +203 -204
  116. package/core/hmr.js +205 -197
  117. package/core/html.d.ts +30 -30
  118. package/core/html.js +84 -84
  119. package/core/hydration.js +52 -52
  120. package/core/lipa-namba-journey.js +548 -605
  121. package/core/logging.js +14 -14
  122. package/core/middleware.js +145 -145
  123. package/core/motion.js +106 -106
  124. package/core/nida-cig-middleware.js +417 -460
  125. package/core/patterns.d.ts +124 -124
  126. package/core/patterns.js +947 -1001
  127. package/core/plugins/index.js +345 -345
  128. package/core/request-analytics.js +253 -253
  129. package/core/request-identity.js +93 -93
  130. package/core/router.js +386 -386
  131. package/core/sdk-browser.js +140 -140
  132. package/core/sdk-client.js +61 -61
  133. package/core/sdk.d.ts +133 -133
  134. package/core/sdk.js +148 -148
  135. package/core/seo.js +76 -76
  136. package/core/server/auth-endpoints.js +339 -339
  137. package/core/server/auth.js +180 -180
  138. package/core/server/csrf.js +200 -206
  139. package/core/server/db.js +39 -39
  140. package/core/server/middleware.js +324 -324
  141. package/core/server/rate-limit.js +238 -238
  142. package/core/server/render.js +67 -69
  143. package/core/server/router.js +102 -120
  144. package/core/session-store.js +68 -68
  145. package/core/shim.js +28 -28
  146. package/core/state.d.ts +86 -86
  147. package/core/state.js +276 -276
  148. package/core/store.d.ts +122 -122
  149. package/core/store.js +61 -61
  150. package/core/validation.d.ts +232 -232
  151. package/core/validation.js +602 -602
  152. package/core/websocket.js +656 -641
  153. package/dist/africode.js +233 -230
  154. package/dist/africode.js.map +83 -83
  155. package/dist/build-info.json +3 -3
  156. package/dist/components.js +195 -192
  157. package/dist/components.js.map +73 -73
  158. package/dist/styles/africanity.css +321 -321
  159. package/dist/styles/typography.css +140 -140
  160. package/docs/IDE-Guide.md +50 -50
  161. package/package.json +113 -113
  162. package/scripts/generate-component-schema.js +82 -79
  163. package/styles/africanity.css +321 -321
  164. package/styles/typography.css +140 -140
  165. package/templates/starter/.env.example +15 -15
  166. package/templates/starter/africode.config.js +40 -40
  167. package/templates/starter/package.json +13 -13
  168. package/templates/starter/src/index.js +18 -18
  169. package/templates/starter/src/pages/index.html +55 -55
  170. package/templates/starter/src/pages/index.js +17 -17
  171. package/templates/starter/src/styles/main.css +3 -3
  172. package/templates/starter-3d/.env.example +7 -7
  173. package/templates/starter-3d/africode.config.js +29 -29
  174. package/templates/starter-3d/components/af-model-viewer.js +125 -125
  175. package/templates/starter-3d/package.json +14 -14
  176. package/templates/starter-3d/src/pages/index.html +55 -55
  177. package/templates/starter-3d/src/pages/index.js +50 -50
  178. package/templates/starter-3d/src/styles/main.css +3 -3
  179. package/templates/starter-dashboard/.env.example +21 -21
  180. package/templates/starter-dashboard/africode.config.js +20 -20
  181. package/templates/starter-dashboard/package.json +14 -14
  182. package/templates/starter-dashboard/src/index.js +17 -17
  183. package/templates/starter-dashboard/src/pages/api/analytics.js +24 -24
  184. package/templates/starter-dashboard/src/pages/index.html +118 -118
  185. package/templates/starter-dashboard/src/pages/index.js +110 -110
  186. package/templates/starter-dashboard/src/styles/main.css +172 -172
  187. package/templates/starter-fintech/.env.example +28 -28
  188. package/templates/starter-fintech/africode.config.js +20 -20
  189. package/templates/starter-fintech/package.json +15 -15
  190. package/templates/starter-fintech/src/index.js +17 -17
  191. package/templates/starter-fintech/src/pages/api/auth.js +45 -45
  192. package/templates/starter-fintech/src/pages/api/dashboard.js +19 -0
  193. package/templates/starter-fintech/src/pages/api/transfer.js +65 -65
  194. package/templates/starter-fintech/src/pages/api/wallet.js +39 -39
  195. package/templates/starter-fintech/src/pages/api/webhooks/payment.js +32 -32
  196. package/templates/starter-fintech/src/pages/index.html +169 -169
  197. package/templates/starter-fintech/src/pages/index.js +161 -161
  198. package/templates/starter-fintech/src/styles/main.css +246 -246
  199. package/templates/starter-react/.env.example +15 -15
  200. package/templates/starter-react/africode.config.js +40 -40
  201. package/templates/starter-react/package.json +15 -15
  202. package/templates/starter-react/src/pages/index.html +55 -55
  203. package/templates/starter-react/src/pages/index.js +68 -68
  204. package/templates/starter-react/src/styles/main.css +3 -3
  205. package/templates/starter-tailwind/.env.example +15 -15
  206. package/templates/starter-tailwind/africode.config.js +40 -40
  207. package/templates/starter-tailwind/package.json +19 -19
  208. package/templates/starter-tailwind/src/pages/index.html +55 -55
  209. package/templates/starter-tailwind/src/pages/index.js +67 -67
  210. package/templates/starter-tailwind/src/styles/main.css +3 -3
  211. package/templates/starter-tailwind/src/styles/tailwind.css +1 -1
  212. package/templates/starter-tailwind/src/tailwind-loader.js +30 -30
  213. package/templates/starter-tailwind/tailwind.config.cjs +18 -18
  214. package/templates/starter-website/.env.example +18 -18
  215. package/templates/starter-website/africode.config.js +20 -20
  216. package/templates/starter-website/package.json +14 -14
  217. package/templates/starter-website/src/index.js +17 -17
  218. package/templates/starter-website/src/pages/index.html +124 -124
  219. package/templates/starter-website/src/pages/index.js +116 -116
  220. package/templates/starter-website/src/styles/main.css +195 -195
  221. package/bin/africode.js.1758507140 +0 -343
  222. package/core/heartbeat.js +0 -64
@@ -1,481 +1,478 @@
1
- /**
2
- * AfriCode Advanced ORM
3
- * Query builder, relationships, transactions, and migrations
4
- *
5
- * Features:
6
- * - Fluent query builder (.where, .select, .join, .orderBy, .limit)
7
- * - Relationship definitions (.hasMany, .belongsTo)
8
- * - Transaction support for ACID operations
9
- * - Migration runner for schema versioning
10
- */
11
-
12
- import { Database } from 'bun:sqlite';
13
- import { query as dbQuery, get as dbGet, run as dbRun } from './db.js';
14
-
15
- /**
16
- * Query Builder
17
- * Fluent interface for building SQL queries
18
- */
19
- export class QueryBuilder {
20
- constructor(table, db = null) {
21
- this.table = table;
22
- this.db = db;
23
- this.selectFields = ['*'];
24
- this.whereConditions = [];
25
- this.joinClauses = [];
26
- this.orderByClause = null;
27
- this.limitClause = null;
28
- this.offsetClause = null;
29
- this.bindings = [];
30
- }
31
-
32
- /**
33
- * Select specific columns
34
- */
35
- select(...fields) {
36
- this.selectFields = fields.length > 0 ? fields : ['*'];
37
- return this;
38
- }
39
-
40
- /**
41
- * Add WHERE condition
42
- */
43
- where(field, operator, value = undefined) {
44
- if (value === undefined) {
45
- // where(field, value) syntax
46
- value = operator;
47
- operator = '=';
48
- }
49
-
50
- this.whereConditions.push({ field, operator, value });
51
- this.bindings.push(value);
52
- return this;
53
- }
54
-
55
- /**
56
- * Add OR WHERE condition
57
- */
58
- orWhere(field, operator, value = undefined) {
59
- if (value === undefined) {
60
- value = operator;
61
- operator = '=';
62
- }
63
-
64
- this.whereConditions.push({ field, operator, value, or: true });
65
- this.bindings.push(value);
66
- return this;
67
- }
68
-
69
- /**
70
- * Add JOIN clause
71
- */
72
- join(table, field1, operator, field2) {
73
- this.joinClauses.push({ table, field1, operator, field2, type: 'INNER' });
74
- return this;
75
- }
76
-
77
- /**
78
- * Add LEFT JOIN clause
79
- */
80
- leftJoin(table, field1, operator, field2) {
81
- this.joinClauses.push({ table, field1, operator, field2, type: 'LEFT' });
82
- return this;
83
- }
84
-
85
- /**
86
- * Order by column
87
- */
88
- orderBy(field, direction = 'ASC') {
89
- this.orderByClause = `${field} ${direction}`;
90
- return this;
91
- }
92
-
93
- /**
94
- * Limit results
95
- */
96
- limit(count) {
97
- this.limitClause = count;
98
- return this;
99
- }
100
-
101
- /**
102
- * Offset results
103
- */
104
- offset(count) {
105
- this.offsetClause = count;
106
- return this;
107
- }
108
-
109
- /**
110
- * Build SQL query
111
- */
112
- build() {
113
- let sql = `SELECT ${this.selectFields.join(', ')} FROM ${this.table}`;
114
-
115
- // Add JOINs
116
- for (const join of this.joinClauses) {
117
- sql += ` ${join.type} JOIN ${join.table} ON ${join.field1} ${join.operator} ${join.field2}`;
118
- }
119
-
120
- // Add WHERE conditions
121
- if (this.whereConditions.length > 0) {
122
- const conditions = this.whereConditions.map((cond, idx) => {
123
- const prefix = idx > 0 && cond.or ? 'OR' : idx > 0 ? 'AND' : '';
124
- return `${prefix} ${cond.field} ${cond.operator} ?`.trim();
125
- });
126
- sql += ` WHERE ${conditions.join(' ')}`;
127
- }
128
-
129
- // Add ORDER BY
130
- if (this.orderByClause) {
131
- sql += ` ORDER BY ${this.orderByClause}`;
132
- }
133
-
134
- // Add LIMIT
135
- if (this.limitClause !== null) {
136
- sql += ` LIMIT ${this.limitClause}`;
137
- }
138
-
139
- // Add OFFSET
140
- if (this.offsetClause !== null) {
141
- sql += ` OFFSET ${this.offsetClause}`;
142
- }
143
-
144
- return { sql, bindings: this.bindings };
145
- }
146
-
147
- /**
148
- * Execute query and get all results
149
- */
150
- all() {
151
- const { sql, bindings } = this.build();
152
- return dbQuery(sql, bindings);
153
- }
154
-
155
- /**
156
- * Execute query and get first result
157
- */
158
- first() {
159
- const { sql, bindings } = this.build();
160
- return dbGet(sql, bindings);
161
- }
162
-
163
- /**
164
- * Execute query and get count
165
- */
166
- count() {
167
- const originalSelect = this.selectFields;
168
- this.selectFields = ['COUNT(*) as count'];
169
- const result = this.first();
170
- this.selectFields = originalSelect;
171
- return result?.count || 0;
172
- }
173
-
174
- /**
175
- * Get SQL and bindings without executing
176
- */
177
- toSql() {
178
- return this.build();
179
- }
180
- }
181
-
182
- /**
183
- * Model Base Class
184
- * Provides common ORM functionality
185
- */
186
- export class Model {
187
- constructor(data = {}) {
188
- this.data = data;
189
- this.relationships = {};
190
- this.isDirty = false;
191
- }
192
-
193
- /**
194
- * Define hasMany relationship
195
- */
196
- static hasMany(relationName, foreignModel, foreignKey, localKey = 'id') {
197
- return function() {
198
- const localValue = this.data[localKey];
199
- if (!localValue) return [];
200
- const related = new foreignModel();
201
- return new QueryBuilder(foreignModel.tableName)
202
- .where(foreignKey, localValue)
203
- .all();
204
- };
205
- }
206
-
207
- /**
208
- * Define belongsTo relationship
209
- */
210
- static belongsTo(relationName, parentModel, foreignKey, parentKey = 'id') {
211
- return function() {
212
- const foreignValue = this.data[foreignKey];
213
- if (!foreignValue) return null;
214
- const parent = new parentModel();
215
- return new QueryBuilder(parentModel.tableName)
216
- .where(parentKey, foreignValue)
217
- .first();
218
- };
219
- }
220
-
221
- /**
222
- * Get a relationship
223
- */
224
- getRelation(name) {
225
- if (!this.relationships[name]) {
226
- throw new Error(`Relationship "${name}" not defined on model`);
227
- }
228
- return this.relationships[name].call(this);
229
- }
230
-
231
- /**
232
- * Query builder for this model
233
- */
234
- static query() {
235
- return new QueryBuilder(this.tableName);
236
- }
237
-
238
- /**
239
- * Find by ID
240
- */
241
- static findById(id) {
242
- return new QueryBuilder(this.tableName)
243
- .where('id', id)
244
- .first();
245
- }
246
-
247
- /**
248
- * Find all
249
- */
250
- static all() {
251
- return new QueryBuilder(this.tableName).all();
252
- }
253
-
254
- /**
255
- * Create new record
256
- */
257
- static create(data) {
258
- const fields = Object.keys(data);
259
- const values = Object.values(data);
260
- const placeholders = fields.map(() => '?').join(', ');
261
-
262
- const sql = `INSERT INTO ${this.tableName} (${fields.join(', ')}) VALUES (${placeholders})`;
263
- const result = dbRun(sql, values);
264
-
265
- return { id: result.lastInsertRowid, ...data };
266
- }
267
-
268
- /**
269
- * Update record
270
- */
271
- static update(id, data) {
272
- const fields = Object.keys(data);
273
- const values = Object.values(data);
274
- const setClause = fields.map(f => `${f} = ?`).join(', ');
275
-
276
- const sql = `UPDATE ${this.tableName} SET ${setClause}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`;
277
- return dbRun(sql, [...values, id]);
278
- }
279
-
280
- /**
281
- * Delete record
282
- */
283
- static delete(id) {
284
- const sql = `DELETE FROM ${this.tableName} WHERE id = ?`;
285
- return dbRun(sql, [id]);
286
- }
287
- }
288
-
289
- /**
290
- * Transaction Support
291
- * Provides ACID-compliant multi-step operations
292
- * Note: SQLite auto-manages transactions in WAL mode, so we batch operations
293
- */
294
- export class Transaction {
295
- constructor(db) {
296
- this.db = db;
297
- this.isActive = false;
298
- this.operations = [];
299
- }
300
-
301
- /**
302
- * Begin transaction (queues operations)
303
- */
304
- begin() {
305
- this.isActive = true;
306
- this.operations = [];
307
- return this;
308
- }
309
-
310
- /**
311
- * Add operation to transaction
312
- */
313
- addOperation(sql, bindings = []) {
314
- if (!this.isActive) {
315
- throw new Error('Transaction not active');
316
- }
317
- this.operations.push({ sql, bindings });
318
- return this;
319
- }
320
-
321
- /**
322
- * Commit transaction (executes all operations)
323
- */
324
- commit() {
325
- if (!this.isActive) {
326
- throw new Error('No active transaction');
327
- }
328
-
329
- try {
330
- // Execute all operations
331
- for (const op of this.operations) {
332
- dbRun(op.sql, op.bindings);
333
- }
334
- this.isActive = false;
335
- this.operations = [];
336
- return true;
337
- } catch (error) {
338
- this.rollback();
339
- throw error;
340
- }
341
- }
342
-
343
- /**
344
- * Rollback transaction (clear operations)
345
- */
346
- rollback() {
347
- if (this.isActive) {
348
- this.isActive = false;
349
- this.operations = [];
350
- }
351
- }
352
- }
353
-
354
- /**
355
- * Migration Runner
356
- * Handles schema versioning and migrations
357
- */
358
- export class MigrationRunner {
359
- constructor(db) {
360
- this.db = db;
361
- this.migrationsPath = new URL('../migrations', import.meta.url).pathname;
362
- this.initMigrationsTable();
363
- }
364
-
365
- /**
366
- * Initialize migrations tracking table
367
- */
368
- initMigrationsTable() {
369
- const sql = `
370
- CREATE TABLE IF NOT EXISTS migrations (
371
- id INTEGER PRIMARY KEY AUTOINCREMENT,
372
- name TEXT UNIQUE NOT NULL,
373
- executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
374
- )
375
- `;
376
- dbRun(sql);
377
- }
378
-
379
- /**
380
- * Get list of executed migrations
381
- */
382
- getExecutedMigrations() {
383
- const sql = 'SELECT name FROM migrations ORDER BY executed_at ASC';
384
- const results = dbQuery(sql);
385
- return results.map(r => r.name);
386
- }
387
-
388
- /**
389
- * Get list of pending migrations
390
- */
391
- async getPendingMigrations() {
392
- const executed = this.getExecutedMigrations();
393
- const migrationsDir = Bun.file(this.migrationsPath);
394
-
395
- if (!migrationsDir.exists) {
396
- return [];
397
- }
398
-
399
- const allMigrations = [];
400
- // In a real implementation, this would scan the migrations directory
401
- return allMigrations.filter(m => !executed.includes(m));
402
- }
403
-
404
- /**
405
- * Run a single migration
406
- */
407
- runMigration(name, migrationSQL) {
408
- try {
409
- // Execute migration SQL
410
- if (migrationSQL && migrationSQL.trim()) {
411
- dbRun(migrationSQL);
412
- }
413
- // Record migration
414
- dbRun(
415
- 'INSERT INTO migrations (name) VALUES (?)',
416
- [name]
417
- );
418
- return true;
419
- } catch (error) {
420
- throw new Error(`Migration ${name} failed: ${error.message}`);
421
- }
422
- }
423
-
424
- /**
425
- * Rollback last migration
426
- */
427
- rollbackMigration(name) {
428
- const sql = 'DELETE FROM migrations WHERE name = ?';
429
- dbRun(sql, [name]);
430
- }
431
-
432
- /**
433
- * Run all pending migrations
434
- */
435
- async runPending() {
436
- const pending = await this.getPendingMigrations();
437
- const results = [];
438
-
439
- for (const migration of pending) {
440
- try {
441
- this.runMigration(migration, ''); // SQL would come from file
442
- results.push({ name: migration, status: 'success' });
443
- } catch (error) {
444
- results.push({ name: migration, status: 'failed', error: error.message });
445
- }
446
- }
447
-
448
- return results;
449
- }
450
- }
451
-
452
- /**
453
- * Define model relationships dynamically
454
- */
455
- export function defineRelationships(Model, relationships) {
456
- for (const [name, definition] of Object.entries(relationships)) {
457
- if (definition.type === 'hasMany') {
458
- Model.prototype[name] = Model.hasMany(
459
- name,
460
- definition.model,
461
- definition.foreignKey,
462
- definition.localKey
463
- );
464
- } else if (definition.type === 'belongsTo') {
465
- Model.prototype[name] = Model.belongsTo(
466
- name,
467
- definition.model,
468
- definition.foreignKey,
469
- definition.parentKey
470
- );
471
- }
472
- }
473
- }
474
-
475
- export default {
476
- QueryBuilder,
477
- Model,
478
- Transaction,
479
- MigrationRunner,
480
- defineRelationships
481
- };
1
+ /**
2
+ * AfriCode Advanced ORM
3
+ * Query builder, relationships, transactions, and migrations
4
+ *
5
+ * Features:
6
+ * - Fluent query builder (.where, .select, .join, .orderBy, .limit)
7
+ * - Relationship definitions (.hasMany, .belongsTo)
8
+ * - Transaction support for ACID operations
9
+ * - Migration runner for schema versioning
10
+ */
11
+
12
+ import { query as dbQuery, get as dbGet, run as dbRun } from './db.js';
13
+
14
+ /**
15
+ * Query Builder
16
+ * Fluent interface for building SQL queries
17
+ */
18
+ export class QueryBuilder {
19
+ constructor(table, db = null) {
20
+ this.table = table;
21
+ this.db = db;
22
+ this.selectFields = ['*'];
23
+ this.whereConditions = [];
24
+ this.joinClauses = [];
25
+ this.orderByClause = null;
26
+ this.limitClause = null;
27
+ this.offsetClause = null;
28
+ this.bindings = [];
29
+ }
30
+
31
+ /**
32
+ * Select specific columns
33
+ */
34
+ select(...fields) {
35
+ this.selectFields = fields.length > 0 ? fields : ['*'];
36
+ return this;
37
+ }
38
+
39
+ /**
40
+ * Add WHERE condition
41
+ */
42
+ where(field, operator, value = undefined) {
43
+ if (value === undefined) {
44
+ // where(field, value) syntax
45
+ value = operator;
46
+ operator = '=';
47
+ }
48
+
49
+ this.whereConditions.push({ field, operator, value });
50
+ this.bindings.push(value);
51
+ return this;
52
+ }
53
+
54
+ /**
55
+ * Add OR WHERE condition
56
+ */
57
+ orWhere(field, operator, value = undefined) {
58
+ if (value === undefined) {
59
+ value = operator;
60
+ operator = '=';
61
+ }
62
+
63
+ this.whereConditions.push({ field, operator, value, or: true });
64
+ this.bindings.push(value);
65
+ return this;
66
+ }
67
+
68
+ /**
69
+ * Add JOIN clause
70
+ */
71
+ join(table, field1, operator, field2) {
72
+ this.joinClauses.push({ table, field1, operator, field2, type: 'INNER' });
73
+ return this;
74
+ }
75
+
76
+ /**
77
+ * Add LEFT JOIN clause
78
+ */
79
+ leftJoin(table, field1, operator, field2) {
80
+ this.joinClauses.push({ table, field1, operator, field2, type: 'LEFT' });
81
+ return this;
82
+ }
83
+
84
+ /**
85
+ * Order by column
86
+ */
87
+ orderBy(field, direction = 'ASC') {
88
+ this.orderByClause = `${field} ${direction}`;
89
+ return this;
90
+ }
91
+
92
+ /**
93
+ * Limit results
94
+ */
95
+ limit(count) {
96
+ this.limitClause = count;
97
+ return this;
98
+ }
99
+
100
+ /**
101
+ * Offset results
102
+ */
103
+ offset(count) {
104
+ this.offsetClause = count;
105
+ return this;
106
+ }
107
+
108
+ /**
109
+ * Build SQL query
110
+ */
111
+ build() {
112
+ let sql = `SELECT ${this.selectFields.join(', ')} FROM ${this.table}`;
113
+
114
+ // Add JOINs
115
+ for (const join of this.joinClauses) {
116
+ sql += ` ${join.type} JOIN ${join.table} ON ${join.field1} ${join.operator} ${join.field2}`;
117
+ }
118
+
119
+ // Add WHERE conditions
120
+ if (this.whereConditions.length > 0) {
121
+ const conditions = this.whereConditions.map((cond, idx) => {
122
+ const prefix = idx > 0 && cond.or ? 'OR' : idx > 0 ? 'AND' : '';
123
+ return `${prefix} ${cond.field} ${cond.operator} ?`.trim();
124
+ });
125
+ sql += ` WHERE ${conditions.join(' ')}`;
126
+ }
127
+
128
+ // Add ORDER BY
129
+ if (this.orderByClause) {
130
+ sql += ` ORDER BY ${this.orderByClause}`;
131
+ }
132
+
133
+ // Add LIMIT
134
+ if (this.limitClause !== null) {
135
+ sql += ` LIMIT ${this.limitClause}`;
136
+ }
137
+
138
+ // Add OFFSET
139
+ if (this.offsetClause !== null) {
140
+ sql += ` OFFSET ${this.offsetClause}`;
141
+ }
142
+
143
+ return { sql, bindings: this.bindings };
144
+ }
145
+
146
+ /**
147
+ * Execute query and get all results
148
+ */
149
+ all() {
150
+ const { sql, bindings } = this.build();
151
+ return dbQuery(sql, bindings);
152
+ }
153
+
154
+ /**
155
+ * Execute query and get first result
156
+ */
157
+ first() {
158
+ const { sql, bindings } = this.build();
159
+ return dbGet(sql, bindings);
160
+ }
161
+
162
+ /**
163
+ * Execute query and get count
164
+ */
165
+ count() {
166
+ const originalSelect = this.selectFields;
167
+ this.selectFields = ['COUNT(*) as count'];
168
+ const result = this.first();
169
+ this.selectFields = originalSelect;
170
+ return result?.count || 0;
171
+ }
172
+
173
+ /**
174
+ * Get SQL and bindings without executing
175
+ */
176
+ toSql() {
177
+ return this.build();
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Model Base Class
183
+ * Provides common ORM functionality
184
+ */
185
+ export class Model {
186
+ constructor(data = {}) {
187
+ this.data = data;
188
+ this.relationships = {};
189
+ this.isDirty = false;
190
+ }
191
+
192
+ /**
193
+ * Define hasMany relationship
194
+ */
195
+ static hasMany(relationName, foreignModel, foreignKey, localKey = 'id') {
196
+ return function() {
197
+ const localValue = this.data[localKey];
198
+ if (!localValue) {return [];}
199
+ return new QueryBuilder(foreignModel.tableName)
200
+ .where(foreignKey, localValue)
201
+ .all();
202
+ };
203
+ }
204
+
205
+ /**
206
+ * Define belongsTo relationship
207
+ */
208
+ static belongsTo(relationName, parentModel, foreignKey, parentKey = 'id') {
209
+ return function() {
210
+ const foreignValue = this.data[foreignKey];
211
+ if (!foreignValue) {return null;}
212
+ return new QueryBuilder(parentModel.tableName)
213
+ .where(parentKey, foreignValue)
214
+ .first();
215
+ };
216
+ }
217
+
218
+ /**
219
+ * Get a relationship
220
+ */
221
+ getRelation(name) {
222
+ if (!this.relationships[name]) {
223
+ throw new Error(`Relationship "${name}" not defined on model`);
224
+ }
225
+ return this.relationships[name].call(this);
226
+ }
227
+
228
+ /**
229
+ * Query builder for this model
230
+ */
231
+ static query() {
232
+ return new QueryBuilder(this.tableName);
233
+ }
234
+
235
+ /**
236
+ * Find by ID
237
+ */
238
+ static findById(id) {
239
+ return new QueryBuilder(this.tableName)
240
+ .where('id', id)
241
+ .first();
242
+ }
243
+
244
+ /**
245
+ * Find all
246
+ */
247
+ static all() {
248
+ return new QueryBuilder(this.tableName).all();
249
+ }
250
+
251
+ /**
252
+ * Create new record
253
+ */
254
+ static create(data) {
255
+ const fields = Object.keys(data);
256
+ const values = Object.values(data);
257
+ const placeholders = fields.map(() => '?').join(', ');
258
+
259
+ const sql = `INSERT INTO ${this.tableName} (${fields.join(', ')}) VALUES (${placeholders})`;
260
+ const result = dbRun(sql, values);
261
+
262
+ return { id: result.lastInsertRowid, ...data };
263
+ }
264
+
265
+ /**
266
+ * Update record
267
+ */
268
+ static update(id, data) {
269
+ const fields = Object.keys(data);
270
+ const values = Object.values(data);
271
+ const setClause = fields.map(f => `${f} = ?`).join(', ');
272
+
273
+ const sql = `UPDATE ${this.tableName} SET ${setClause}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`;
274
+ return dbRun(sql, [...values, id]);
275
+ }
276
+
277
+ /**
278
+ * Delete record
279
+ */
280
+ static delete(id) {
281
+ const sql = `DELETE FROM ${this.tableName} WHERE id = ?`;
282
+ return dbRun(sql, [id]);
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Transaction Support
288
+ * Provides ACID-compliant multi-step operations
289
+ * Note: SQLite auto-manages transactions in WAL mode, so we batch operations
290
+ */
291
+ export class Transaction {
292
+ constructor(db) {
293
+ this.db = db;
294
+ this.isActive = false;
295
+ this.operations = [];
296
+ }
297
+
298
+ /**
299
+ * Begin transaction (queues operations)
300
+ */
301
+ begin() {
302
+ this.isActive = true;
303
+ this.operations = [];
304
+ return this;
305
+ }
306
+
307
+ /**
308
+ * Add operation to transaction
309
+ */
310
+ addOperation(sql, bindings = []) {
311
+ if (!this.isActive) {
312
+ throw new Error('Transaction not active');
313
+ }
314
+ this.operations.push({ sql, bindings });
315
+ return this;
316
+ }
317
+
318
+ /**
319
+ * Commit transaction (executes all operations)
320
+ */
321
+ commit() {
322
+ if (!this.isActive) {
323
+ throw new Error('No active transaction');
324
+ }
325
+
326
+ try {
327
+ // Execute all operations
328
+ for (const op of this.operations) {
329
+ dbRun(op.sql, op.bindings);
330
+ }
331
+ this.isActive = false;
332
+ this.operations = [];
333
+ return true;
334
+ } catch (error) {
335
+ this.rollback();
336
+ throw error;
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Rollback transaction (clear operations)
342
+ */
343
+ rollback() {
344
+ if (this.isActive) {
345
+ this.isActive = false;
346
+ this.operations = [];
347
+ }
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Migration Runner
353
+ * Handles schema versioning and migrations
354
+ */
355
+ export class MigrationRunner {
356
+ constructor(db) {
357
+ this.db = db;
358
+ this.migrationsPath = new URL('../migrations', import.meta.url).pathname;
359
+ this.initMigrationsTable();
360
+ }
361
+
362
+ /**
363
+ * Initialize migrations tracking table
364
+ */
365
+ initMigrationsTable() {
366
+ const sql = `
367
+ CREATE TABLE IF NOT EXISTS migrations (
368
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
369
+ name TEXT UNIQUE NOT NULL,
370
+ executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
371
+ )
372
+ `;
373
+ dbRun(sql);
374
+ }
375
+
376
+ /**
377
+ * Get list of executed migrations
378
+ */
379
+ getExecutedMigrations() {
380
+ const sql = 'SELECT name FROM migrations ORDER BY executed_at ASC';
381
+ const results = dbQuery(sql);
382
+ return results.map(r => r.name);
383
+ }
384
+
385
+ /**
386
+ * Get list of pending migrations
387
+ */
388
+ async getPendingMigrations() {
389
+ const executed = this.getExecutedMigrations();
390
+ const migrationsDir = Bun.file(this.migrationsPath);
391
+
392
+ if (!migrationsDir.exists) {
393
+ return [];
394
+ }
395
+
396
+ const allMigrations = [];
397
+ // In a real implementation, this would scan the migrations directory
398
+ return allMigrations.filter(m => !executed.includes(m));
399
+ }
400
+
401
+ /**
402
+ * Run a single migration
403
+ */
404
+ runMigration(name, migrationSQL) {
405
+ try {
406
+ // Execute migration SQL
407
+ if (migrationSQL && migrationSQL.trim()) {
408
+ dbRun(migrationSQL);
409
+ }
410
+ // Record migration
411
+ dbRun(
412
+ 'INSERT INTO migrations (name) VALUES (?)',
413
+ [name]
414
+ );
415
+ return true;
416
+ } catch (error) {
417
+ throw new Error(`Migration ${name} failed: ${error.message}`, { cause: error });
418
+ }
419
+ }
420
+
421
+ /**
422
+ * Rollback last migration
423
+ */
424
+ rollbackMigration(name) {
425
+ const sql = 'DELETE FROM migrations WHERE name = ?';
426
+ dbRun(sql, [name]);
427
+ }
428
+
429
+ /**
430
+ * Run all pending migrations
431
+ */
432
+ async runPending() {
433
+ const pending = await this.getPendingMigrations();
434
+ const results = [];
435
+
436
+ for (const migration of pending) {
437
+ try {
438
+ this.runMigration(migration, ''); // SQL would come from file
439
+ results.push({ name: migration, status: 'success' });
440
+ } catch (error) {
441
+ results.push({ name: migration, status: 'failed', error: error.message });
442
+ }
443
+ }
444
+
445
+ return results;
446
+ }
447
+ }
448
+
449
+ /**
450
+ * Define model relationships dynamically
451
+ */
452
+ export function defineRelationships(TargetModel, relationships) {
453
+ for (const [name, definition] of Object.entries(relationships)) {
454
+ if (definition.type === 'hasMany') {
455
+ TargetModel.prototype[name] = TargetModel.hasMany(
456
+ name,
457
+ definition.model,
458
+ definition.foreignKey,
459
+ definition.localKey
460
+ );
461
+ } else if (definition.type === 'belongsTo') {
462
+ TargetModel.prototype[name] = TargetModel.belongsTo(
463
+ name,
464
+ definition.model,
465
+ definition.foreignKey,
466
+ definition.parentKey
467
+ );
468
+ }
469
+ }
470
+ }
471
+
472
+ export default {
473
+ QueryBuilder,
474
+ Model,
475
+ Transaction,
476
+ MigrationRunner,
477
+ defineRelationships
478
+ };