@objectstack/objectql 0.4.2 → 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/index.ts CHANGED
@@ -1,348 +1,14 @@
1
- import { QueryAST, HookContext } from '@objectstack/spec/data';
2
- import { ObjectStackManifest } from '@objectstack/spec/system';
3
- import { DriverInterface, DriverOptions } from '@objectstack/spec/system';
4
- import { SchemaRegistry } from './registry';
5
-
6
- // Export Registry for consumers
1
+ // Export Registry
7
2
  export { SchemaRegistry } from './registry';
8
3
 
9
- export type HookHandler = (context: HookContext) => Promise<void> | void;
10
-
11
- /**
12
- * Host Context provided to plugins
13
- */
14
- export interface PluginContext {
15
- ql: ObjectQL;
16
- logger: Console;
17
- // Extensible map for host-specific globals (like HTTP Router, etc.)
18
- [key: string]: any;
19
- }
20
-
21
- /**
22
- * ObjectQL Engine
23
- */
24
- export class ObjectQL {
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
- // 1. Handle Module Imports (commonjs/esm interop)
51
- // If the passed object is a module namespace with a default export, use that.
52
- const manifest = manifestPart.default || manifestPart;
53
-
54
- // In a real scenario, we might strictly parse this using Zod
55
- // For now, simple ID check
56
- const id = manifest.id || manifest.name;
57
- if (!id) {
58
- console.warn(`[ObjectQL] Plugin manifest missing ID (keys: ${Object.keys(manifest)})`, manifest);
59
- // Don't return, try to proceed if it looks like an App (Apps might use 'name' instead of 'id')
60
- // return;
61
- }
62
-
63
- console.log(`[ObjectQL] Loading Plugin: ${id}`);
64
- SchemaRegistry.registerPlugin(manifest as ObjectStackManifest);
65
-
66
- // Register Objects from App/Plugin
67
- if (manifest.objects) {
68
- for (const obj of manifest.objects) {
69
- // Ensure object name is registered globally
70
- SchemaRegistry.registerObject(obj);
71
- console.log(`[ObjectQL] Registered Object: ${obj.name}`);
72
- }
73
- }
74
-
75
- // Register contributions
76
- if (manifest.contributes?.kinds) {
77
- for (const kind of manifest.contributes.kinds) {
78
- SchemaRegistry.registerKind(kind);
79
- }
80
- }
81
-
82
- // Register Data Seeding (Lazy execution or immediate?)
83
- // We store it in a temporary registry or execute immediately if engine is ready.
84
- // Since `use` is init time, we might need to store it and run later in `seed()`.
85
- // For this MVP, let's attach it to the manifest object in registry so Kernel can find it.
86
- }
87
-
88
- // 2. Execute Runtime
89
- if (runtimePart) {
90
- const pluginDef = (runtimePart as any).default || runtimePart;
91
- if (pluginDef.onEnable) {
92
- const context: PluginContext = {
93
- ql: this,
94
- logger: console,
95
- // Expose the driver registry helper explicitly if needed
96
- drivers: {
97
- register: (driver: DriverInterface) => this.registerDriver(driver)
98
- },
99
- ...this.hostContext
100
- };
101
-
102
- await pluginDef.onEnable(context);
103
- }
104
- }
105
- }
106
-
107
- /**
108
- * Register a hook
109
- * @param event The event name (e.g. 'beforeFind', 'afterInsert')
110
- * @param handler The handler function
111
- */
112
- registerHook(event: string, handler: HookHandler) {
113
- if (!this.hooks[event]) {
114
- this.hooks[event] = [];
115
- }
116
- this.hooks[event].push(handler);
117
- console.log(`[ObjectQL] Registered hook for ${event}`);
118
- }
119
-
120
- private async triggerHooks(event: string, context: HookContext) {
121
- const handlers = this.hooks[event] || [];
122
- for (const handler of handlers) {
123
- // In a real system, we might want to catch errors here or allow them to bubble up
124
- await handler(context);
125
- }
126
- }
127
-
128
- /**
129
- * Register a new storage driver
130
- */
131
- registerDriver(driver: DriverInterface, isDefault: boolean = false) {
132
- if (this.drivers.has(driver.name)) {
133
- console.warn(`[ObjectQL] Driver ${driver.name} is already registered. Skipping.`);
134
- return;
135
- }
136
-
137
- this.drivers.set(driver.name, driver);
138
- console.log(`[ObjectQL] Registered driver: ${driver.name} v${driver.version}`);
139
-
140
- if (isDefault || this.drivers.size === 1) {
141
- this.defaultDriver = driver.name;
142
- }
143
- }
144
-
145
- /**
146
- * Helper to get object definition
147
- */
148
- getSchema(objectName: string) {
149
- return SchemaRegistry.getObject(objectName);
150
- }
151
-
152
- /**
153
- * Helper to get the target driver
154
- */
155
- private getDriver(objectName: string): DriverInterface {
156
- const object = SchemaRegistry.getObject(objectName);
157
-
158
- // 1. If object definition exists, check for explicit datasource
159
- if (object) {
160
- const datasourceName = object.datasource || 'default';
161
-
162
- // If configured for 'default', try to find the default driver
163
- if (datasourceName === 'default') {
164
- if (this.defaultDriver && this.drivers.has(this.defaultDriver)) {
165
- return this.drivers.get(this.defaultDriver)!;
166
- }
167
- // Fallback: If 'default' not explicitly set, use the first available driver?
168
- // Better to be strict.
169
- } else {
170
- // Specific datasource requested
171
- if (this.drivers.has(datasourceName)) {
172
- return this.drivers.get(datasourceName)!;
173
- }
174
- // If not found, fall back to default? Or error?
175
- // Standard behavior: Error if specific datasource is missing.
176
- throw new Error(`[ObjectQL] Datasource '${datasourceName}' configured for object '${objectName}' is not registered.`);
177
- }
178
- }
179
-
180
- // 2. Fallback for ad-hoc objects or missing definitions
181
- // If we have a default driver, use it.
182
- if (this.defaultDriver) {
183
- if (!object) {
184
- console.warn(`[ObjectQL] Object '${objectName}' not found in registry. Using default driver.`);
185
- }
186
- return this.drivers.get(this.defaultDriver)!;
187
- }
188
-
189
- throw new Error(`[ObjectQL] No driver available for object '${objectName}'`);
190
- }
191
-
192
- /**
193
- * Initialize the engine and all registered drivers
194
- */
195
- async init() {
196
- console.log('[ObjectQL] Initializing drivers...');
197
- for (const [name, driver] of this.drivers) {
198
- try {
199
- await driver.connect();
200
- } catch (e) {
201
- console.error(`[ObjectQL] Failed to connect driver ${name}`, e);
202
- }
203
- }
204
- // In a real app, we would sync schemas here
205
- }
206
-
207
- async destroy() {
208
- for (const driver of this.drivers.values()) {
209
- await driver.disconnect();
210
- }
211
- }
212
-
213
- // ============================================
214
- // Data Access Methods
215
- // ============================================
216
-
217
- async find(object: string, query: any = {}, options?: DriverOptions) {
218
- const driver = this.getDriver(object);
219
-
220
- // Normalize QueryAST
221
- let ast: QueryAST;
222
- if (query.where || query.fields || query.orderBy || query.limit) {
223
- ast = { object, ...query } as QueryAST;
224
- } else {
225
- ast = { object, where: query } as QueryAST;
226
- }
227
-
228
- if (ast.limit === undefined) ast.limit = 100;
229
-
230
- // Trigger Before Hook
231
- const hookContext: HookContext = {
232
- object,
233
- event: 'beforeFind',
234
- input: { ast, options }, // Hooks can modify AST here
235
- ql: this
236
- };
237
- await this.triggerHooks('beforeFind', hookContext);
238
-
239
- try {
240
- const result = await driver.find(object, hookContext.input.ast, hookContext.input.options);
241
-
242
- // Trigger After Hook
243
- hookContext.event = 'afterFind';
244
- hookContext.result = result;
245
- await this.triggerHooks('afterFind', hookContext);
246
-
247
- return hookContext.result;
248
- } catch (e) {
249
- // hookContext.error = e;
250
- throw e;
251
- }
252
- }
253
-
254
- async findOne(object: string, idOrQuery: string | any, options?: DriverOptions) {
255
- const driver = this.getDriver(object);
256
-
257
- let ast: QueryAST;
258
- if (typeof idOrQuery === 'string') {
259
- ast = {
260
- object,
261
- where: { _id: idOrQuery }
262
- };
263
- } else {
264
- // Assume query object
265
- // reuse logic from find() or just wrap it
266
- if (idOrQuery.where || idOrQuery.fields) {
267
- ast = { object, ...idOrQuery };
268
- } else {
269
- ast = { object, where: idOrQuery };
270
- }
271
- }
272
- // Limit 1 for findOne
273
- ast.limit = 1;
274
-
275
- return driver.findOne(object, ast, options);
276
- }
277
-
278
- async insert(object: string, data: Record<string, any>, options?: DriverOptions) {
279
- const driver = this.getDriver(object);
280
-
281
- // 1. Get Schema
282
- const schema = SchemaRegistry.getObject(object);
283
-
284
- if (schema) {
285
- // TODO: Validation Logic
286
- // validate(schema, data);
287
- }
288
-
289
- // 2. Trigger Before Hook
290
- const hookContext: HookContext = {
291
- object,
292
- event: 'beforeInsert',
293
- input: { data, options },
294
- ql: this
295
- };
296
- await this.triggerHooks('beforeInsert', hookContext);
297
-
298
- // 3. Execute Driver
299
- const result = await driver.create(object, hookContext.input.data, hookContext.input.options);
300
-
301
- // 4. Trigger After Hook
302
- hookContext.event = 'afterInsert';
303
- hookContext.result = result;
304
- await this.triggerHooks('afterInsert', hookContext);
305
-
306
- return hookContext.result;
307
- }
308
-
309
- async update(object: string, id: string | number, data: Record<string, any>, options?: DriverOptions) {
310
- const driver = this.getDriver(object);
311
-
312
- const hookContext: HookContext = {
313
- object,
314
- event: 'beforeUpdate',
315
- input: { id, data, options },
316
- ql: this
317
- };
318
- await this.triggerHooks('beforeUpdate', hookContext);
319
-
320
- const result = await driver.update(object, hookContext.input.id, hookContext.input.data, hookContext.input.options);
321
-
322
- hookContext.event = 'afterUpdate';
323
- hookContext.result = result;
324
- await this.triggerHooks('afterUpdate', hookContext);
325
-
326
- return hookContext.result;
327
- }
328
-
329
- async delete(object: string, id: string | number, options?: DriverOptions) {
330
- const driver = this.getDriver(object);
331
-
332
- const hookContext: HookContext = {
333
- object,
334
- event: 'beforeDelete',
335
- input: { id, options },
336
- ql: this
337
- };
338
- await this.triggerHooks('beforeDelete', hookContext);
4
+ // Export Protocol Implementation
5
+ export { ObjectStackProtocolImplementation } from './protocol';
339
6
 
340
- 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';
341
10
 
342
- hookContext.event = 'afterDelete';
343
- hookContext.result = result;
344
- await this.triggerHooks('afterDelete', hookContext);
11
+ // Export Plugin Shim
12
+ export { ObjectQLPlugin } from './plugin';
345
13
 
346
- return hookContext.result;
347
- }
348
- }
14
+ // Moved logic to engine.ts
package/src/plugin.ts ADDED
@@ -0,0 +1,62 @@
1
+ import { ObjectQL } from './engine';
2
+ import { ObjectStackProtocolImplementation } from './protocol';
3
+ import { Plugin, PluginContext } from '@objectstack/core';
4
+
5
+ export type { Plugin, PluginContext };
6
+
7
+ export class ObjectQLPlugin implements Plugin {
8
+ name = 'com.objectstack.engine.objectql';
9
+ type = 'objectql' as const;
10
+ version = '1.0.0';
11
+
12
+ private ql: ObjectQL | undefined;
13
+ private hostContext?: Record<string, any>;
14
+
15
+ constructor(ql?: ObjectQL, hostContext?: Record<string, any>) {
16
+ if (ql) {
17
+ this.ql = ql;
18
+ } else {
19
+ this.hostContext = hostContext;
20
+ // Lazily created in init
21
+ }
22
+ }
23
+
24
+ async init(ctx: PluginContext) {
25
+ if (!this.ql) {
26
+ this.ql = new ObjectQL(this.hostContext);
27
+ }
28
+
29
+ ctx.registerService('objectql', this.ql);
30
+ if(ctx.logger) ctx.logger.log(`[ObjectQLPlugin] ObjectQL engine registered as service`);
31
+
32
+ // Register Protocol Implementation
33
+ if (!this.ql) {
34
+ throw new Error('ObjectQL engine not initialized');
35
+ }
36
+ const protocolShim = new ObjectStackProtocolImplementation(this.ql);
37
+
38
+ ctx.registerService('protocol', protocolShim);
39
+ if(ctx.logger) ctx.logger.log(`[ObjectQLPlugin] Protocol service registered`);
40
+ }
41
+
42
+ async start(ctx: PluginContext) {
43
+ if(ctx.logger) ctx.logger.log(`[ObjectQLPlugin] ObjectQL engine initialized`);
44
+
45
+ // Discover features from Kernel Services
46
+ if (ctx.getServices && this.ql) {
47
+ const services = ctx.getServices();
48
+ for (const [name, service] of services.entries()) {
49
+ if (name.startsWith('driver.')) {
50
+ // Register Driver
51
+ this.ql.registerDriver(service);
52
+ if(ctx.logger) ctx.logger.log(`[ObjectQLPlugin] Discovered and registered driver service: ${name}`);
53
+ }
54
+ if (name.startsWith('app.')) {
55
+ // Register App
56
+ this.ql.registerApp(service); // service is Manifest
57
+ if(ctx.logger) ctx.logger.log(`[ObjectQLPlugin] Discovered and registered app service: ${name}`);
58
+ }
59
+ }
60
+ }
61
+ }
62
+ }
@@ -0,0 +1,104 @@
1
+ import { IObjectStackProtocol } from '@objectstack/spec/api';
2
+ import { IDataEngine } from '@objectstack/core';
3
+
4
+ // We import SchemaRegistry directly since this class lives in the same package
5
+ import { SchemaRegistry } from './registry';
6
+
7
+ export class ObjectStackProtocolImplementation implements IObjectStackProtocol {
8
+ private engine: IDataEngine;
9
+
10
+ constructor(engine: IDataEngine) {
11
+ this.engine = engine;
12
+ }
13
+
14
+ getDiscovery() {
15
+ return {
16
+ name: 'ObjectStack API',
17
+ version: '1.0',
18
+ capabilities: {
19
+ metadata: true,
20
+ data: true,
21
+ ui: true
22
+ }
23
+ };
24
+ }
25
+
26
+ getMetaTypes() {
27
+ return SchemaRegistry.getRegisteredTypes();
28
+ }
29
+
30
+ getMetaItems(type: string) {
31
+ return SchemaRegistry.listItems(type);
32
+ }
33
+
34
+ getMetaItem(type: string, name: string) {
35
+ return SchemaRegistry.getItem(type, name);
36
+ }
37
+
38
+ getUiView(object: string, type: 'list' | 'form') {
39
+ const schema = SchemaRegistry.getObject(object);
40
+ if (!schema) throw new Error(`Object ${object} not found`);
41
+
42
+ if (type === 'list') {
43
+ return {
44
+ type: 'list',
45
+ object: object,
46
+ columns: Object.keys(schema.fields || {}).slice(0, 5).map(f => ({
47
+ field: f,
48
+ label: schema.fields[f].label || f
49
+ }))
50
+ };
51
+ } else {
52
+ return {
53
+ type: 'form',
54
+ object: object,
55
+ sections: [
56
+ {
57
+ label: 'General',
58
+ fields: Object.keys(schema.fields || {}).map(f => ({
59
+ field: f
60
+ }))
61
+ }
62
+ ]
63
+ };
64
+ }
65
+ }
66
+
67
+ findData(object: string, query: any) {
68
+ return this.engine.find(object, query);
69
+ }
70
+
71
+ async getData(object: string, id: string) {
72
+ // IDataEngine doesn't have findOne, so we simulate it with find and limit 1
73
+ // Assuming the ID field is named '_id' or 'id'.
74
+ // For broad compatibility, we might need to know the ID field name.
75
+ // But traditionally it is _id in ObjectStack/mongo or id in others.
76
+ // Let's rely on finding by ID if the engine supports it via find?
77
+ // Actually, ObjectQL (the implementation) DOES have findOne.
78
+ // But we are programming against IDataEngine interface here.
79
+
80
+ // If the engine IS ObjectQL (which it practically is), we could cast it.
81
+ // But let's try to stick to interface.
82
+
83
+ const results = await this.engine.find(object, {
84
+ filter: { _id: id }, // Default Assumption: _id
85
+ limit: 1
86
+ });
87
+ if (results && results.length > 0) {
88
+ return results[0];
89
+ }
90
+ throw new Error(`Record ${id} not found in ${object}`);
91
+ }
92
+
93
+ createData(object: string, data: any) {
94
+ return this.engine.insert(object, data);
95
+ }
96
+
97
+ updateData(object: string, id: string, data: any) {
98
+ return this.engine.update(object, id, data);
99
+ }
100
+
101
+ deleteData(object: string, id: string) {
102
+ return this.engine.delete(object, id);
103
+ }
104
+ }
package/src/registry.ts CHANGED
@@ -29,6 +29,19 @@ export class SchemaRegistry {
29
29
  console.log(`[Registry] Registered ${type}: ${key}`);
30
30
  }
31
31
 
32
+ /**
33
+ * Universal Unregister Method
34
+ */
35
+ static unregisterItem(type: string, name: string) {
36
+ const collection = this.metadata.get(type);
37
+ if (collection && collection.has(name)) {
38
+ collection.delete(name);
39
+ console.log(`[Registry] Unregistered ${type}: ${name}`);
40
+ } else {
41
+ console.warn(`[Registry] Attempted to unregister non-existent ${type}: ${name}`);
42
+ }
43
+ }
44
+
32
45
  /**
33
46
  * Universal Get Method
34
47
  */