@maravilla-labs/platform 0.1.20 → 0.1.21

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/dist/index.d.ts CHANGED
@@ -294,7 +294,7 @@ interface DbFindOptions {
294
294
  * Source types accepted by Storage.putStream for streaming uploads.
295
295
  */
296
296
  type StoragePutStreamSource = Uint8Array | ArrayBuffer | string | Blob | ReadableStream<Uint8Array | ArrayBuffer | string | number[]> | Iterable<Uint8Array | ArrayBuffer | string | number[]> | AsyncIterable<Uint8Array | ArrayBuffer | string | number[]>;
297
- interface Storage {
297
+ interface Storage$1 {
298
298
  /**
299
299
  * Generate a presigned URL for uploading a file directly from the browser.
300
300
  *
@@ -506,7 +506,7 @@ interface PlatformEnv {
506
506
  /** Database interface for document operations */
507
507
  DB: Database;
508
508
  /** Object/file storage interface */
509
- STORAGE: Storage;
509
+ STORAGE: Storage$1;
510
510
  }
511
511
  /**
512
512
  * Main platform interface providing access to all Maravilla runtime services.
@@ -530,6 +530,50 @@ interface Platform {
530
530
  env: PlatformEnv;
531
531
  }
532
532
 
533
+ interface RenEvent {
534
+ t: string;
535
+ r: string;
536
+ k?: string;
537
+ v?: string;
538
+ ts?: number;
539
+ src?: string;
540
+ ns?: string;
541
+ [extra: string]: any;
542
+ }
543
+ interface RenClientOptions {
544
+ endpoint?: string;
545
+ subscriptions?: string[];
546
+ clientId?: string;
547
+ autoReconnect?: boolean;
548
+ maxBackoffMs?: number;
549
+ debug?: boolean;
550
+ }
551
+ type Listener = (event: RenEvent) => void;
552
+ declare class RenClient {
553
+ private endpoint;
554
+ private subs;
555
+ private clientId;
556
+ private listeners;
557
+ private es;
558
+ private closed;
559
+ private attempt;
560
+ private autoReconnect;
561
+ private maxBackoff;
562
+ private debug;
563
+ constructor(opts?: RenClientOptions);
564
+ private detectEndpoint;
565
+ private log;
566
+ private buildUrl;
567
+ private connect;
568
+ on(listener: Listener): () => void;
569
+ getClientId(): string;
570
+ close(): void;
571
+ }
572
+ declare function getOrCreateClientId(storage?: Storage): string;
573
+ declare function renFetch(input: string | URL | Request, init?: RequestInit, clientId?: string): Promise<Response>;
574
+ declare function storageUpload(path: string, file: Blob | File, clientId?: string): Promise<any>;
575
+ declare function storageDelete(path: string, clientId?: string): Promise<any>;
576
+
533
577
  /**
534
578
  * @fileoverview Maravilla Platform SDK
535
579
  *
@@ -650,4 +694,4 @@ declare function getPlatform(options?: {
650
694
  */
651
695
  declare function clearPlatformCache(): void;
652
696
 
653
- export { type Database, type DbFindOptions, type KvListResult, type KvNamespace, type Platform, type PlatformEnv, type Storage, type StoragePutStreamSource, clearPlatformCache, getPlatform };
697
+ export { type Database, type DbFindOptions, type KvListResult, type KvNamespace, type Platform, type PlatformEnv, RenClient, type RenClientOptions, type RenEvent, type Storage$1 as Storage, type StoragePutStreamSource, clearPlatformCache, getOrCreateClientId, getPlatform, renFetch, storageDelete, storageUpload };
package/dist/index.js CHANGED
@@ -285,6 +285,171 @@ function createRemoteClient(baseUrl, tenant) {
285
285
  };
286
286
  }
287
287
 
288
+ // src/ren.ts
289
+ var RenClient = class {
290
+ endpoint;
291
+ subs;
292
+ clientId;
293
+ listeners = /* @__PURE__ */ new Set();
294
+ es = null;
295
+ closed = false;
296
+ attempt = 0;
297
+ autoReconnect;
298
+ maxBackoff;
299
+ debug;
300
+ constructor(opts = {}) {
301
+ this.endpoint = opts.endpoint || this.detectEndpoint();
302
+ this.subs = opts.subscriptions && opts.subscriptions.length ? opts.subscriptions : ["*"];
303
+ this.clientId = opts.clientId || getOrCreateClientId();
304
+ this.autoReconnect = opts.autoReconnect !== false;
305
+ this.maxBackoff = opts.maxBackoffMs ?? 15e3;
306
+ this.debug = !!opts.debug || typeof localStorage !== "undefined" && localStorage.getItem("REN_DEBUG") === "1";
307
+ this.connect();
308
+ }
309
+ detectEndpoint() {
310
+ console.log("[REN detectEndpoint] Starting detection...");
311
+ console.log("[REN detectEndpoint] globalThis:", typeof globalThis);
312
+ console.log("[REN detectEndpoint] globalThis.platform:", globalThis?.platform);
313
+ console.log("[REN detectEndpoint] globalThis.__maravilla_platform:", globalThis?.__maravilla_platform);
314
+ console.log("[REN detectEndpoint] window:", typeof window);
315
+ console.log("[REN detectEndpoint] window.location:", typeof window !== "undefined" ? window.location.href : "N/A");
316
+ if (typeof globalThis !== "undefined" && globalThis.platform) {
317
+ console.log("[REN detectEndpoint] Detected production runtime, using relative endpoint");
318
+ return "/api/maravilla/ren";
319
+ }
320
+ if (typeof window !== "undefined" && window.location.port === "5173") {
321
+ const devServerUrl = `http://${window.location.hostname}:3001`;
322
+ console.log("[REN detectEndpoint] Detected Vite dev server (port 5173), using dev server:", devServerUrl);
323
+ return `${devServerUrl}/api/maravilla/ren`;
324
+ }
325
+ if (typeof globalThis !== "undefined" && globalThis.__maravilla_platform) {
326
+ let devServerUrl = "http://localhost:3001";
327
+ if (typeof window !== "undefined" && window.location.hostname !== "localhost") {
328
+ devServerUrl = `http://${window.location.hostname}:3001`;
329
+ }
330
+ console.log("[REN detectEndpoint] Detected injected platform, using dev server:", devServerUrl);
331
+ return `${devServerUrl}/api/maravilla/ren`;
332
+ }
333
+ console.log("[REN detectEndpoint] Using default relative endpoint (preview/production mode)");
334
+ return "/api/maravilla/ren";
335
+ }
336
+ log(...args) {
337
+ if (this.debug) console.debug("[RenClient]", ...args);
338
+ }
339
+ buildUrl() {
340
+ const s = this.subs.length === 1 && this.subs[0] === "*" ? "*" : this.subs.join(",");
341
+ const qs = new URLSearchParams({ cid: this.clientId, s });
342
+ return `${this.endpoint}?${qs.toString()}`;
343
+ }
344
+ connect() {
345
+ const url = this.buildUrl();
346
+ this.log("connecting", { url });
347
+ this.es = new EventSource(url);
348
+ this.closed = false;
349
+ const forward = (e) => {
350
+ try {
351
+ const evt = JSON.parse(e.data);
352
+ this.log("event", evt);
353
+ this.listeners.forEach((l) => l(evt));
354
+ } catch (err) {
355
+ this.log("malformed event data", e.data, err);
356
+ }
357
+ };
358
+ this.es.onmessage = forward;
359
+ const knownEventTypes = [
360
+ // Database events
361
+ "db.document.created",
362
+ "db.document.updated",
363
+ "db.document.deleted",
364
+ // KV events
365
+ "kv.put",
366
+ "kv.delete",
367
+ "kv.expired",
368
+ // Storage events
369
+ "storage.object.created",
370
+ "storage.object.updated",
371
+ "storage.object.deleted",
372
+ // Runtime events
373
+ "runtime.snapshot.ready",
374
+ "runtime.worker.started",
375
+ "runtime.worker.stopped",
376
+ // Meta events
377
+ "ren.meta"
378
+ ];
379
+ knownEventTypes.forEach((k) => this.es?.addEventListener(k, forward));
380
+ this.es.onerror = (ev) => {
381
+ this.log("error", ev);
382
+ if (this.closed) return;
383
+ this.es?.close();
384
+ if (!this.autoReconnect) return;
385
+ const delay = Math.min(1e3 * Math.pow(2, this.attempt++), this.maxBackoff);
386
+ this.log("reconnecting in", delay, "ms");
387
+ setTimeout(() => this.connect(), delay);
388
+ };
389
+ this.es.onopen = () => {
390
+ this.attempt = 0;
391
+ this.log("open");
392
+ };
393
+ }
394
+ on(listener) {
395
+ this.listeners.add(listener);
396
+ this.log("listener added; total", this.listeners.size);
397
+ return () => {
398
+ this.listeners.delete(listener);
399
+ this.log("listener removed; total", this.listeners.size);
400
+ };
401
+ }
402
+ getClientId() {
403
+ return this.clientId;
404
+ }
405
+ close() {
406
+ this.closed = true;
407
+ this.es?.close();
408
+ this.log("closed");
409
+ }
410
+ };
411
+ function getOrCreateClientId(storage) {
412
+ if (!storage) {
413
+ storage = typeof window !== "undefined" && window.localStorage ? window.localStorage : typeof globalThis !== "undefined" && globalThis.localStorage ? globalThis.localStorage : void 0;
414
+ if (!storage) {
415
+ return globalThis.crypto?.randomUUID?.() || randomFallback();
416
+ }
417
+ }
418
+ const key = "maravillaClientId";
419
+ let id = storage.getItem(key);
420
+ if (!id) {
421
+ id = globalThis.crypto?.randomUUID?.() || randomFallback();
422
+ try {
423
+ storage.setItem(key, id);
424
+ } catch {
425
+ }
426
+ }
427
+ return id;
428
+ }
429
+ function randomFallback() {
430
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
431
+ const r = Math.random() * 16 | 0;
432
+ const v = c === "x" ? r : r & 3 | 8;
433
+ return v.toString(16);
434
+ });
435
+ }
436
+ async function renFetch(input, init = {}, clientId) {
437
+ const cid = clientId || getOrCreateClientId();
438
+ const headers = new Headers(init.headers || {});
439
+ headers.set("X-Ren-Client", cid);
440
+ return fetch(input, { ...init, headers });
441
+ }
442
+ async function storageUpload(path, file, clientId) {
443
+ const res = await renFetch(`/api/storage/upload?path=${encodeURIComponent(path)}`, { method: "POST", body: file }, clientId);
444
+ if (!res.ok) throw new Error("upload failed");
445
+ return res.json().catch(() => ({}));
446
+ }
447
+ async function storageDelete(path, clientId) {
448
+ const res = await renFetch(`/api/storage/delete?path=${encodeURIComponent(path)}`, { method: "DELETE" }, clientId);
449
+ if (!res.ok) throw new Error("delete failed");
450
+ return res.json().catch(() => ({}));
451
+ }
452
+
288
453
  // src/index.ts
