File size: 19,970 Bytes
c72f0a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
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();
  };
}