fix: add TypeScript types to godMode client library

This commit is contained in:
cawcenter
2025-12-14 11:28:22 -05:00
parent d26643b5fe
commit 52393ea2dd

View File

@@ -10,12 +10,15 @@ const GOD_MODE_BASE_URL = import.meta.env.PUBLIC_DIRECTUS_URL || 'https://spark.
const GOD_TOKEN = import.meta.env.GOD_MODE_TOKEN || 'jmQXoeyxWoBsB7eHzG7FmnH90f22JtaYBxXHoorhfZ-v4tT3VNEr9vvmwHqYHCDoWXHSU4DeZXApCP-Gha-YdA'; const GOD_TOKEN = import.meta.env.GOD_MODE_TOKEN || 'jmQXoeyxWoBsB7eHzG7FmnH90f22JtaYBxXHoorhfZ-v4tT3VNEr9vvmwHqYHCDoWXHSU4DeZXApCP-Gha-YdA';
class GodModeClient { class GodModeClient {
constructor(token = GOD_TOKEN) { private token: string;
private baseUrl: string;
constructor(token: string = GOD_TOKEN) {
this.token = token; this.token = token;
this.baseUrl = `${GOD_MODE_BASE_URL}/god`; this.baseUrl = `${GOD_MODE_BASE_URL}/god`;
} }
async request(endpoint, options = {}) { async request(endpoint: string, options: RequestInit = {}): Promise<any> {
const url = `${this.baseUrl}${endpoint}`; const url = `${this.baseUrl}${endpoint}`;
const response = await fetch(url, { const response = await fetch(url, {
...options, ...options,
@@ -40,14 +43,14 @@ class GodModeClient {
} }
// === Database Operations === // === Database Operations ===
async setupDatabase(sql) { async setupDatabase(sql: string): Promise<any> {
return this.request('/setup/database', { return this.request('/setup/database', {
method: 'POST', method: 'POST',
body: JSON.stringify({ sql }) body: JSON.stringify({ sql })
}); });
} }
async executeSQL(sql, params = []) { async executeSQL(sql: string, params: any[] = []): Promise<any> {
return this.request('/sql/execute', { return this.request('/sql/execute', {
method: 'POST', method: 'POST',
body: JSON.stringify({ sql, params }) body: JSON.stringify({ sql, params })
@@ -55,19 +58,19 @@ class GodModeClient {
} }
// === Permissions === // === Permissions ===
async grantAllPermissions() { async grantAllPermissions(): Promise<any> {
return this.request('/permissions/grant-all', { return this.request('/permissions/grant-all', {
method: 'POST' method: 'POST'
}); });
} }
// === Collections === // === Collections ===
async getAllCollections() { async getAllCollections(): Promise<any> {
return this.request('/collections/all'); return this.request('/collections/all');
} }
// === Users === // === Users ===
async makeUserAdmin(emailOrId) { async makeUserAdmin(emailOrId: string): Promise<any> {
const body = typeof emailOrId === 'string' && emailOrId.includes('@') const body = typeof emailOrId === 'string' && emailOrId.includes('@')
? { email: emailOrId } ? { email: emailOrId }
: { userId: emailOrId }; : { userId: emailOrId };
@@ -79,38 +82,38 @@ class GodModeClient {
} }
// === Schema Management === // === Schema Management ===
async createCollection(collection, fields, meta = {}) { async createCollection(collection: string, fields: any[], meta: any = {}): Promise<any> {
return this.request('/schema/collections/create', { return this.request('/schema/collections/create', {
method: 'POST', method: 'POST',
body: JSON.stringify({ collection, fields, meta }) body: JSON.stringify({ collection, fields, meta })
}); });
} }
async addField(collection, field, type, meta = {}) { async addField(collection: string, field: string, type: string, meta: any = {}): Promise<any> {
return this.request('/schema/fields/create', { return this.request('/schema/fields/create', {
method: 'POST', method: 'POST',
body: JSON.stringify({ collection, field, type, meta }) body: JSON.stringify({ collection, field, type, meta })
}); });
} }
async deleteField(collection, field) { async deleteField(collection: string, field: string): Promise<any> {
return this.request(`/schema/fields/${collection}/${field}`, { return this.request(`/schema/fields/${collection}/${field}`, {
method: 'DELETE' method: 'DELETE'
}); });
} }
async exportSchema() { async exportSchema(): Promise<any> {
return this.request('/schema/snapshot'); return this.request('/schema/snapshot');
} }
async applySchema(yaml) { async applySchema(yaml: string): Promise<any> {
return this.request('/schema/apply', { return this.request('/schema/apply', {
method: 'POST', method: 'POST',
body: JSON.stringify({ yaml }) body: JSON.stringify({ yaml })
}); });
} }
async createRelation(relation) { async createRelation(relation: any): Promise<any> {
return this.request('/schema/relations/create', { return this.request('/schema/relations/create', {
method: 'POST', method: 'POST',
body: JSON.stringify(relation) body: JSON.stringify(relation)
@@ -118,7 +121,12 @@ class GodModeClient {
} }
// === Site Provisioning === // === Site Provisioning ===
async provisionSite({ name, domain, create_homepage = true, include_collections = [] }) { async provisionSite({ name, domain, create_homepage = true, include_collections = [] }: {
name: string;
domain: string;
create_homepage?: boolean;
include_collections?: string[];
}): Promise<any> {
return this.request('/sites/provision', { return this.request('/sites/provision', {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
@@ -130,7 +138,11 @@ class GodModeClient {
}); });
} }
async addPageToSite(siteId, { title, slug, template = 'default' }) { async addPageToSite(siteId: string, { title, slug, template = 'default' }: {
title: string;
slug: string;
template?: string;
}): Promise<any> {
return this.request(`/sites/${siteId}/add-page`, { return this.request(`/sites/${siteId}/add-page`, {
method: 'POST', method: 'POST',
body: JSON.stringify({ title, slug, template }) body: JSON.stringify({ title, slug, template })
@@ -138,21 +150,21 @@ class GodModeClient {
} }
// === Work Log === // === Work Log ===
async logWork(data) { async logWork(data: { action: string; details: any; userId?: string }): Promise<any> {
return this.executeSQL( return this.executeSQL(
'INSERT INTO work_log (action, details, user_id, timestamp) VALUES ($1, $2, $3, NOW()) RETURNING *', 'INSERT INTO work_log (action, details, user_id, timestamp) VALUES ($1, $2, $3, NOW()) RETURNING *',
[data.action, JSON.stringify(data.details), data.userId || 'god-mode'] [data.action, JSON.stringify(data.details), data.userId || 'god-mode']
); );
} }
async getWorkLog(limit = 100) { async getWorkLog(limit: number = 100): Promise<any> {
return this.executeSQL( return this.executeSQL(
`SELECT * FROM work_log ORDER BY timestamp DESC LIMIT ${limit}` `SELECT * FROM work_log ORDER BY timestamp DESC LIMIT ${limit}`
); );
} }
// === Error Logs === // === Error Logs ===
async logError(error, context = {}) { async logError(error: Error | any, context: any = {}): Promise<any> {
return this.executeSQL( return this.executeSQL(
'INSERT INTO error_logs (error_message, stack_trace, context, timestamp) VALUES ($1, $2, $3, NOW()) RETURNING *', 'INSERT INTO error_logs (error_message, stack_trace, context, timestamp) VALUES ($1, $2, $3, NOW()) RETURNING *',
[ [
@@ -163,21 +175,21 @@ class GodModeClient {
); );
} }
async getErrorLogs(limit = 50) { async getErrorLogs(limit: number = 50): Promise<any> {
return this.executeSQL( return this.executeSQL(
`SELECT * FROM error_logs ORDER BY timestamp DESC LIMIT ${limit}` `SELECT * FROM error_logs ORDER BY timestamp DESC LIMIT ${limit}`
); );
} }
// === Job Queue === // === Job Queue ===
async addJob(jobType, payload, priority = 0) { async addJob(jobType: string, payload: any, priority: number = 0): Promise<any> {
return this.executeSQL( return this.executeSQL(
'INSERT INTO job_queue (job_type, payload, priority, status, created_at) VALUES ($1, $2, $3, $4, NOW()) RETURNING *', 'INSERT INTO job_queue (job_type, payload, priority, status, created_at) VALUES ($1, $2, $3, $4, NOW()) RETURNING *',
[jobType, JSON.stringify(payload), priority, 'pending'] [jobType, JSON.stringify(payload), priority, 'pending']
); );
} }
async getJobQueue(status = null) { async getJobQueue(status: string | null = null): Promise<any> {
const sql = status const sql = status
? `SELECT * FROM job_queue WHERE status = $1 ORDER BY priority DESC, created_at ASC` ? `SELECT * FROM job_queue WHERE status = $1 ORDER BY priority DESC, created_at ASC`
: `SELECT * FROM job_queue ORDER BY priority DESC, created_at ASC`; : `SELECT * FROM job_queue ORDER BY priority DESC, created_at ASC`;
@@ -185,22 +197,22 @@ class GodModeClient {
return this.executeSQL(sql, status ? [status] : []); return this.executeSQL(sql, status ? [status] : []);
} }
async updateJobStatus(jobId, status, result = null) { async updateJobStatus(jobId: string, status: string, result: any = null): Promise<any> {
return this.executeSQL( return this.executeSQL(
'UPDATE job_queue SET status = $1, result = $2, updated_at = NOW() WHERE id = $3 RETURNING *', 'UPDATE job_queue SET status = $1, result = $2, updated_at = NOW() WHERE id = $3 RETURNING *',
[status, result ? JSON.stringify(result) : null, jobId] [status, result ? JSON.stringify(result) : null, jobId]
); );
} }
async clearCompletedJobs() { async clearCompletedJobs(): Promise<any> {
return this.executeSQL( return this.executeSQL(
"DELETE FROM job_queue WHERE status IN ('completed', 'failed') AND updated_at < NOW() - INTERVAL '7 days'" "DELETE FROM job_queue WHERE status IN ('completed', 'failed') AND updated_at < NOW() - INTERVAL '7 days'"
); );
} }
// === Batch Operations === // === Batch Operations ===
async batch(operations) { async batch(operations: Array<{ endpoint: string; method?: string; body?: any }>): Promise<any[]> {
const results = []; const results: any[] = [];
for (const op of operations) { for (const op of operations) {
try { try {
const result = await this.request(op.endpoint, { const result = await this.request(op.endpoint, {
@@ -208,8 +220,9 @@ class GodModeClient {
body: op.body ? JSON.stringify(op.body) : undefined body: op.body ? JSON.stringify(op.body) : undefined
}); });
results.push({ success: true, result }); results.push({ success: true, result });
} catch (error) { } catch (error: unknown) {
results.push({ success: false, error: error.message }); const err = error as Error;
results.push({ success: false, error: err.message });
} }
} }
return results; return results;