289
454
  var cachedPlatform = null;
290
455
  function getPlatform(options) {
@@ -319,7 +484,12 @@ function clearPlatformCache() {
319
484
  }
320
485
  }
321
486
  export {
487
+ RenClient,
322
488
  clearPlatformCache,
323
- getPlatform
489
+ getOrCreateClientId,
490
+ getPlatform,
491
+ renFetch,
492
+ storageDelete,
493
+ storageUpload
324
494
  };
325
495
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/remote-client.ts","../src/index.ts"],"sourcesContent":["import type { KvNamespace, KvListResult, Database, DbFindOptions, Storage } from './types.js';\n\n/**\n * Remote KV namespace implementation that communicates with a development server.\n * This class provides the KV interface by making HTTP requests to the dev server.\n * \n * @internal\n */\nclass RemoteKvNamespace implements KvNamespace {\n constructor(\n private baseUrl: string,\n private namespace: string,\n private headers: Record<string, string>\n ) {}\n\n /**\n * Internal method for making HTTP requests to the dev server.\n * Handles error responses and authentication headers.\n * \n * @internal\n */\n private async fetch(url: string, options: RequestInit = {}) {\n const response = await fetch(url, {\n ...options,\n headers: { ...this.headers, ...options.headers },\n });\n\n if (!response.ok && response.status !== 404) {\n const error = await response.text();\n throw new Error(`Platform API error: ${response.status} - ${error}`);\n }\n\n return response;\n }\n\n async get(key: string): Promise<any> {\n const response = await this.fetch(`${this.baseUrl}/api/kv/${this.namespace}/${key}`);\n if (response.status === 404) return null;\n return response.json();\n }\n\n async put(key: string, value: any, options?: { expirationTtl?: number }): Promise<void> {\n const headers: Record<string, string> = {};\n if (options?.expirationTtl) {\n headers['X-TTL'] = options.expirationTtl.toString();\n }\n\n await this.fetch(`${this.baseUrl}/api/kv/${this.namespace}/${key}`, {\n method: 'PUT',\n headers,\n body: JSON.stringify(value),\n });\n }\n\n async delete(key: string): Promise<void> {\n await this.fetch(`${this.baseUrl}/api/kv/${this.namespace}/${key}`, {\n method: 'DELETE',\n });\n }\n\n async list(options?: { prefix?: string; limit?: number; cursor?: string }): Promise<KvListResult> {\n const response = await this.fetch(`${this.baseUrl}/api/kv/${this.namespace}`, {\n method: 'POST',\n body: JSON.stringify(options || {}),\n });\n const data = await response.json() as any;\n return {\n keys: data.result || [],\n list_complete: !data.result_info?.cursor,\n cursor: data.result_info?.cursor,\n };\n }\n}\n\n/**\n * Remote Database implementation that communicates with a development server.\n * This class provides the Database interface by making HTTP requests to the dev server.\n * \n * @internal\n */\nclass RemoteDatabase implements Database {\n constructor(\n private baseUrl: string,\n private headers: Record<string, string>\n ) {}\n\n /**\n * Internal method for making HTTP requests to the dev server.\n * Handles error responses and authentication headers.\n * \n * @internal\n */\n private async fetch(url: string, options: RequestInit = {}) {\n const response = await fetch(url, {\n ...options,\n headers: { ...this.headers, ...options.headers },\n });\n\n if (!response.ok && response.status !== 404) {\n const error = await response.text();\n throw new Error(`Platform API error: ${response.status} - ${error}`);\n }\n\n return response;\n }\n\n async find(collection: string, filter: any = {}, options: DbFindOptions = {}): Promise<any[]> {\n const response = await this.fetch(`${this.baseUrl}/api/db/${collection}`, {\n method: 'POST',\n body: JSON.stringify({ filter, options }),\n });\n return response.json() as Promise<any[]>;\n }\n\n async findOne(collection: string, filter: any): Promise<any | null> {\n const response = await this.fetch(`${this.baseUrl}/api/db/${collection}/findOne`, {\n method: 'POST',\n body: JSON.stringify(filter),\n });\n if (response.status === 404) return null;\n return response.json();\n }\n\n async insertOne(collection: string, document: any): Promise<string> {\n const response = await this.fetch(`${this.baseUrl}/api/db/${collection}`, {\n method: 'PUT',\n body: JSON.stringify(document),\n });\n const result = await response.json() as any;\n return result.id;\n }\n\n async updateOne(collection: string, filter: any, update: any): Promise<{ modified: number }> {\n const response = await this.fetch(`${this.baseUrl}/api/db/${collection}/update`, {\n method: 'POST',\n body: JSON.stringify({ filter, update }),\n });\n return response.json() as Promise<{ modified: number }>;\n }\n\n async deleteOne(collection: string, filter: any): Promise<{ deleted: number }> {\n const response = await this.fetch(`${this.baseUrl}/api/db/${collection}/delete`, {\n method: 'DELETE',\n body: JSON.stringify(filter),\n });\n return response.json() as Promise<{ deleted: number }>;\n }\n\n async deleteMany(collection: string, filter: any): Promise<{ deleted: number }> {\n // For now, deleteMany is the same as deleteOne in the remote client\n // This would need to be implemented properly in the dev server\n return this.deleteOne(collection, filter);\n }\n}\n\n/**\n * Remote Storage implementation that communicates with a development server.\n * This class provides the Storage interface by making HTTP requests to the dev server.\n * \n * @internal\n */\nclass RemoteStorage implements Storage {\n constructor(\n private baseUrl: string,\n private headers: Record<string, string>\n ) {}\n\n /**\n * Internal method for making HTTP requests to the dev server.\n * Handles error responses and authentication headers.\n * \n * @internal\n */\n private async fetch(url: string, options: RequestInit = {}) {\n const response = await fetch(url, {\n ...options,\n headers: { ...this.headers, ...options.headers },\n });\n\n if (!response.ok && response.status !== 404) {\n const error = await response.text();\n throw new Error(`Platform API error: ${response.status} - ${error}`);\n }\n\n return response;\n }\n\n async generateUploadUrl(key: string, contentType: string, options?: { sizeLimit?: number }): Promise<{\n url: string;\n method: string;\n headers: Record<string, string>;\n expiresIn: number;\n }> {\n // For development, return a direct upload URL to the dev server\n // The dev server supports PUT directly to /api/storage/{key}\n return {\n url: `${this.baseUrl}/api/storage/${encodeURIComponent(key)}`,\n method: 'PUT',\n headers: {\n 'Content-Type': contentType,\n ...this.headers, // Include tenant headers\n },\n expiresIn: 3600, // 1 hour\n };\n }\n\n async generateDownloadUrl(key: string, options?: { expiresIn?: number }): Promise<{\n url: string;\n method: string;\n headers: Record<string, string>;\n expiresIn: number;\n }> {\n // For development, return a direct download URL to the dev server\n // In production, this would call the actual storage service for presigned URLs\n return {\n url: `${this.baseUrl}/api/storage/${encodeURIComponent(key)}`,\n method: 'GET',\n headers: {},\n expiresIn: options?.expiresIn || 3600, // Default 1 hour\n };\n }\n\n async get(key: string): Promise<Uint8Array | null> {\n const response = await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`);\n if (response.status === 404) return null;\n const arrayBuffer = await response.arrayBuffer();\n return new Uint8Array(arrayBuffer);\n }\n\n async put(key: string, data: Uint8Array | string, metadata?: any): Promise<void> {\n // Convert string to Uint8Array if needed\n const bodyData = typeof data === 'string' \n ? new TextEncoder().encode(data)\n : data;\n\n await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`, {\n method: 'PUT',\n headers: metadata ? { 'X-Metadata': JSON.stringify(metadata) } : {},\n // Cast because TypeScript's lib.dom.d.ts BodyInit union sometimes misses Uint8Array\n body: bodyData as any,\n });\n }\n\n async putStream(key: string, source: any, metadata?: any): Promise<void> {\n // If it's a Blob we can send directly\n if (typeof Blob !== 'undefined' && source instanceof Blob) {\n await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`, {\n method: 'PUT',\n headers: {\n ...(metadata ? { 'X-Metadata': JSON.stringify(metadata) } : {}),\n 'Content-Type': source.type || 'application/octet-stream'\n },\n body: source as any,\n });\n return;\n }\n\n // ReadableStream\n if (source && typeof source.getReader === 'function') {\n await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`, {\n method: 'PUT',\n headers: metadata ? { 'X-Metadata': JSON.stringify(metadata) } : {},\n body: source as any,\n });\n return;\n }\n\n // Async iterable -> wrap in ReadableStream\n if (Symbol.asyncIterator in Object(source ?? {})) {\n const asyncIt = source as AsyncIterable<any>;\n const stream = new ReadableStream({\n async pull(controller) {\n const { value, done } = await asyncIt[Symbol.asyncIterator]().next();\n if (done) { controller.close(); return; }\n controller.enqueue(RemoteStorage.normalizeChunk(value));\n }\n });\n await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`, {\n method: 'PUT',\n headers: metadata ? { 'X-Metadata': JSON.stringify(metadata) } : {},\n body: stream as any,\n });\n return;\n }\n\n // Synchronous iterable\n if (Symbol.iterator in Object(source ?? {})) {\n const it = (source as Iterable<any>)[Symbol.iterator]();\n const stream = new ReadableStream({\n pull(controller) {\n const res = it.next();\n if (res.done) { controller.close(); return; }\n controller.enqueue(RemoteStorage.normalizeChunk(res.value));\n }\n });\n await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`, {\n method: 'PUT',\n headers: metadata ? { 'X-Metadata': JSON.stringify(metadata) } : {},\n body: stream as any,\n });\n return;\n }\n\n // Fallback: primitive/string/Uint8Array/ArrayBuffer\n await this.put(key, RemoteStorage.normalizeChunk(source), metadata);\n }\n private static normalizeChunk(c: any): Uint8Array {\n if (c == null) return new Uint8Array();\n if (typeof c === 'string') return new TextEncoder().encode(c);\n if (c instanceof Uint8Array) return c;\n if (c instanceof ArrayBuffer) return new Uint8Array(c);\n if (Array.isArray(c)) return Uint8Array.from(c);\n throw new Error('Unsupported chunk type in putStream');\n }\n async delete(key: string): Promise<void> {\n await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`, {\n method: 'DELETE',\n });\n }\n\n async list(options?: { prefix?: string; limit?: number }): Promise<Array<{\n key: string;\n size: number;\n lastModified: string;\n metadata?: any;\n }>> {\n const params = new URLSearchParams();\n if (options?.prefix) params.set('prefix', options.prefix);\n if (options?.limit) params.set('limit', options.limit.toString());\n\n const response = await this.fetch(`${this.baseUrl}/api/storage?${params}`);\n return response.json();\n }\n\n async getMetadata(key: string): Promise<{\n size: number;\n contentType?: string;\n lastModified: string;\n metadata?: any;\n } | null> {\n const response = await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}/metadata`);\n if (response.status === 404) return null;\n return response.json();\n }\n}\n\n/**\n * Create a remote platform client for development environments.\n * \n * This function creates a platform instance that communicates with a development\n * server over HTTP. It's used internally by getPlatform() when running in development\n * mode and no native platform is available.\n * \n * @param baseUrl - The base URL of the development server\n * @param tenant - The tenant identifier for multi-tenancy support\n * @returns A platform instance that proxies requests to the development server\n * \n * @internal\n * \n * @example\n * ```typescript\n * // This is typically called internally by getPlatform()\n * const platform = createRemoteClient('http://localhost:3001', 'dev-tenant');\n * \n * // The returned platform works the same as the native one\n * await platform.env.KV.cache.put('key', 'value');\n * await platform.env.DB.insertOne('users', { name: 'John' });\n * await platform.env.STORAGE.put('file.pdf', pdfData);\n * ```\n */\nexport function createRemoteClient(baseUrl: string, tenant: string) {\n const headers = {\n 'Content-Type': 'application/json',\n 'X-Tenant-Id': tenant,\n };\n\n // Create KV namespaces proxy that dynamically creates namespace instances\n const kvProxy = new Proxy({} as Record<string, KvNamespace>, {\n get(_, namespace: string) {\n return new RemoteKvNamespace(baseUrl, namespace, headers);\n }\n });\n\n const db = new RemoteDatabase(baseUrl, headers);\n const storage = new RemoteStorage(baseUrl, headers);\n\n return {\n env: {\n KV: kvProxy,\n DB: db,\n STORAGE: storage,\n }\n };\n}","/**\n * @fileoverview Maravilla Platform SDK\n * \n * This package provides the main interface for accessing Maravilla runtime services\n * including Key-Value storage and Database operations. It automatically detects the\n * runtime environment and provides the appropriate implementation.\n * \n * ## Environment Detection\n * \n * The SDK automatically detects and adapts to different environments:\n * - **Production**: Uses native Maravilla runtime APIs\n * - **Development**: Connects to development server via HTTP\n * - **Testing**: Can be mocked or use development server\n * \n * ## Key Features\n * \n * - **KV Storage**: Cloudflare Workers KV-compatible API for key-value operations\n * - **Database**: MongoDB-style document database operations\n * - **Multi-tenancy**: Built-in tenant isolation and support\n * - **TypeScript**: Fully typed APIs with comprehensive JSDoc comments\n * - **Development-friendly**: Seamless development server integration\n * \n * @example\n * ```typescript\n * import { getPlatform } from '@maravilla/platform';\n * \n * const platform = getPlatform();\n * \n * // KV operations\n * await platform.env.KV.cache.put('user:123', { name: 'John' });\n * const user = await platform.env.KV.cache.get('user:123');\n * \n * // Database operations\n * const userId = await platform.env.DB.insertOne('users', {\n * name: 'John Doe',\n * email: 'john@example.com'\n * });\n * \n * const users = await platform.env.DB.find('users', { active: true });\n * ```\n * \n * @author Maravilla Team\n * @since 1.0.0\n */\n\nimport type { Platform } from './types.js';\nimport { createRemoteClient } from './remote-client.js';\n\nexport * from './types.js';\n\n/**\n * Global platform instance injected by Maravilla runtime or development tools.\n * This should not be accessed directly - use getPlatform() instead.\n * \n * @internal\n */\n\ndeclare global {\n var __maravilla_platform: Platform | undefined;\n var platform: Platform | undefined;\n}\n\nlet cachedPlatform: Platform | null = null;\n\n/**\n * Get the platform instance. This will:\n * 1. Check if running in Maravilla runtime (global.platform exists)\n * 2. Check if a platform was injected via vite plugin or hooks\n * 3. Fall back to remote client for development\n * \n * The platform provides access to KV storage and database operations,\n * with automatic environment detection for seamless development and production.\n * \n * @param options - Optional configuration for development mode\n * @param options.devServerUrl - URL of the development server (defaults to MARAVILLA_DEV_SERVER env var or http://localhost:3001)\n * @param options.tenant - Tenant identifier for multi-tenancy (defaults to MARAVILLA_TENANT env var or 'dev-tenant')\n * @returns Platform instance with access to KV and database services\n * \n * @example\n * ```typescript\n * import { getPlatform } from '@maravilla/platform';\n * \n * // Basic usage (auto-detects environment)\n * const platform = getPlatform();\n * \n * // Development with custom server\n * const platform = getPlatform({\n * devServerUrl: 'http://localhost:3001',\n * tenant: 'my-app'\n * });\n * \n * // Use KV storage\n * await platform.env.KV.cache.put('user:123', { name: 'John' });\n * const user = await platform.env.KV.cache.get('user:123');\n * \n * // Use database\n * const userId = await platform.env.DB.insertOne('users', {\n * name: 'John Doe',\n * email: 'john@example.com'\n * });\n * ```\n */\nexport function getPlatform(options?: {\n devServerUrl?: string;\n tenant?: string;\n}): Platform {\n // Return cached if available\n if (cachedPlatform) {\n return cachedPlatform;\n }\n\n // 1. Check if we're in the real Maravilla runtime\n if (typeof globalThis !== 'undefined') {\n // Check for native platform (in production runtime)\n if (globalThis.platform) {\n console.log('[platform] Using native Maravilla platform');\n cachedPlatform = globalThis.platform;\n return cachedPlatform;\n }\n\n // Check for injected platform (from vite plugin or hooks)\n if (globalThis.__maravilla_platform) {\n console.log('[platform] Using injected platform');\n cachedPlatform = globalThis.__maravilla_platform;\n return cachedPlatform;\n }\n }\n\n // 2. Fall back to remote client for development\n const devServerUrl = options?.devServerUrl || process.env.MARAVILLA_DEV_SERVER || 'http://localhost:3001';\n const tenant = options?.tenant || process.env.MARAVILLA_TENANT || 'dev-tenant';\n \n console.log(`[platform] Creating remote client for ${devServerUrl}`);\n cachedPlatform = createRemoteClient(devServerUrl, tenant);\n \n // Cache it globally for other modules\n if (typeof globalThis !== 'undefined') {\n globalThis.__maravilla_platform = cachedPlatform;\n }\n \n return cachedPlatform;\n}\n\n/**\n * Clear the cached platform instance (useful for testing).\n * \n * This function resets the internal platform cache and clears any globally\n * injected platform instances. Subsequent calls to getPlatform() will\n * re-initialize the platform based on the current environment.\n * \n * @example\n * ```typescript\n * import { clearPlatformCache, getPlatform } from '@maravilla/platform';\n * \n * // In tests, clear cache between test cases\n * afterEach(() => {\n * clearPlatformCache();\n * });\n * \n * // Or when switching between different environments\n * clearPlatformCache();\n * const newPlatform = getPlatform({ devServerUrl: 'http://localhost:3002' });\n * ```\n */\nexport function clearPlatformCache(): void {\n cachedPlatform = null;\n if (typeof globalThis !== 'undefined') {\n globalThis.__maravilla_platform = undefined;\n }\n}"],"mappings":";AAQA,IAAM,oBAAN,MAA+C;AAAA,EAC7C,YACU,SACA,WACA,SACR;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,uBAAuB;AAAA,EACpC;AAEA,SAAO;AACT;AAuBO,SAAS,qBAA2B;AACzC,mBAAiB;AACjB,MAAI,OAAO,eAAe,aAAa;AACrC,eAAW,uBAAuB;AAAA,EACpC;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/remote-client.ts","../src/ren.ts","../src/index.ts"],"sourcesContent":["import type { KvNamespace, KvListResult, Database, DbFindOptions, Storage } from './types.js';\n\n/**\n * Remote KV namespace implementation that communicates with a development server.\n * This class provides the KV interface by making HTTP requests to the dev server.\n * \n * @internal\n */\nclass RemoteKvNamespace implements KvNamespace {\n constructor(\n private baseUrl: string,\n private namespace: string,\n private headers: Record<string, string>\n ) {}\n\n /**\n * Internal method for making HTTP requests to the dev server.\n * Handles error responses and authentication headers.\n * \n * @internal\n */\n private async fetch(url: string, options: RequestInit = {}) {\n const response = await fetch(url, {\n ...options,\n headers: { ...this.headers, ...options.headers },\n });\n\n if (!response.ok && response.status !== 404) {\n const error = await response.text();\n throw new Error(`Platform API error: ${response.status} - ${error}`);\n }\n\n return response;\n }\n\n async get(key: string): Promise<any> {\n const response = await this.fetch(`${this.baseUrl}/api/kv/${this.namespace}/${key}`);\n if (response.status === 404) return null;\n return response.json();\n }\n\n async put(key: string, value: any, options?: { expirationTtl?: number }): Promise<void> {\n const headers: Record<string, string> = {};\n if (options?.expirationTtl) {\n headers['X-TTL'] = options.expirationTtl.toString();\n }\n\n await this.fetch(`${this.baseUrl}/api/kv/${this.namespace}/${key}`, {\n method: 'PUT',\n headers,\n body: JSON.stringify(value),\n });\n }\n\n async delete(key: string): Promise<void> {\n await this.fetch(`${this.baseUrl}/api/kv/${this.namespace}/${key}`, {\n method: 'DELETE',\n });\n }\n\n async list(options?: { prefix?: string; limit?: number; cursor?: string }): Promise<KvListResult> {\n const response = await this.fetch(`${this.baseUrl}/api/kv/${this.namespace}`, {\n method: 'POST',\n body: JSON.stringify(options || {}),\n });\n const data = await response.json() as any;\n return {\n keys: data.result || [],\n list_complete: !data.result_info?.cursor,\n cursor: data.result_info?.cursor,\n };\n }\n}\n\n/**\n * Remote Database implementation that communicates with a development server.\n * This class provides the Database interface by making HTTP requests to the dev server.\n * \n * @internal\n */\nclass RemoteDatabase implements Database {\n constructor(\n private baseUrl: string,\n private headers: Record<string, string>\n ) {}\n\n /**\n * Internal method for making HTTP requests to the dev server.\n * Handles error responses and authentication headers.\n * \n * @internal\n */\n private async fetch(url: string, options: RequestInit = {}) {\n const response = await fetch(url, {\n ...options,\n headers: { ...this.headers, ...options.headers },\n });\n\n if (!response.ok && response.status !== 404) {\n const error = await response.text();\n throw new Error(`Platform API error: ${response.status} - ${error}`);\n }\n\n return response;\n }\n\n async find(collection: string, filter: any = {}, options: DbFindOptions = {}): Promise<any[]> {\n const response = await this.fetch(`${this.baseUrl}/api/db/${collection}`, {\n method: 'POST',\n body: JSON.stringify({ filter, options }),\n });\n return response.json() as Promise<any[]>;\n }\n\n async findOne(collection: string, filter: any): Promise<any | null> {\n const response = await this.fetch(`${this.baseUrl}/api/db/${collection}/findOne`, {\n method: 'POST',\n body: JSON.stringify(filter),\n });\n if (response.status === 404) return null;\n return response.json();\n }\n\n async insertOne(collection: string, document: any): Promise<string> {\n const response = await this.fetch(`${this.baseUrl}/api/db/${collection}`, {\n method: 'PUT',\n body: JSON.stringify(document),\n });\n const result = await response.json() as any;\n return result.id;\n }\n\n async updateOne(collection: string, filter: any, update: any): Promise<{ modified: number }> {\n const response = await this.fetch(`${this.baseUrl}/api/db/${collection}/update`, {\n method: 'POST',\n body: JSON.stringify({ filter, update }),\n });\n return response.json() as Promise<{ modified: number }>;\n }\n\n async deleteOne(collection: string, filter: any): Promise<{ deleted: number }> {\n const response = await this.fetch(`${this.baseUrl}/api/db/${collection}/delete`, {\n method: 'DELETE',\n body: JSON.stringify(filter),\n });\n return response.json() as Promise<{ deleted: number }>;\n }\n\n async deleteMany(collection: string, filter: any): Promise<{ deleted: number }> {\n // For now, deleteMany is the same as deleteOne in the remote client\n // This would need to be implemented properly in the dev server\n return this.deleteOne(collection, filter);\n }\n}\n\n/**\n * Remote Storage implementation that communicates with a development server.\n * This class provides the Storage interface by making HTTP requests to the dev server.\n * \n * @internal\n */\nclass RemoteStorage implements Storage {\n constructor(\n private baseUrl: string,\n private headers: Record<string, string>\n ) {}\n\n /**\n * Internal method for making HTTP requests to the dev server.\n * Handles error responses and authentication headers.\n * \n * @internal\n */\n private async fetch(url: string, options: RequestInit = {}) {\n const response = await fetch(url, {\n ...options,\n headers: { ...this.headers, ...options.headers },\n });\n\n if (!response.ok && response.status !== 404) {\n const error = await response.text();\n throw new Error(`Platform API error: ${response.status} - ${error}`);\n }\n\n return response;\n }\n\n async generateUploadUrl(key: string, contentType: string, options?: { sizeLimit?: number }): Promise<{\n url: string;\n method: string;\n headers: Record<string, string>;\n expiresIn: number;\n }> {\n // For development, return a direct upload URL to the dev server\n // The dev server supports PUT directly to /api/storage/{key}\n return {\n url: `${this.baseUrl}/api/storage/${encodeURIComponent(key)}`,\n method: 'PUT',\n headers: {\n 'Content-Type': contentType,\n ...this.headers, // Include tenant headers\n },\n expiresIn: 3600, // 1 hour\n };\n }\n\n async generateDownloadUrl(key: string, options?: { expiresIn?: number }): Promise<{\n url: string;\n method: string;\n headers: Record<string, string>;\n expiresIn: number;\n }> {\n // For development, return a direct download URL to the dev server\n // In production, this would call the actual storage service for presigned URLs\n return {\n url: `${this.baseUrl}/api/storage/${encodeURIComponent(key)}`,\n method: 'GET',\n headers: {},\n expiresIn: options?.expiresIn || 3600, // Default 1 hour\n };\n }\n\n async get(key: string): Promise<Uint8Array | null> {\n const response = await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`);\n if (response.status === 404) return null;\n const arrayBuffer = await response.arrayBuffer();\n return new Uint8Array(arrayBuffer);\n }\n\n async put(key: string, data: Uint8Array | string, metadata?: any): Promise<void> {\n // Convert string to Uint8Array if needed\n const bodyData = typeof data === 'string' \n ? new TextEncoder().encode(data)\n : data;\n\n await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`, {\n method: 'PUT',\n headers: metadata ? { 'X-Metadata': JSON.stringify(metadata) } : {},\n // Cast because TypeScript's lib.dom.d.ts BodyInit union sometimes misses Uint8Array\n body: bodyData as any,\n });\n }\n\n async putStream(key: string, source: any, metadata?: any): Promise<void> {\n // If it's a Blob we can send directly\n if (typeof Blob !== 'undefined' && source instanceof Blob) {\n await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`, {\n method: 'PUT',\n headers: {\n ...(metadata ? { 'X-Metadata': JSON.stringify(metadata) } : {}),\n 'Content-Type': source.type || 'application/octet-stream'\n },\n body: source as any,\n });\n return;\n }\n\n // ReadableStream\n if (source && typeof source.getReader === 'function') {\n await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`, {\n method: 'PUT',\n headers: metadata ? { 'X-Metadata': JSON.stringify(metadata) } : {},\n body: source as any,\n });\n return;\n }\n\n // Async iterable -> wrap in ReadableStream\n if (Symbol.asyncIterator in Object(source ?? {})) {\n const asyncIt = source as AsyncIterable<any>;\n const stream = new ReadableStream({\n async pull(controller) {\n const { value, done } = await asyncIt[Symbol.asyncIterator]().next();\n if (done) { controller.close(); return; }\n controller.enqueue(RemoteStorage.normalizeChunk(value));\n }\n });\n await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`, {\n method: 'PUT',\n headers: metadata ? { 'X-Metadata': JSON.stringify(metadata) } : {},\n body: stream as any,\n });\n return;\n }\n\n // Synchronous iterable\n if (Symbol.iterator in Object(source ?? {})) {\n const it = (source as Iterable<any>)[Symbol.iterator]();\n const stream = new ReadableStream({\n pull(controller) {\n const res = it.next();\n if (res.done) { controller.close(); return; }\n controller.enqueue(RemoteStorage.normalizeChunk(res.value));\n }\n });\n await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`, {\n method: 'PUT',\n headers: metadata ? { 'X-Metadata': JSON.stringify(metadata) } : {},\n body: stream as any,\n });\n return;\n }\n\n // Fallback: primitive/string/Uint8Array/ArrayBuffer\n await this.put(key, RemoteStorage.normalizeChunk(source), metadata);\n }\n private static normalizeChunk(c: any): Uint8Array {\n if (c == null) return new Uint8Array();\n if (typeof c === 'string') return new TextEncoder().encode(c);\n if (c instanceof Uint8Array) return c;\n if (c instanceof ArrayBuffer) return new Uint8Array(c);\n if (Array.isArray(c)) return Uint8Array.from(c);\n throw new Error('Unsupported chunk type in putStream');\n }\n async delete(key: string): Promise<void> {\n await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}`, {\n method: 'DELETE',\n });\n }\n\n async list(options?: { prefix?: string; limit?: number }): Promise<Array<{\n key: string;\n size: number;\n lastModified: string;\n metadata?: any;\n }>> {\n const params = new URLSearchParams();\n if (options?.prefix) params.set('prefix', options.prefix);\n if (options?.limit) params.set('limit', options.limit.toString());\n\n const response = await this.fetch(`${this.baseUrl}/api/storage?${params}`);\n return response.json();\n }\n\n async getMetadata(key: string): Promise<{\n size: number;\n contentType?: string;\n lastModified: string;\n metadata?: any;\n } | null> {\n const response = await this.fetch(`${this.baseUrl}/api/storage/${encodeURIComponent(key)}/metadata`);\n if (response.status === 404) return null;\n return response.json();\n }\n}\n\n/**\n * Create a remote platform client for development environments.\n * \n * This function creates a platform instance that communicates with a development\n * server over HTTP. It's used internally by getPlatform() when running in development\n * mode and no native platform is available.\n * \n * @param baseUrl - The base URL of the development server\n * @param tenant - The tenant identifier for multi-tenancy support\n * @returns A platform instance that proxies requests to the development server\n * \n * @internal\n * \n * @example\n * ```typescript\n * // This is typically called internally by getPlatform()\n * const platform = createRemoteClient('http://localhost:3001', 'dev-tenant');\n * \n * // The returned platform works the same as the native one\n * await platform.env.KV.cache.put('key', 'value');\n * await platform.env.DB.insertOne('users', { name: 'John' });\n * await platform.env.STORAGE.put('file.pdf', pdfData);\n * ```\n */\nexport function createRemoteClient(baseUrl: string, tenant: string) {\n const headers = {\n 'Content-Type': 'application/json',\n 'X-Tenant-Id': tenant,\n };\n\n // Create KV namespaces proxy that dynamically creates namespace instances\n const kvProxy = new Proxy({} as Record<string, KvNamespace>, {\n get(_, namespace: string) {\n return new RemoteKvNamespace(baseUrl, namespace, headers);\n }\n });\n\n const db = new RemoteDatabase(baseUrl, headers);\n const storage = new RemoteStorage(baseUrl, headers);\n\n return {\n env: {\n KV: kvProxy,\n DB: db,\n STORAGE: storage,\n }\n };\n}","// REN (Resource Event Notifications) client utilities\n// Thin SSE client for /api/maravilla/ren\n// Reconnect w/ basic backoff; consumer filters self vs others using evt.src\n\nexport interface RenEvent {\n t: string; // event type e.g. storage.object.created\n r: string; // resource domain e.g. storage, runtime\n k?: string; // key (object key, deployment key, etc.)\n v?: string; // version / etag\n ts?: number; // timestamp (ms)\n src?: string;// origin client id (if set on mutation request)\n ns?: string; // future namespace / tenant\n [extra: string]: any;\n}\n\nexport interface RenClientOptions {\n endpoint?: string; // override (default /api/maravilla/ren)\n subscriptions?: string[]; // resource filters, ['*'] means all\n clientId?: string; // supply existing client id\n autoReconnect?: boolean; // default true\n maxBackoffMs?: number; // default 15000\n debug?: boolean; // enable console debug logging\n}\n\ntype Listener = (event: RenEvent) => void;\n\nexport class RenClient {\n private endpoint: string;\n private subs: string[];\n private clientId: string;\n private listeners = new Set<Listener>();\n private es: EventSource | null = null;\n private closed = false;\n private attempt = 0;\n private autoReconnect: boolean;\n private maxBackoff: number;\n private debug: boolean;\n\n constructor(opts: RenClientOptions = {}) {\n this.endpoint = opts.endpoint || this.detectEndpoint();\n this.subs = (opts.subscriptions && opts.subscriptions.length) ? opts.subscriptions : ['*'];\n this.clientId = opts.clientId || getOrCreateClientId();\n this.autoReconnect = opts.autoReconnect !== false;\n this.maxBackoff = opts.maxBackoffMs ?? 15000;\n this.debug = !!opts.debug || (typeof localStorage !== 'undefined' && localStorage.getItem('REN_DEBUG') === '1');\n this.connect();\n }\n\n private detectEndpoint(): string {\n console.log('[REN detectEndpoint] Starting detection...');\n console.log('[REN detectEndpoint] globalThis:', typeof globalThis);\n console.log('[REN detectEndpoint] globalThis.platform:', (globalThis as any)?.platform);\n console.log('[REN detectEndpoint] globalThis.__maravilla_platform:', (globalThis as any)?.__maravilla_platform);\n console.log('[REN detectEndpoint] window:', typeof window);\n console.log('[REN detectEndpoint] window.location:', typeof window !== 'undefined' ? window.location.href : 'N/A');\n\n // Check if we're in production runtime (has native platform)\n if (typeof globalThis !== 'undefined' && (globalThis as any).platform) {\n console.log('[REN detectEndpoint] Detected production runtime, using relative endpoint');\n return '/api/maravilla/ren';\n }\n\n // Check if we're running on dev server (port 5173 is Vite dev server)\n if (typeof window !== 'undefined' && window.location.port === '5173') {\n // We're in development mode with Vite dev server\n const devServerUrl = `http://${window.location.hostname}:3001`;\n console.log('[REN detectEndpoint] Detected Vite dev server (port 5173), using dev server:', devServerUrl);\n return `${devServerUrl}/api/maravilla/ren`;\n }\n\n // Check if we're in development with injected platform\n if (typeof globalThis !== 'undefined' && (globalThis as any).__maravilla_platform) {\n // In development, use the dev server URL\n let devServerUrl = 'http://localhost:3001';\n // Also check window location to use same host in browser\n if (typeof window !== 'undefined' && window.location.hostname !== 'localhost') {\n devServerUrl = `http://${window.location.hostname}:3001`;\n }\n console.log('[REN detectEndpoint] Detected injected platform, using dev server:', devServerUrl);\n return `${devServerUrl}/api/maravilla/ren`;\n }\n\n // Default to relative URL (works in preview mode and production)\n console.log('[REN detectEndpoint] Using default relative endpoint (preview/production mode)');\n return '/api/maravilla/ren';\n }\n\n private log(...args: any[]) { if (this.debug) console.debug('[RenClient]', ...args); }\n\n private buildUrl(): string {\n const s = (this.subs.length === 1 && this.subs[0] === '*') ? '*' : this.subs.join(',');\n const qs = new URLSearchParams({ cid: this.clientId, s });\n return `${this.endpoint}?${qs.toString()}`;\n }\n\n private connect() {\n const url = this.buildUrl();\n this.log('connecting', { url });\n this.es = new EventSource(url);\n this.closed = false;\n\n const forward = (e: MessageEvent) => {\n try {\n const evt: RenEvent = JSON.parse(e.data);\n this.log('event', evt);\n this.listeners.forEach(l => l(evt));\n } catch (err) {\n this.log('malformed event data', e.data, err);\n }\n };\n\n // Attach generic message handler for events without a specific event: type\n this.es.onmessage = forward;\n\n // Register listeners for all known event types\n // The browser EventSource API does NOT call onmessage for events with an event: field\n // We must explicitly register listeners for each event type we want to handle\n const knownEventTypes = [\n // Database events\n 'db.document.created',\n 'db.document.updated',\n 'db.document.deleted',\n // KV events\n 'kv.put',\n 'kv.delete',\n 'kv.expired',\n // Storage events\n 'storage.object.created',\n 'storage.object.updated',\n 'storage.object.deleted',\n // Runtime events\n 'runtime.snapshot.ready',\n 'runtime.worker.started',\n 'runtime.worker.stopped',\n // Meta events\n 'ren.meta'\n ];\n // Use the more general addEventListener signature to avoid TypeScript issues\n knownEventTypes.forEach(k => this.es?.addEventListener(k, forward as EventListener));\n\n this.es.onerror = (ev) => {\n this.log('error', ev);\n if (this.closed) return;\n this.es?.close();\n if (!this.autoReconnect) return;\n const delay = Math.min(1000 * Math.pow(2, this.attempt++), this.maxBackoff);\n this.log('reconnecting in', delay, 'ms');\n setTimeout(() => this.connect(), delay);\n };\n\n this.es.onopen = () => { this.attempt = 0; this.log('open'); };\n }\n\n on(listener: Listener): () => void {\n this.listeners.add(listener);\n this.log('listener added; total', this.listeners.size);\n return () => { this.listeners.delete(listener); this.log('listener removed; total', this.listeners.size); };\n }\n\n getClientId() { return this.clientId; }\n\n close() {\n this.closed = true;\n this.es?.close();\n this.log('closed');\n }\n}\n\nexport function getOrCreateClientId(storage?: Storage): string {\n if (!storage) {\n storage = (typeof window !== 'undefined' && window.localStorage) ? window.localStorage : (typeof globalThis !== 'undefined' && (globalThis as any).localStorage) ? (globalThis as any).localStorage : undefined as any;\n if (!storage) {\n // Return a random ID if no storage is available\n return (globalThis.crypto?.randomUUID?.() || randomFallback());\n }\n }\n const key = 'maravillaClientId';\n let id = storage.getItem(key);\n if (!id) {\n id = (globalThis.crypto?.randomUUID?.() || randomFallback());\n try { storage.setItem(key, id); } catch {} // ignore quota errors\n }\n return id;\n}\n\nfunction randomFallback(): string {\n // Very small UUID-ish fallback\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n// Helper to add client header to fetch\nexport async function renFetch(input: string | URL | Request, init: RequestInit = {}, clientId?: string) {\n const cid = clientId || getOrCreateClientId();\n const headers = new Headers(init.headers || {});\n headers.set('X-Ren-Client', cid);\n return fetch(input, { ...init, headers });\n}\n\n// Storage convenience wrappers (example)\nexport async function storageUpload(path: string, file: Blob | File, clientId?: string) {\n const res = await renFetch(`/api/storage/upload?path=${encodeURIComponent(path)}`, { method: 'POST', body: file }, clientId);\n if (!res.ok) throw new Error('upload failed');\n return res.json().catch(() => ({}));\n}\n\nexport async function storageDelete(path: string, clientId?: string) {\n const res = await renFetch(`/api/storage/delete?path=${encodeURIComponent(path)}`, { method: 'DELETE' }, clientId);\n if (!res.ok) throw new Error('delete failed');\n return res.json().catch(() => ({}));\n}\n","/**\n * @fileoverview Maravilla Platform SDK\n * \n * This package provides the main interface for accessing Maravilla runtime services\n * including Key-Value storage and Database operations. It automatically detects the\n * runtime environment and provides the appropriate implementation.\n * \n * ## Environment Detection\n * \n * The SDK automatically detects and adapts to different environments:\n * - **Production**: Uses native Maravilla runtime APIs\n * - **Development**: Connects to development server via HTTP\n * - **Testing**: Can be mocked or use development server\n * \n * ## Key Features\n * \n * - **KV Storage**: Cloudflare Workers KV-compatible API for key-value operations\n * - **Database**: MongoDB-style document database operations\n * - **Multi-tenancy**: Built-in tenant isolation and support\n * - **TypeScript**: Fully typed APIs with comprehensive JSDoc comments\n * - **Development-friendly**: Seamless development server integration\n * \n * @example\n * ```typescript\n * import { getPlatform } from '@maravilla/platform';\n * \n * const platform = getPlatform();\n * \n * // KV operations\n * await platform.env.KV.cache.put('user:123', { name: 'John' });\n * const user = await platform.env.KV.cache.get('user:123');\n * \n * // Database operations\n * const userId = await platform.env.DB.insertOne('users', {\n * name: 'John Doe',\n * email: 'john@example.com'\n * });\n * \n * const users = await platform.env.DB.find('users', { active: true });\n * ```\n * \n * @author Maravilla Team\n * @since 1.0.0\n */\n\nimport type { Platform } from './types.js';\nimport { createRemoteClient } from './remote-client.js';\n\nexport * from './types.js';\nexport * from './ren.js';\n\n/**\n * Global platform instance injected by Maravilla runtime or development tools.\n * This should not be accessed directly - use getPlatform() instead.\n * \n * @internal\n */\n\ndeclare global {\n var __maravilla_platform: Platform | undefined;\n var platform: Platform | undefined;\n}\n\nlet cachedPlatform: Platform | null = null;\n\n/**\n * Get the platform instance. This will:\n * 1. Check if running in Maravilla runtime (global.platform exists)\n * 2. Check if a platform was injected via vite plugin or hooks\n * 3. Fall back to remote client for development\n * \n * The platform provides access to KV storage and database operations,\n * with automatic environment detection for seamless development and production.\n * \n * @param options - Optional configuration for development mode\n * @param options.devServerUrl - URL of the development server (defaults to MARAVILLA_DEV_SERVER env var or http://localhost:3001)\n * @param options.tenant - Tenant identifier for multi-tenancy (defaults to MARAVILLA_TENANT env var or 'dev-tenant')\n * @returns Platform instance with access to KV and database services\n * \n * @example\n * ```typescript\n * import { getPlatform } from '@maravilla/platform';\n * \n * // Basic usage (auto-detects environment)\n * const platform = getPlatform();\n * \n * // Development with custom server\n * const platform = getPlatform({\n * devServerUrl: 'http://localhost:3001',\n * tenant: 'my-app'\n * });\n * \n * // Use KV storage\n * await platform.env.KV.cache.put('user:123', { name: 'John' });\n * const user = await platform.env.KV.cache.get('user:123');\n * \n * // Use database\n * const userId = await platform.env.DB.insertOne('users', {\n * name: 'John Doe',\n * email: 'john@example.com'\n * });\n * ```\n */\nexport function getPlatform(options?: {\n devServerUrl?: string;\n tenant?: string;\n}): Platform {\n // Return cached if available\n if (cachedPlatform) {\n return cachedPlatform;\n }\n\n // 1. Check if we're in the real Maravilla runtime\n if (typeof globalThis !== 'undefined') {\n // Check for native platform (in production runtime)\n if (globalThis.platform) {\n console.log('[platform] Using native Maravilla platform');\n cachedPlatform = globalThis.platform;\n return cachedPlatform;\n }\n\n // Check for injected platform (from vite plugin or hooks)\n if (globalThis.__maravilla_platform) {\n console.log('[platform] Using injected platform');\n cachedPlatform = globalThis.__maravilla_platform;\n return cachedPlatform;\n }\n }\n\n // 2. Fall back to remote client for development\n const devServerUrl = options?.devServerUrl || process.env.MARAVILLA_DEV_SERVER || 'http://localhost:3001';\n const tenant = options?.tenant || process.env.MARAVILLA_TENANT || 'dev-tenant';\n \n console.log(`[platform] Creating remote client for ${devServerUrl}`);\n cachedPlatform = createRemoteClient(devServerUrl, tenant);\n \n // Cache it globally for other modules\n if (typeof globalThis !== 'undefined') {\n globalThis.__maravilla_platform = cachedPlatform;\n }\n \n return cachedPlatform;\n}\n\n/**\n * Clear the cached platform instance (useful for testing).\n * \n * This function resets the internal platform cache and clears any globally\n * injected platform instances. Subsequent calls to getPlatform() will\n * re-initialize the platform based on the current environment.\n * \n * @example\n * ```typescript\n * import { clearPlatformCache, getPlatform } from '@maravilla/platform';\n * \n * // In tests, clear cache between test cases\n * afterEach(() => {\n * clearPlatformCache();\n * });\n * \n * // Or when switching between different environments\n * clearPlatformCache();\n * const newPlatform = getPlatform({ devServerUrl: 'http://localhost:3002' });\n * ```\n */\nexport function clearPlatformCache(): void {\n cachedPlatform = null;\n if (typeof globalThis !== 'undefined') {\n globalThis.__maravilla_platform = undefined;\n }\n}"],"mappings":";AAQA,IAAM,oBAAN,MAA+C;AAAA,EAC7C,YACU,SACA,WACA,SACR;AAHQ;AACA;AACA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQH,MAAc,MAAM,KAAa,UAAuB,CAAC,GAAG;AAC1D,UAAM,WAAW,MAAM,MAAM,KAAK;AAAA,MAChC,GAAG;AAAA,MACH,SAAS,EAAE,GAAG,KAAK,SAAS,GAAG,QAAQ,QAAQ;AAAA,IACjD,CAAC;AAED,QAAI,CAAC,SAAS,MAAM,SAAS,WAAW,KAAK;AAC3C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,IAAI,EAAE,QAAQ,SAAS,GAAG,QAAQ;AACjH,MAAI,CAAC,IAAI,GAAI,OAAM,IAAI,MAAM,eAAe;AAC5C,SAAO,IAAI,KAAK,EAAE,MAAM,OAAO,CAAC,EAAE;AACpC;;;ACtJA,IAAI,iBAAkC;AAwC/B,SAAS,YAAY,SAGf;AAEX,MAAI,gBAAgB;AAClB,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,eAAe,aAAa;AAErC,QAAI,WAAW,UAAU;AACvB,cAAQ,IAAI,4CAA4C;AACxD,uBAAiB,WAAW;AAC5B,aAAO;AAAA,IACT;AAGA,QAAI,WAAW,sBAAsB;AACnC,cAAQ,IAAI,oCAAoC;AAChD,uBAAiB,WAAW;AAC5B,aAAO;AAAA,IACT;AAAA,EACF;AAGA,QAAM,eAAe,SAAS,gBAAgB,QAAQ,IAAI,wBAAwB;AAClF,QAAM,SAAS,SAAS,UAAU,QAAQ,IAAI,oBAAoB;AAElE,UAAQ,IAAI,yCAAyC,YAAY,EAAE;AACnE,mBAAiB,mBAAmB,cAAc,MAAM;AAGxD,MAAI,OAAO,eAAe,aAAa;AACrC,eAAW,uBAAuB;AAAA,EACpC;AAEA,SAAO;AACT;AAuBO,SAAS,qBAA2B;AACzC,mBAAiB;AACjB,MAAI,OAAO,eAAe,aAAa;AACrC,eAAW,uBAAuB;AAAA,EACpC;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maravilla-labs/platform",
3
- "version": "0.1.20",
3
+ "version": "0.1.21",
4
4
  "description": "Universal platform client for Maravilla runtime",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/src/index.ts CHANGED
@@ -47,6 +47,7 @@ import type { Platform } from './types.js';
47
47
  import { createRemoteClient } from './remote-client.js';
48
48
 
49
49
  export * from './types.js';
50
+ export * from './ren.js';
50
51
 
51
52
  /**
52
53
  * Global platform instance injected by Maravilla runtime or development tools.
package/src/ren.ts ADDED
@@ -0,0 +1,214 @@
1
+ // REN (Resource Event Notifications) client utilities
2
+ // Thin SSE client for /api/maravilla/ren
3
+ // Reconnect w/ basic backoff; consumer filters self vs others using evt.src
4
+
5
+ export interface RenEvent {
6
+ t: string; // event type e.g. storage.object.created
7
+ r: string; // resource domain e.g. storage, runtime
8
+ k?: string; // key (object key, deployment key, etc.)
9
+ v?: string; // version / etag
10
+ ts?: number; // timestamp (ms)
11
+ src?: string;// origin client id (if set on mutation request)
12
+ ns?: string; // future namespace / tenant
13
+ [extra: string]: any;
14
+ }
15
+
16
+ export interface RenClientOptions {
17
+ endpoint?: string; // override (default /api/maravilla/ren)
18
+ subscriptions?: string[]; // resource filters, ['*'] means all
19
+ clientId?: string; // supply existing client id
20
+ autoReconnect?: boolean; // default true
21
+ maxBackoffMs?: number; // default 15000
22
+ debug?: boolean; // enable console debug logging
23
+ }
24
+
25
+ type Listener = (event: RenEvent) => void;
26
+
27
+ export class RenClient {
28
+ private endpoint: string;
29
+ private subs: string[];
30
+ private clientId: string;
31
+ private listeners = new Set<Listener>();
32
+ private es: EventSource | null = null;
33
+ private closed = false;
34
+ private attempt = 0;
35
+ private autoReconnect: boolean;
36
+ private maxBackoff: number;
37
+ private debug: boolean;
38
+
39
+ constructor(opts: RenClientOptions = {}) {
40
+ this.endpoint = opts.endpoint || this.detectEndpoint();
41
+ this.subs = (opts.subscriptions && opts.subscriptions.length) ? opts.subscriptions : ['*'];
42
+ this.clientId = opts.clientId || getOrCreateClientId();
43
+ this.autoReconnect = opts.autoReconnect !== false;
44
+ this.maxBackoff = opts.maxBackoffMs ?? 15000;
45
+ this.debug = !!opts.debug || (typeof localStorage !== 'undefined' && localStorage.getItem('REN_DEBUG') === '1');
46
+ this.connect();
47
+ }
48
+
49
+ private detectEndpoint(): string {
50
+ console.log('[REN detectEndpoint] Starting detection...');
51
+ console.log('[REN detectEndpoint] globalThis:', typeof globalThis);
52
+ console.log('[REN detectEndpoint] globalThis.platform:', (globalThis as any)?.platform);
53
+ console.log('[REN detectEndpoint] globalThis.__maravilla_platform:', (globalThis as any)?.__maravilla_platform);
54
+ console.log('[REN detectEndpoint] window:', typeof window);
55
+ console.log('[REN detectEndpoint] window.location:', typeof window !== 'undefined' ? window.location.href : 'N/A');
56
+
57
+ // Check if we're in production runtime (has native platform)
58
+ if (typeof globalThis !== 'undefined' && (globalThis as any).platform) {
59
+ console.log('[REN detectEndpoint] Detected production runtime, using relative endpoint');
60
+ return '/api/maravilla/ren';
61
+ }
62
+
63
+ // Check if we're running on dev server (port 5173 is Vite dev server)
64
+ if (typeof window !== 'undefined' && window.location.port === '5173') {
65
+ // We're in development mode with Vite dev server
66
+ const devServerUrl = `http://${window.location.hostname}:3001`;
67
+ console.log('[REN detectEndpoint] Detected Vite dev server (port 5173), using dev server:', devServerUrl);
68
+ return `${devServerUrl}/api/maravilla/ren`;
69
+ }
70
+
71
+ // Check if we're in development with injected platform
72
+ if (typeof globalThis !== 'undefined' && (globalThis as any).__maravilla_platform) {
73
+ // In development, use the dev server URL
74
+ let devServerUrl = 'http://localhost:3001';
75
+ // Also check window location to use same host in browser
76
+ if (typeof window !== 'undefined' && window.location.hostname !== 'localhost') {
77
+ devServerUrl = `http://${window.location.hostname}:3001`;
78
+ }
79
+ console.log('[REN detectEndpoint] Detected injected platform, using dev server:', devServerUrl);
80
+ return `${devServerUrl}/api/maravilla/ren`;
81
+ }
82
+
83
+ // Default to relative URL (works in preview mode and production)
84
+ console.log('[REN detectEndpoint] Using default relative endpoint (preview/production mode)');
85
+ return '/api/maravilla/ren';
86
+ }
87
+
88
+ private log(...args: any[]) { if (this.debug) console.debug('[RenClient]', ...args); }
89
+
90
+ private buildUrl(): string {
91
+ const s = (this.subs.length === 1 && this.subs[0] === '*') ? '*' : this.subs.join(',');
92
+ const qs = new URLSearchParams({ cid: this.clientId, s });
93
+ return `${this.endpoint}?${qs.toString()}`;
94
+ }
95
+
96
+ private connect() {
97
+ const url = this.buildUrl();
98
+ this.log('connecting', { url });
99
+ this.es = new EventSource(url);
100
+ this.closed = false;
101
+
102
+ const forward = (e: MessageEvent) => {
103
+ try {
104
+ const evt: RenEvent = JSON.parse(e.data);
105
+ this.log('event', evt);
106
+ this.listeners.forEach(l => l(evt));
107
+ } catch (err) {
108
+ this.log('malformed event data', e.data, err);
109
+ }
110
+ };
111
+
112
+ // Attach generic message handler for events without a specific event: type
113
+ this.es.onmessage = forward;
114
+
115
+ // Register listeners for all known event types
116
+ // The browser EventSource API does NOT call onmessage for events with an event: field
117
+ // We must explicitly register listeners for each event type we want to handle
118
+ const knownEventTypes = [
119
+ // Database events
120
+ 'db.document.created',
121
+ 'db.document.updated',
122
+ 'db.document.deleted',
123
+ // KV events
124
+ 'kv.put',
125
+ 'kv.delete',
126
+ 'kv.expired',
127
+ // Storage events
128
+ 'storage.object.created',
129
+ 'storage.object.updated',
130
+ 'storage.object.deleted',
131
+ // Runtime events
132
+ 'runtime.snapshot.ready',
133
+ 'runtime.worker.started',
134
+ 'runtime.worker.stopped',
135
+ // Meta events
136
+ 'ren.meta'
137
+ ];
138
+ // Use the more general addEventListener signature to avoid TypeScript issues
139
+ knownEventTypes.forEach(k => this.es?.addEventListener(k, forward as EventListener));
140
+
141
+ this.es.onerror = (ev) => {
142
+ this.log('error', ev);
143
+ if (this.closed) return;
144
+ this.es?.close();
145
+ if (!this.autoReconnect) return;
146
+ const delay = Math.min(1000 * Math.pow(2, this.attempt++), this.maxBackoff);
147
+ this.log('reconnecting in', delay, 'ms');
148
+ setTimeout(() => this.connect(), delay);
149
+ };
150
+
151
+ this.es.onopen = () => { this.attempt = 0; this.log('open'); };
152
+ }
153
+
154
+ on(listener: Listener): () => void {
155
+ this.listeners.add(listener);
156
+ this.log('listener added; total', this.listeners.size);
157
+ return () => { this.listeners.delete(listener); this.log('listener removed; total', this.listeners.size); };
158
+ }
159
+
160
+ getClientId() { return this.clientId; }
161
+
162
+ close() {
163
+ this.closed = true;
164
+ this.es?.close();
165
+ this.log('closed');
166
+ }
167
+ }
168
+
169
+ export function getOrCreateClientId(storage?: Storage): string {
170
+ if (!storage) {
171
+ storage = (typeof window !== 'undefined' && window.localStorage) ? window.localStorage : (typeof globalThis !== 'undefined' && (globalThis as any).localStorage) ? (globalThis as any).localStorage : undefined as any;
172
+ if (!storage) {
173
+ // Return a random ID if no storage is available
174
+ return (globalThis.crypto?.randomUUID?.() || randomFallback());
175
+ }
176
+ }
177
+ const key = 'maravillaClientId';
178
+ let id = storage.getItem(key);
179
+ if (!id) {
180
+ id = (globalThis.crypto?.randomUUID?.() || randomFallback());
181
+ try { storage.setItem(key, id); } catch {} // ignore quota errors
182
+ }
183
+ return id;
184
+ }
185
+
186
+ function randomFallback(): string {
187
+ // Very small UUID-ish fallback
188
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
189
+ const r = Math.random() * 16 | 0;
190
+ const v = c === 'x' ? r : (r & 0x3 | 0x8);
191
+ return v.toString(16);
192
+ });
193
+ }
194
+
195
+ // Helper to add client header to fetch
196
+ export async function renFetch(input: string | URL | Request, init: RequestInit = {}, clientId?: string) {
197
+ const cid = clientId || getOrCreateClientId();
198
+ const headers = new Headers(init.headers || {});
199
+ headers.set('X-Ren-Client', cid);
200
+ return fetch(input, { ...init, headers });
201
+ }
202
+
203
+ // Storage convenience wrappers (example)
204
+ export async function storageUpload(path: string, file: Blob | File, clientId?: string) {
205
+ const res = await renFetch(`/api/storage/upload?path=${encodeURIComponent(path)}`, { method: 'POST', body: file }, clientId);
206
+ if (!res.ok) throw new Error('upload failed');
207
+ return res.json().catch(() => ({}));
208
+ }
209
+
210
+ export async function storageDelete(path: string, clientId?: string) {
211
+ const res = await renFetch(`/api/storage/delete?path=${encodeURIComponent(path)}`, { method: 'DELETE' }, clientId);
212
+ if (!res.ok) throw new Error('delete failed');
213
+ return res.json().catch(() => ({}));
214
+ }
package/tsconfig.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "compilerOptions": {
3
3
  "target": "ES2022",
4
4
  "module": "ES2022",
5
- "lib": ["ES2022"],
5
+ "lib": ["ES2022", "DOM"],
6
6
  "moduleResolution": "node",
7
7
  "rootDir": "./src",
8
8
  "outDir": "./dist",