Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download web/src/apps/code/bridgeHost.ts from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 20 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/apps/code/bridgeHost.ts
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/web/src/apps/code/bridgeHost.ts
-
curl -L -o bridgeHost.ts https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/apps/code/bridgeHost.ts
20 kB
| import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract"; | |
| import { CODE_APP_CALLS } from "./bridge"; | |
| import type { BridgeAnswer, BridgeCall, BridgeField, RowOptions, RowPage, TotalOptions, Totals } from "./bridge"; | |
| import { BridgeRefused, serveTool } from "./bridgeTools"; | |
| import type { ConfirmTool } from "./bridgeTools"; | |
| export { BridgeRefused } from "./bridgeTools"; | |
| const READ_CALLS = new Set<BridgeCall>(["databases", "describe", "rows", "totals"]); | |
| const WRITE_CALLS = new Set<BridgeCall>(["addRecord", "editRecord", "editRecords", "deleteRecord"]); | |
| type Json = Record<string, unknown>; | |
| export type DeleteRequest = { database: string; id: string | number }; | |
| export type BridgeHostOptions = { | |
| applicationId: string; | |
| confirmDelete: (request: DeleteRequest, abort: AbortSignal) => Promise<boolean>; | |
| confirmTool: ConfirmTool; | |
| }; | |
| function object(value: unknown): Json { | |
| if (!value || typeof value !== "object" || Array.isArray(value)) { | |
| throw new BridgeRefused("bad_arguments", "Send an object for these options."); | |
| } | |
| return value as Json; | |
| } | |
| function count(value: unknown): number { | |
| if (!Number.isSafeInteger(value) || (value as number) < 0) { | |
| throw new BridgeRefused("invalid_response", "This database returned an invalid count."); | |
| } | |
| return value as number; | |
| } | |
| function databaseKey(value: unknown): string { | |
| if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value)) { | |
| throw new BridgeRefused("bad_arguments", "Send a database key."); | |
| } | |
| return value; | |
| } | |
| function list(value: unknown, name: string): unknown[] { | |
| if (value === undefined) return []; | |
| if (!Array.isArray(value)) throw new BridgeRefused("bad_arguments", `${name} must be a list.`); | |
| return value; | |
| } | |
| function options(value: unknown, allowed: string[]): Json { | |
| const result = value === undefined ? {} : object(value); | |
| if (Object.keys(result).some((key) => !allowed.includes(key))) { | |
| throw new BridgeRefused("bad_arguments", "These options include an unsupported key."); | |
| } | |
| return result; | |
| } | |
| function alias(value: Json, native: string, publicKey: string): unknown { | |
| if (Object.hasOwn(value, native) && Object.hasOwn(value, publicKey) && value[native] !== value[publicKey]) { | |
| throw new BridgeRefused("bad_arguments", `${native} and ${publicKey} must agree.`); | |
| } | |
| return Object.hasOwn(value, native) ? value[native] : value[publicKey]; | |
| } | |
| function sortOptions(value: unknown): Json { | |
| const sort = options(value, ["colId", "dir", "field", "direction"]); | |
| const colId = alias(sort, "colId", "field"), dir = alias(sort, "dir", "direction"); | |
| if (typeof colId !== "string" || !colId || (dir !== "asc" && dir !== "desc")) { | |
| throw new BridgeRefused("bad_arguments", "Send a field key and asc or desc for each sort."); | |
| } | |
| return { colId, dir }; | |
| } | |
| function aggregateOptions(value: unknown): Json { | |
| const aggregate = options(value, ["colId", "agg", "field", "fn", "p"]); | |
| const colId = alias(aggregate, "colId", "field"), agg = alias(aggregate, "agg", "fn"); | |
| if (typeof colId !== "string" || !colId || typeof agg !== "string" || !agg) { | |
| throw new BridgeRefused("bad_arguments", "Send a field key and aggregate name."); | |
| } | |
| return { colId, agg, ...(Object.hasOwn(aggregate, "p") ? { p: aggregate.p } : {}) }; | |
| } | |
| function groupField(value: unknown): string | undefined { | |
| if (value === undefined) return undefined; | |
| if (Array.isArray(value)) { | |
| if (!value.length) return undefined; | |
| if (value.length !== 1) throw new BridgeRefused("bad_arguments", "groupBy supports one field."); | |
| value = value[0]; | |
| } | |
| if (typeof value !== "string" || !value) { | |
| throw new BridgeRefused("bad_arguments", "groupBy must name a field key."); | |
| } | |
| return value; | |
| } | |
| async function readRoute(path: string, abort: AbortSignal, body?: Json): Promise<Json> { | |
| let response: Response; | |
| try { | |
| response = await fetch(`${API_V1}${path}`, { | |
| credentials: CREDENTIALS, cache: "no-store", signal: abort, | |
| ...(body ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}), | |
| }); | |
| } catch { | |
| throw new BridgeRefused("read_unavailable", "This database could not be read."); | |
| } | |
| if (checkTenant(response)) throw new BridgeRefused("tenant_changed", "Open this App again."); | |
| if (response.status === 401) signal(UNAUTHORIZED_EVENT); | |
| let payload: Json; | |
| try { payload = object(await response.json()); } | |
| catch { throw new BridgeRefused("read_unavailable", "This database could not be read."); } | |
| if (!response.ok) { | |
| const error = payload.error as Partial<BridgeRefused> | undefined; | |
| throw new BridgeRefused(typeof error?.code === "string" ? error.code : `http_${response.status}`, | |
| typeof error?.message === "string" ? error.message : "This database could not be read."); | |
| } | |
| return payload; | |
| } | |
| function visibleFields(payload: Json, requested?: unknown): BridgeField[] { | |
| if (!Array.isArray(payload.fields)) throw new BridgeRefused("invalid_response", "This database returned no fields."); | |
| const fields = payload.fields.map((value) => { | |
| const field = object(value); | |
| if (typeof field.key !== "string") throw new BridgeRefused("invalid_response", "This database returned an invalid field."); | |
| return { key: field.key, ...(typeof field.label === "string" ? { label: field.label } : {}), | |
| ...(typeof field.type === "string" ? { type: field.type } : {}) }; | |
| }); | |
| if (requested === undefined) return fields; | |
| const keys = list(requested, "fields"); | |
| if (keys.some((key) => typeof key !== "string" || !fields.some((field) => field.key === key))) { | |
| throw new BridgeRefused("field_not_readable", "One of these fields is unavailable to your account."); | |
| } | |
| return fields.filter((field) => keys.includes(field.key)); | |
| } | |
| function readLimits(value: unknown): Json[] { | |
| if (!Array.isArray(value)) return []; | |
| return value.map((item) => { | |
| const limit = object(item); | |
| return Object.fromEntries(["subject", "effect", "cause", "recommendation"] | |
| .filter((key) => typeof limit[key] === "string").map((key) => [key, limit[key]])); | |
| }); | |
| } | |
| function rowResult(payload: Json, database: string, offset: number, query: string, requested?: unknown): RowPage { | |
| const fields = visibleFields(payload, requested); | |
| if (!Array.isArray(payload.rows)) throw new BridgeRefused("invalid_response", "This database returned no rows."); | |
| const identity = typeof (payload.identity as Json | undefined)?.pid === "string" ? (payload.identity as Json).pid as string : "pid"; | |
| const admitted = new Set([identity, ...fields.map((field) => field.key)]); | |
| const rows = payload.rows.map((value) => Object.fromEntries(Object.entries(object(value)).filter(([key]) => admitted.has(key)))); | |
| const total = count(payload.total); | |
| if (count(payload.offset) !== offset || offset + rows.length > total || (!rows.length && offset < total)) { | |
| throw new BridgeRefused("incomplete_rows", "This database could not supply the next page."); | |
| } | |
| const nextCursor = offset + rows.length < total | |
| ? encodeURIComponent(JSON.stringify({ version: 1, database, offset: offset + rows.length, query })) : null; | |
| return { fields, rows, total, nextCursor, limits: readLimits(payload.limits) }; | |
| } | |
| async function readRows(database: string, value: unknown, abort: AbortSignal): Promise<RowPage> { | |
| const opts = options(value, ["filters", "sorts", "fields", "limit", "cursor"]) as RowOptions; | |
| const filters = list(opts.filters, "filters"), sorts = list(opts.sorts, "sorts").map(sortOptions); | |
| if (opts.fields !== undefined) list(opts.fields, "fields"); | |
| const limit = opts.limit === undefined ? 100 : count(opts.limit); | |
| if (!limit) throw new BridgeRefused("bad_arguments", "limit must be a positive page size."); | |
| const query = JSON.stringify({ filters, sorts, fields: opts.fields }); | |
| let offset = 0; | |
| if (opts.cursor !== undefined && opts.cursor !== null) { | |
| try { | |
| if (typeof opts.cursor !== "string") throw new Error(); | |
| const cursor = object(JSON.parse(decodeURIComponent(opts.cursor))); | |
| if (cursor.version !== 1 || cursor.database !== database || cursor.query !== query) throw new Error(); | |
| offset = count(cursor.offset); | |
| } catch { throw new BridgeRefused("bad_cursor", "Use the cursor with its original database and options."); } | |
| } | |
| const search = new URLSearchParams({ offset: String(offset), limit: String(limit) }); | |
| if (filters.length) search.set("filters", JSON.stringify(filters)); | |
| if (sorts.length) search.set("sorts", JSON.stringify(sorts)); | |
| const payload = await readRoute(`/odoo-tables/${encodeURIComponent(database)}/rows?${search}`, abort); | |
| return rowResult(payload, database, offset, query, opts.fields); | |
| } | |
| function aggregateValues(value: unknown, aggregates: unknown[]): Json { | |
| const source = object(value); | |
| const keys = new Set(aggregates.map((item) => object(item).colId)); | |
| return Object.fromEntries(Object.entries(source).filter(([key]) => keys.has(key))); | |
| } | |
| async function readTotals(database: string, value: unknown, abort: AbortSignal): Promise<Totals> { | |
| const opts = options(value, ["aggregates", "groupBy", "filters"]) as TotalOptions; | |
| const aggregates = list(opts.aggregates, "aggregates").map(aggregateOptions), filters = list(opts.filters, "filters"); | |
| const groupBy = groupField(opts.groupBy); | |
| const path = `/odoo-tables/${encodeURIComponent(database)}/aggregates`; | |
| const request = { filters, aggs: aggregates, ...(groupBy ? { groupBy } : {}) }; | |
| const payload = await readRoute(path, abort, request); | |
| const groups = Array.isArray(payload.groups) ? [...payload.groups] : null; | |
| const totalGroups = payload.total_groups === undefined ? undefined : count(payload.total_groups); | |
| // Group pages bound each response, while every group remains available to the App. | |
| while (groups && totalGroups !== undefined && groups.length < totalGroups) { | |
| const page = await readRoute(path, abort, { ...request, groupOffset: groups.length, | |
| groupLimit: count(payload.group_limit ?? groups.length) }); | |
| if (!Array.isArray(page.groups) || !page.groups.length || count(page.total_groups) !== totalGroups | |
| || count(page.total_rows) !== count(payload.total_rows) || count(page.group_offset) !== groups.length) { | |
| throw new BridgeRefused("incomplete_totals", "This database could not supply all groups."); | |
| } | |
| groups.push(...page.groups); | |
| } | |
| if (groups && totalGroups !== undefined && groups.length !== totalGroups) { | |
| throw new BridgeRefused("incomplete_totals", "This database could not supply all groups."); | |
| } | |
| return { total_rows: count(payload.total_rows), aggregates: aggregateValues(payload.aggregates, aggregates), | |
| groups: groups?.map((value) => { | |
| const group = object(value); | |
| return { key: group.key, label: group.label, count: count(group.count), | |
| aggregates: aggregateValues(group.aggregates, aggregates) }; | |
| }) ?? null, ...(totalGroups !== undefined ? { total_groups: totalGroups } : {}), | |
| limits: readLimits(payload.limits) }; | |
| } | |
| export async function serveRead(call: BridgeCall, args: unknown[], abort: AbortSignal): Promise<unknown> { | |
| if (!READ_CALLS.has(call)) throw new BridgeRefused("call_not_enabled", "This App call is not enabled."); | |
| if (call === "databases") { | |
| if (args.length) throw new BridgeRefused("bad_arguments", "databases takes no arguments."); | |
| const payload = await readRoute("/tables?brief=1", abort); | |
| if (!Array.isArray(payload.tables)) throw new BridgeRefused("invalid_response", "The database list is unavailable."); | |
| return payload.tables.map((value) => { | |
| const database = object(value); | |
| return { key: databaseKey(database.key), label: typeof database.label === "string" ? database.label : database.key }; | |
| }); | |
| } | |
| if (args.length < 1 || args.length > (call === "describe" ? 1 : 2)) { | |
| throw new BridgeRefused("bad_arguments", "Send a database key and its options."); | |
| } | |
| const database = databaseKey(args[0]); | |
| if (call === "rows") return readRows(database, args[1], abort); | |
| if (call === "totals") return readTotals(database, args[1], abort); | |
| const payload = await readRoute(`/odoo-tables/${encodeURIComponent(database)}/rows?offset=0&limit=1`, abort); | |
| return { key: database, fields: visibleFields(payload), | |
| identity: { pid: typeof (payload.identity as Json | undefined)?.pid === "string" ? (payload.identity as Json).pid : "pid" }, | |
| recordsMutable: payload.recordsMutable === true }; | |
| } | |
| function recordId(value: unknown): string { | |
| const id = typeof value === "number" && Number.isSafeInteger(value) ? String(value) : value; | |
| if (typeof id !== "string" || !/^[1-9]\d*$/.test(id) || !Number.isSafeInteger(Number(id))) { | |
| throw new BridgeRefused("bad_arguments", "Send a record id."); | |
| } | |
| return id; | |
| } | |
| async function writeRoute(path: string, method: string, values: Json | undefined, | |
| applicationId: string, abort: AbortSignal): Promise<Json> { | |
| let response: Response; | |
| try { | |
| response = await fetch(`${API_V1}${path}`, { | |
| method, credentials: CREDENTIALS, cache: "no-store", signal: abort, | |
| headers: { "X-Loopable-App": applicationId, ...(values === undefined ? {} : { "Content-Type": "application/json" }) }, | |
| ...(values === undefined ? {} : { body: JSON.stringify(values) }), | |
| }); | |
| } catch { throw new BridgeRefused("write_unavailable", "This record could not be saved."); } | |
| if (checkTenant(response)) throw new BridgeRefused("tenant_changed", "Open this App again."); | |
| if (response.status === 401) signal(UNAUTHORIZED_EVENT); | |
| let payload: Json; | |
| try { payload = object(await response.json()); } | |
| catch { throw new BridgeRefused("write_unavailable", "This record could not be saved."); } | |
| if (!response.ok) { | |
| const error = payload.error as Partial<BridgeRefused> | undefined; | |
| throw new BridgeRefused(typeof error?.code === "string" ? error.code : `http_${response.status}`, | |
| typeof error?.message === "string" ? error.message : "This record could not be saved."); | |
| } | |
| // Row PATCH can return 200 with refused cells. That is a failed App write. | |
| if (Array.isArray(payload.refused) && payload.refused.length) { | |
| const error = payload.error as Partial<BridgeRefused> | undefined; | |
| throw new BridgeRefused(typeof error?.code === "string" ? error.code : "fields_refused", | |
| typeof error?.message === "string" ? error.message : "One of these fields cannot be edited."); | |
| } | |
| return payload; | |
| } | |
| async function checkAddFields(database: string, values: Json, abort: AbortSignal) { | |
| const payload = await readRoute(`/odoo-tables/${encodeURIComponent(database)}/rows?offset=0&limit=1`, abort); | |
| // Locked databases still use the row route's own refusal sentence. | |
| if (payload.recordsMutable === false) return; | |
| if (!Array.isArray(payload.fields)) throw new BridgeRefused("invalid_response", "This database returned no fields."); | |
| const fields = payload.fields.map(object); | |
| for (const key of Object.keys(values)) { | |
| const field = fields.find((entry) => entry.key === key); | |
| if (!field) throw new BridgeRefused("field_not_readable", "One of these fields is unavailable to your account."); | |
| const automation = field.automation as Json | undefined; | |
| if (field.valueAuthority === "computed" || field.valueAuthority === "source" || field.valueAuthority === "derived" | |
| || ["automation", "formula", "rollup"].includes(String(field.type)) || field.metric | |
| || ((automation?.preset === true || automation?.flowId) && !field.profile)) { | |
| throw new BridgeRefused("fields_refused", "One of these pre-set fields cannot be edited."); | |
| } | |
| } | |
| } | |
| export async function serveWrite(call: BridgeCall, args: unknown[], host: BridgeHostOptions, | |
| abort: AbortSignal): Promise<unknown> { | |
| if (!WRITE_CALLS.has(call)) throw new BridgeRefused("call_not_enabled", "This App call is not enabled."); | |
| if (args.length !== (call === "editRecord" ? 3 : 2)) { | |
| throw new BridgeRefused("bad_arguments", "Send a database key and the record values or id."); | |
| } | |
| const database = databaseKey(args[0]); | |
| const path = `/tables/${encodeURIComponent(database)}/rows`; | |
| if (call === "addRecord") { | |
| const values = object(args[1]); | |
| await checkAddFields(database, values, abort); | |
| const result = await writeRoute(path, "POST", { values }, host.applicationId, abort); | |
| return { rid: result.rid, pid: result.pid }; | |
| } | |
| if (call === "deleteRecord") { | |
| const id = recordId(args[1]); | |
| if (!await host.confirmDelete({ database, id }, abort)) { | |
| throw new BridgeRefused("delete_canceled", "This record was not deleted."); | |
| } | |
| if (abort.aborted) throw new BridgeRefused("bridge_closed", "This App was closed."); | |
| const result = await writeRoute(`${path}/${id}`, "DELETE", undefined, host.applicationId, abort); | |
| return { ok: result.ok === true }; | |
| } | |
| const records = call === "editRecord" ? [{ id: args[1], values: args[2] }] : list(args[1], "records"); | |
| // Validate the whole request before its first write. Bulk edits retain server per-record checks. | |
| const edits = records.map((record) => { | |
| const entry = options(record, ["id", "values"]); | |
| const values = object(entry.values); | |
| if (!Object.keys(values).length) throw new BridgeRefused("bad_arguments", "Send at least one field to edit."); | |
| return { id: recordId(entry.id), values }; | |
| }); | |
| const results = []; | |
| for (const edit of edits) { | |
| const result = await writeRoute(`${path}/${edit.id}`, "PATCH", edit.values, host.applicationId, abort); | |
| const updates = object(result.updates); | |
| results.push({ pid: result.pid, updates: Object.fromEntries(Object.entries(updates) | |
| .filter(([key]) => Object.hasOwn(edit.values, key))) }); | |
| } | |
| return call === "editRecord" ? results[0] : results; | |
| } | |
| export function attachBridgeHost(getAppWindow: () => Window | null, host: BridgeHostOptions): () => void { | |
| const controller = new AbortController(); | |
| const pending = new Set<string | number>(); | |
| const owns = (source: MessageEventSource | null) => source !== null && source === getAppWindow(); | |
| const receive = (event: MessageEvent) => { | |
| if (!owns(event.source)) return; | |
| const request = event.data; | |
| if (!request || typeof request !== "object" || !Array.isArray(request.args) | |
| || !((typeof request.id === "string" && request.id.length > 0) || Number.isSafeInteger(request.id)) | |
| || typeof request.call !== "string" || pending.has(request.id)) return; | |
| const sender = event.source as Window; | |
| const { id, call, args } = request; | |
| pending.add(id); | |
| void (async () => { | |
| let answer: BridgeAnswer; | |
| try { | |
| if (call.startsWith("tools.")) { | |
| answer = { id, ok: true, result: await serveTool(call, args, host.applicationId, host.confirmTool, controller.signal) }; | |
| } else { | |
| if (!(CODE_APP_CALLS as readonly string[]).includes(call)) { | |
| throw new BridgeRefused("unknown_call", "This App call is unknown."); | |
| } | |
| answer = { id, ok: true, result: WRITE_CALLS.has(call) | |
| ? await serveWrite(call, args, host, controller.signal) | |
| : await serveRead(call, args, controller.signal) }; | |
| } | |
| } catch (error) { | |
| answer = { id, ok: false, error: error instanceof BridgeRefused | |
| ? { code: error.code, message: error.message } | |
| : call.startsWith("tools.") ? { code: "tool_unavailable", message: "This tool could not complete its request." } | |
| : WRITE_CALLS.has(call) ? { code: "write_unavailable", message: "This record could not be saved." } | |
| : { code: "read_unavailable", message: "This database could not be read." } }; | |
| } finally { | |
| pending.delete(id); | |
| } | |
| if (!controller.signal.aborted && owns(sender)) sender.postMessage(answer, "*"); | |
| })(); | |
| }; | |
| window.addEventListener("message", receive); | |
| return () => { | |
| window.removeEventListener("message", receive); | |
| controller.abort(); | |
| pending.clear(); | |
| }; | |
| } | |