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