@objectstack/objectql 0.6.0 → 0.6.1

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.
package/src/engine.ts ADDED
@@ -0,0 +1,404 @@
1
+ import { QueryAST, HookContext } from '@objectstack/spec/data';
2
+ import { ObjectStackManifest } from '@objectstack/spec/system';
3
+ import { DriverOptions } from '@objectstack/spec/system';
4
+ import { DriverInterface, IDataEngine, DataEngineQueryOptions } from '@objectstack/core';
5
+ import { SchemaRegistry } from './registry';
6
+
7
+ export type HookHandler = (context: HookContext) => Promise<void> | void;
8
+
9
+ /**
10
+ * Host Context provided to plugins (Internal ObjectQL Plugin System)
11
+ */
12
+ export interface ObjectQLHostContext {
13
+ ql: ObjectQL;
14
+ logger: Console;
15
+ // Extensible map for host-specific globals (like HTTP Router, etc.)
16
+ [key: string]: any;
17
+ }
18
+
19
+ /**
20
+ * ObjectQL Engine
21
+ *
22
+ * Implements the IDataEngine interface for data persistence.
23
+ */
24
+ export class ObjectQL implements IDataEngine {
25
+ private drivers = new Map<string, DriverInterface>();
26
+ private defaultDriver: string | null = null;
27
+
28
+ // Hooks Registry
29
+ private hooks: Record<string, HookHandler[]> = {
30
+ 'beforeFind': [], 'afterFind': [],
31
+ 'beforeInsert': [], 'afterInsert': [],
32
+ 'beforeUpdate': [], 'afterUpdate': [],
33
+ 'beforeDelete': [], 'afterDelete': [],
34
+ };
35
+
36
+ // Host provided context additions (e.g. Server router)
37
+ private hostContext: Record<string, any> = {};
38
+
39
+ constructor(hostContext: Record<string, any> = {}) {
40
+ this.hostContext = hostContext;
41
+ console.log(`[ObjectQL] Engine Instance Created`);
42
+ }
43
+
44
+ /**
45
+ * Load and Register a Plugin
46
+ */
47
+ async use(manifestPart: any, runtimePart?: any) {
48
+ // 1. Validate / Register Manifest
49
+ if (manifestPart) {
50
+ this.registerApp(manifestPart);
51
+ }
52
+
53
+ // 2. Execute Runtime
54
+ if (runtimePart) {
55
+ const pluginDef = (runtimePart as any).default || runtimePart;
56
+ if (pluginDef.onEnable) {
57
+ const context: ObjectQLHostContext = {
58
+ ql: this,
59
+ logger: console,
60
+ // Expose the driver registry helper explicitly if needed
61
+ drivers: {
62
+ register: (driver: DriverInterface) => this.registerDriver(driver)
63
+ },
64
+ ...this.hostContext
65
+ };
66
+
67
+ await pluginDef.onEnable(context);
68
+ }
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Register a hook
74
+ * @param event The event name (e.g. 'beforeFind', 'afterInsert')
75
+ * @param handler The handler function
76
+ */
77
+ registerHook(event: string, handler: HookHandler) {
78
+ if (!this.hooks[event]) {
79
+ this.hooks[event] = [];
80
+ }
81
+ this.hooks[event].push(handler);
82
+ console.log(`[ObjectQL] Registered hook for ${event}`);
83
+ }
84
+
85
+ public async triggerHooks(event: string, context: HookContext) {
86
+ const handlers = this.hooks[event] || [];
87
+ for (const handler of handlers) {
88
+ // In a real system, we might want to catch errors here or allow them to bubble up
89
+ await handler(context);
90
+ }
91
+ }
92
+
93
+ registerApp(manifestPart: any) {
94
+ // 1. Handle Module Imports (commonjs/esm interop)
95
+ // If the passed object is a module namespace with a default export, use that.
96
+ const raw = manifestPart.default || manifestPart;
97
+
98
+ // Support nested manifest property (Stack Definition)
99
+ // We merge the inner manifest metadata (id, version, etc) with the outer container (objects, apps)
100
+ const manifest = raw.manifest ? { ...raw, ...raw.manifest } : raw;
101
+
102
+ // In a real scenario, we might strictly parse this using Zod
103
+ // For now, simple ID check
104
+ const id = manifest.id || manifest.name;
105
+ if (!id) {
106
+ console.warn(`[ObjectQL] Plugin manifest missing ID (keys: ${Object.keys(manifest)})`, manifest);
107
+ // Don't return, try to proceed if it looks like an App (Apps might use 'name' instead of 'id')
108
+ // return;
109
+ }
110
+
111
+ console.log(`[ObjectQL] Loading App: ${id}`);
112
+ SchemaRegistry.registerPlugin(manifest as ObjectStackManifest);
113
+
114
+ // Register Objects from App/Plugin
115
+ if (manifest.objects) {
116
+ for (const obj of manifest.objects) {
117
+ // Ensure object name is registered globally
118
+ SchemaRegistry.registerObject(obj);
119
+ console.log(`[ObjectQL] Registered Object: ${obj.name}`);
120
+ }
121
+ }
122
+
123
+ // Register contributions
124
+ if (manifest.contributes?.kinds) {
125
+ for (const kind of manifest.contributes.kinds) {
126
+ SchemaRegistry.registerKind(kind);
127
+ }
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Register a new storage driver
133
+ */
134
+ registerDriver(driver: DriverInterface, isDefault: boolean = false) {
135
+ if (this.drivers.has(driver.name)) {
136
+ console.warn(`[ObjectQL] Driver ${driver.name} is already registered. Skipping.`);
137
+ return;
138
+ }
139
+
140
+ this.drivers.set(driver.name, driver);
141
+ console.log(`[ObjectQL] Registered driver: ${driver.name} v${driver.version}`);
142
+
143
+ if (isDefault || this.drivers.size === 1) {
144
+ this.defaultDriver = driver.name;
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Helper to get object definition
150
+ */
151
+ getSchema(objectName: string) {
152
+ return SchemaRegistry.getObject(objectName);
153
+ }
154
+
155
+ /**
156
+ * Helper to get the target driver
157
+ */
158
+ private getDriver(objectName: string): DriverInterface {
159
+ const object = SchemaRegistry.getObject(objectName);
160
+
161
+ // 1. If object definition exists, check for explicit datasource
162
+ if (object) {
163
+ const datasourceName = object.datasource || 'default';
164
+
165
+ // If configured for 'default', try to find the default driver
166
+ if (datasourceName === 'default') {
167
+ if (this.defaultDriver && this.drivers.has(this.defaultDriver)) {
168
+ return this.drivers.get(this.defaultDriver)!;
169
+ }
170
+ // Fallback: If 'default' not explicitly set, use the first available driver?
171
+ // Better to be strict.
172
+ } else {
173
+ // Specific datasource requested
174
+ if (this.drivers.has(datasourceName)) {
175
+ return this.drivers.get(datasourceName)!;
176
+ }
177
+ // If not found, fall back to default? Or error?
178
+ // Standard behavior: Error if specific datasource is missing.
179
+ throw new Error(`[ObjectQL] Datasource '${datasourceName}' configured for object '${objectName}' is not registered.`);
180
+ }
181
+ }
182
+
183
+ // 2. Fallback for ad-hoc objects or missing definitions
184
+ // If we have a default driver, use it.
185
+ if (this.defaultDriver) {
186
+ if (!object) {
187
+ console.warn(`[ObjectQL] Object '${objectName}' not found in registry. Using default driver.`);
188
+ }
189
+ return this.drivers.get(this.defaultDriver)!;
190
+ }
191
+
192
+ throw new Error(`[ObjectQL] No driver available for object '${objectName}'`);
193
+ }
194
+
195
+ /**
196
+ * Initialize the engine and all registered drivers
197
+ */
198
+ async init() {
199
+ console.log('[ObjectQL] Initializing drivers...');
200
+ for (const [name, driver] of this.drivers) {
201
+ try {
202
+ await driver.connect();
203
+ } catch (e) {
204
+ console.error(`[ObjectQL] Failed to connect driver ${name}`, e);
205
+ }
206
+ }
207
+ // In a real app, we would sync schemas here
208
+ }
209
+
210
+ async destroy() {
211
+ for (const driver of this.drivers.values()) {
212
+ await driver.disconnect();
213
+ }
214
+ }
215
+
216
+ // ============================================
217
+ // Data Access Methods (IDataEngine Interface)
218
+ // ============================================
219
+
220
+ /**
221
+ * Find records matching a query (IDataEngine interface)
222
+ *
223
+ * @param object - Object name
224
+ * @param query - Query options (IDataEngine format)
225
+ * @returns Promise resolving to array of records
226
+ */
227
+ async find(object: string, query?: DataEngineQueryOptions): Promise<any[]> {
228
+ const driver = this.getDriver(object);
229
+
230
+ // Convert DataEngineQueryOptions to QueryAST
231
+ let ast: QueryAST = { object };
232
+
233
+ if (query) {
234
+ // Map DataEngineQueryOptions to QueryAST
235
+ if (query.filter) {
236
+ ast.where = query.filter;
237
+ }
238
+ if (query.select) {
239
+ ast.fields = query.select;
240
+ }
241
+ if (query.sort) {
242
+ // Convert sort Record to orderBy array
243
+ // sort: { createdAt: -1, name: 'asc' } => orderBy: [{ field: 'createdAt', order: 'desc' }, { field: 'name', order: 'asc' }]
244
+ ast.orderBy = Object.entries(query.sort).map(([field, order]) => ({
245
+ field,
246
+ order: (order === -1 || order === 'desc') ? 'desc' : 'asc'
247
+ }));
248
+ }
249
+ // Handle both limit and top (top takes precedence)
250
+ if (query.top !== undefined) {
251
+ ast.limit = query.top;
252
+ } else if (query.limit !== undefined) {
253
+ ast.limit = query.limit;
254
+ }
255
+ if (query.skip !== undefined) {
256
+ ast.offset = query.skip;
257
+ }
258
+ }
259
+
260
+ // Set default limit if not specified
261
+ if (ast.limit === undefined) ast.limit = 100;
262
+
263
+ // Trigger Before Hook
264
+ const hookContext: HookContext = {
265
+ object,
266
+ event: 'beforeFind',
267
+ input: { ast, options: undefined },
268
+ ql: this
269
+ };
270
+ await this.triggerHooks('beforeFind', hookContext);
271
+
272
+ try {
273
+ const result = await driver.find(object, hookContext.input.ast, hookContext.input.options);
274
+
275
+ // Trigger After Hook
276
+ hookContext.event = 'afterFind';
277
+ hookContext.result = result;
278
+ await this.triggerHooks('afterFind', hookContext);
279
+
280
+ return hookContext.result;
281
+ } catch (e) {
282
+ // hookContext.error = e;
283
+ throw e;
284
+ }
285
+ }
286
+
287
+ async findOne(object: string, idOrQuery: string | any, options?: DriverOptions) {
288
+ const driver = this.getDriver(object);
289
+
290
+ let ast: QueryAST;
291
+ if (typeof idOrQuery === 'string') {
292
+ ast = {
293
+ object,
294
+ where: { _id: idOrQuery }
295
+ };
296
+ } else {
297
+ // Assume query object
298
+ // reuse logic from find() or just wrap it
299
+ if (idOrQuery.where || idOrQuery.fields) {
300
+ ast = { object, ...idOrQuery };
301
+ } else {
302
+ ast = { object, where: idOrQuery };
303
+ }
304
+ }
305
+ // Limit 1 for findOne
306
+ ast.limit = 1;
307
+
308
+ return driver.findOne(object, ast, options);
309
+ }
310
+
311
+ /**
312
+ * Insert a new record (IDataEngine interface)
313
+ *
314
+ * @param object - Object name
315
+ * @param data - Data to insert
316
+ * @returns Promise resolving to the created record
317
+ */
318
+ async insert(object: string, data: any): Promise<any> {
319
+ const driver = this.getDriver(object);
320
+
321
+ // 1. Get Schema
322
+ const schema = SchemaRegistry.getObject(object);
323
+
324
+ if (schema) {
325
+ // TODO: Validation Logic
326
+ // validate(schema, data);
327
+ }
328
+
329
+ // 2. Trigger Before Hook
330
+ const hookContext: HookContext = {
331
+ object,
332
+ event: 'beforeInsert',
333
+ input: { data, options: undefined },
334
+ ql: this
335
+ };
336
+ await this.triggerHooks('beforeInsert', hookContext);
337
+
338
+ // 3. Execute Driver
339
+ const result = await driver.create(object, hookContext.input.data, hookContext.input.options);
340
+
341
+ // 4. Trigger After Hook
342
+ hookContext.event = 'afterInsert';
343
+ hookContext.result = result;
344
+ await this.triggerHooks('afterInsert', hookContext);
345
+
346
+ return hookContext.result;
347
+ }
348
+
349
+ /**
350
+ * Update a record by ID (IDataEngine interface)
351
+ *
352
+ * @param object - Object name
353
+ * @param id - Record ID
354
+ * @param data - Updated data
355
+ * @returns Promise resolving to the updated record
356
+ */
357
+ async update(object: string, id: any, data: any): Promise<any> {
358
+ const driver = this.getDriver(object);
359
+
360
+ const hookContext: HookContext = {
361
+ object,
362
+ event: 'beforeUpdate',
363
+ input: { id, data, options: undefined },
364
+ ql: this
365
+ };
366
+ await this.triggerHooks('beforeUpdate', hookContext);
367
+
368
+ const result = await driver.update(object, hookContext.input.id, hookContext.input.data, hookContext.input.options);
369
+
370
+ hookContext.event = 'afterUpdate';
371
+ hookContext.result = result;
372
+ await this.triggerHooks('afterUpdate', hookContext);
373
+
374
+ return hookContext.result;
375
+ }
376
+
377
+ /**
378
+ * Delete a record by ID (IDataEngine interface)
379
+ *
380
+ * @param object - Object name
381
+ * @param id - Record ID
382
+ * @returns Promise resolving to true if deleted, false otherwise
383
+ */
384
+ async delete(object: string, id: any): Promise<boolean> {
385
+ const driver = this.getDriver(object);
386
+
387
+ const hookContext: HookContext = {
388
+ object,
389
+ event: 'beforeDelete',
390
+ input: { id, options: undefined },
391
+ ql: this
392
+ };
393
+ await this.triggerHooks('beforeDelete', hookContext);
394
+
395
+ const result = await driver.delete(object, hookContext.input.id, hookContext.input.options);
396
+
397
+ hookContext.event = 'afterDelete';
398
+ hookContext.result = result;
399
+ await this.triggerHooks('afterDelete', hookContext);
400
+
401
+ // Driver.delete() already returns boolean per DriverInterface spec
402
+ return hookContext.result;
403
+ }
404
+ }