import { NoyaManager } from "../NoyaManager"; import { SerializableRequest } from "../rpc/types"; import { buildLocalAIRoutes, buildLocalAssetRoutes, buildLocalResourceRoutes, createJsonResponse, } from "./localRpcHelpers"; import { ParentToEmbeddedMessage } from "./parentFrameMessages"; /** * Attempt to handle local AI/asset/resource RPC routes and send a response to the child. * Returns true if the request was handled, false to allow other handlers. */ export async function bridgeRpcRequestToLocalAssets< S, M extends object, E extends object, MenuT extends string, I extends Record = Record, >( noyaManager: NoyaManager, request: SerializableRequest, send: (message: ParentToEmbeddedMessage) => void, options: { offlineStorageKey: string } ): Promise { const method = request.options?.method?.toUpperCase(); const pathname = request.url.split("?")[0]; try { // Build the local route table for AI, assets, resources, and basic lists const routes = [ ...buildLocalAIRoutes({ emitStreamEvent: async (streamRequest, event) => { send({ type: "chunk", id: streamRequest.id!, chunk: `${JSON.stringify(event)}\n`, }); if (event.type === "text-delta" || event.type === "partial-object") { await new Promise((resolve) => setTimeout(resolve, 750)); } }, }), ...buildLocalAssetRoutes(noyaManager, { offlineStorageKey: options?.offlineStorageKey, }), ...buildLocalResourceRoutes(noyaManager, { offlineStorageKey: options?.offlineStorageKey, }), ]; // Attempt to match and handle the request for (const r of routes) { if (r.method === method && r.pattern.test(pathname)) { const match = pathname.match(r.pattern); const body = await r.handler(request, match); if ( r.key === "GET /api/resources" || r.key === "PATCH /api/resources" ) { send({ type: "resources", resources: noyaManager.resourceManager.resources$.get(), }); } send({ type: "end", id: request.id!, response: createJsonResponse(body), }); return true; } } return false; } catch (error) { send({ type: "error", id: request.id!, error: error instanceof Error ? error.message : String(error ?? "error"), }); return true; } } export { ensureLocalAssetStore, ensureLocalResourceStore, sendLocalInitializationMessages, } from "./localRpcHelpers";