@mfdaves/okf-odoo 0.0.0-stage → 0.1.2

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.
@@ -0,0 +1,254 @@
1
+ "use strict";
2
+
3
+ // Client for the o3p_mcp data API in Odoo: POST {url}/o3p_mcp/api/v1/{op}
4
+ // with the resource server's client credentials as HTTP Basic and the
5
+ // signed-in user's access token as the subject. Odoo runs the operation as
6
+ // that user. Errors carry a fixed code and message: neither Odoo's text nor
7
+ // the token or the credentials ever reach a result or an error.
8
+
9
+ const { setTimeout: sleep } = require("node:timers/promises");
10
+ const { OdooError, normalizeBaseUrl, postJson } = require("./odoo");
11
+
12
+ const OPS = new Set(["models", "describe", "search", "read", "group", "sql"]);
13
+ // PostgreSQL's own message about an SQL query, as the data API caps it.
14
+ const MAX_SQL_MESSAGE = 500;
15
+ // The host passes on detail strings of at most 200 characters.
16
+ const MAX_DETAIL = 200;
17
+ // Below the host's own per-call limit (30 s in okf-mcp), so the host hears
18
+ // this pack's timeout rather than cutting the call off itself.
19
+ const DEFAULT_TIMEOUT_MS = 25000;
20
+ // Odoo caps a result at 1 MB by default; this only bounds a misbehaving server.
21
+ const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
22
+ // too_many_requests means the user's query slots or the server's sandbox
23
+ // connections are all taken, which lasts as long as a running query. Agents
24
+ // often send several queries at once, so the call waits and asks again
25
+ // instead of failing: here, in the host, the wait holds no Odoo worker. It
26
+ // gives up after BUSY_WAIT_MS, and never later than leaves the last attempt
27
+ // MIN_ATTEMPT_MS of the call's time limit.
28
+ const BUSY_WAIT_MS = 12000;
29
+ const BUSY_DELAYS_MS = [250, 500, 1000];
30
+ const MIN_ATTEMPT_MS = 5000;
31
+ const BUSY_HINT =
32
+ "Odoo limits how many SQL queries run at once and stayed busy; send the queries one after another.";
33
+
34
+ const MESSAGES = {
35
+ // The data API contract.
36
+ invalid_params: "Odoo refused the parameters.",
37
+ invalid_client: "Odoo refused the connector's client credentials.",
38
+ invalid_token: "The signed-in user's access token is not valid for Odoo.",
39
+ insufficient_scope: "The signed-in user's access token does not allow reading Odoo data.",
40
+ access_denied: "The signed-in user may not read this.",
41
+ unknown_op: "Odoo does not offer this operation.",
42
+ unknown_model: "Odoo has no such model, or it is not exposed.",
43
+ result_too_large: "The result is too large; ask for fewer records or fields.",
44
+ query_error: "Odoo could not run the query; check field names, operators and values.",
45
+ too_many_requests: "Too many queries are running for this user or server; try again shortly.",
46
+ unavailable: "SQL queries are not available on this Odoo server right now.",
47
+ timeout: "The query took too long.",
48
+ // The connector.
49
+ aborted: "The request was cancelled.",
50
+ client_credentials_unavailable: "The connector's client credentials are not configured.",
51
+ connection_failed: "Odoo could not be reached.",
52
+ data_api_unavailable: "This Odoo server offers no MCP data API.",
53
+ invalid_arguments: "The tool arguments do not match its input schema.",
54
+ invalid_config: "The connector's Odoo tool configuration is not valid.",
55
+ invalid_response: "Odoo returned an answer that could not be read.",
56
+ server_error: "Odoo failed to answer.",
57
+ subject_token_required:
58
+ "Odoo data tools need a signed-in user; they are available over HTTP only.",
59
+ };
60
+
61
+ const CONTRACT_CODES = new Set([
62
+ "invalid_params",
63
+ "invalid_client",
64
+ "invalid_token",
65
+ "insufficient_scope",
66
+ "access_denied",
67
+ "unknown_op",
68
+ "unknown_model",
69
+ "result_too_large",
70
+ "query_error",
71
+ "too_many_requests",
72
+ "unavailable",
73
+ "timeout",
74
+ ]);
75
+
76
+ class OdooToolError extends Error {
77
+ constructor(code, details = {}) {
78
+ super(MESSAGES[code] || MESSAGES.server_error);
79
+ this.name = "OdooToolError";
80
+ this.code = MESSAGES[code] ? code : "server_error";
81
+ // `details` is what a host may pass on: bounded scalars naming the
82
+ // caller's own parameter, never a value. The HTTP status stays local.
83
+ if (details.field) {
84
+ this.details = { field: details.field.split("/")[1] || null, path: details.field };
85
+ }
86
+ if (details.reply) this.details = details.reply;
87
+ if (details.status) this.status = details.status;
88
+ }
89
+ }
90
+
91
+ function oneLine(value, max) {
92
+ return typeof value === "string"
93
+ ? value
94
+ .toWellFormed()
95
+ .replace(/[\p{Cc}\u2028\u2029]+/gu, " ")
96
+ .trim()
97
+ .slice(0, max) || null
98
+ : null;
99
+ }
100
+
101
+ // What an error answer explains, reduced to bounded scalars the host passes
102
+ // on. Every operation may name the offending parameter, the reason and a
103
+ // hint, all schema names and fixed texts. sql's query_error adds
104
+ // PostgreSQL's answer (the sandbox holds only rows the user may read, and an
105
+ // agent needs it to fix its query): a valid SQLSTATE, a 1-based position and
106
+ // a message of at most 500 characters. A string holding the token or a
107
+ // credential is dropped. Returns null when nothing remains.
108
+ function errorDetails(value, op, code, hidden) {
109
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
110
+ const clean = (text, max) => {
111
+ const line = oneLine(text, max);
112
+ return line && !hidden.some((secret) => secret && line.includes(secret)) ? line : null;
113
+ };
114
+ const details = {};
115
+ for (const key of ["field", "reason", "hint"]) {
116
+ const text = clean(value[key], MAX_DETAIL);
117
+ if (text) details[key] = text;
118
+ }
119
+ if (op === "sql" && code === "query_error") {
120
+ details.sqlstate =
121
+ typeof value.sqlstate === "string" && /^[0-9A-Z]{5}$/.test(value.sqlstate)
122
+ ? value.sqlstate
123
+ : null;
124
+ details.position =
125
+ Number.isInteger(value.position) && value.position > 0 && value.position <= 1000000
126
+ ? value.position
127
+ : null;
128
+ details.message = clean(value.message, MAX_SQL_MESSAGE);
129
+ }
130
+ return Object.keys(details).length ? details : null;
131
+ }
132
+
133
+ // RFC 6749 section 2.3.1: client id and secret are form-urlencoded before
134
+ // they are joined and base64-encoded.
135
+ function formEncode(value) {
136
+ return new URLSearchParams([["", value]]).toString().slice(1);
137
+ }
138
+
139
+ function basicCredentials(clientId, clientSecret) {
140
+ const pair = `${formEncode(clientId)}:${formEncode(clientSecret)}`;
141
+ return `Basic ${Buffer.from(pair, "utf8").toString("base64")}`;
142
+ }
143
+
144
+ // Transport failures of the shared client, as tool codes.
145
+ const TRANSPORT = {
146
+ aborted: "aborted",
147
+ timeout: "timeout",
148
+ connection_failed: "connection_failed",
149
+ response_too_large: "result_too_large",
150
+ invalid_response: "invalid_response",
151
+ };
152
+
153
+ // One call: the request, repeated while the data API answers
154
+ // too_many_requests, within one time limit (`timeoutMs`) for the whole call.
155
+ async function callDataApi(options) {
156
+ const {
157
+ op,
158
+ clientId,
159
+ clientSecret,
160
+ token,
161
+ signal,
162
+ timeoutMs = DEFAULT_TIMEOUT_MS,
163
+ busyWaitMs = BUSY_WAIT_MS,
164
+ } = options;
165
+ if (!OPS.has(op)) throw new OdooToolError("unknown_op");
166
+ if (typeof token !== "string" || !token) throw new OdooToolError("subject_token_required");
167
+ if (
168
+ typeof clientId !== "string" ||
169
+ !clientId ||
170
+ typeof clientSecret !== "string" ||
171
+ !clientSecret
172
+ ) {
173
+ throw new OdooToolError("client_credentials_unavailable");
174
+ }
175
+ const started = Date.now();
176
+ const deadline = started + timeoutMs;
177
+ for (let attempt = 0; ; attempt += 1) {
178
+ try {
179
+ return await requestOnce(options, deadline - Date.now());
180
+ } catch (error) {
181
+ if (error.code !== "too_many_requests") throw error;
182
+ const delay = BUSY_DELAYS_MS[Math.min(attempt, BUSY_DELAYS_MS.length - 1)];
183
+ const resume = Date.now() + delay;
184
+ if (resume - started > busyWaitMs || deadline - resume < MIN_ATTEMPT_MS) {
185
+ throw new OdooToolError("too_many_requests", {
186
+ status: error.status,
187
+ reply: { ...error.details, hint: BUSY_HINT },
188
+ });
189
+ }
190
+ try {
191
+ await sleep(delay, undefined, { signal });
192
+ } catch {
193
+ throw new OdooToolError("aborted");
194
+ }
195
+ }
196
+ }
197
+ }
198
+
199
+ async function requestOnce(options, timeoutMs) {
200
+ const {
201
+ url,
202
+ op,
203
+ clientId,
204
+ clientSecret,
205
+ token,
206
+ params,
207
+ signal,
208
+ maxResponseBytes = MAX_RESPONSE_BYTES,
209
+ fetch,
210
+ } = options;
211
+ let reply;
212
+ try {
213
+ reply = await postJson(
214
+ { url: normalizeBaseUrl(url), signal, timeoutMs, maxResponseBytes, fetch },
215
+ `/o3p_mcp/api/v1/${op}`,
216
+ { Authorization: basicCredentials(clientId, clientSecret) },
217
+ { token, params },
218
+ {},
219
+ );
220
+ } catch (error) {
221
+ if (error instanceof OdooError)
222
+ throw new OdooToolError(TRANSPORT[error.code] || "server_error");
223
+ throw new OdooToolError("server_error");
224
+ }
225
+ const { response, isJson, body } = reply;
226
+ const status = response.status;
227
+ if (status >= 300 && status < 400) throw new OdooToolError("data_api_unavailable", { status });
228
+ if (!isJson) {
229
+ throw new OdooToolError(status === 404 ? "data_api_unavailable" : "invalid_response", {
230
+ status,
231
+ });
232
+ }
233
+ if (response.ok) {
234
+ if (!body || typeof body !== "object" || !Object.hasOwn(body, "result")) {
235
+ throw new OdooToolError("invalid_response", { status });
236
+ }
237
+ return body.result;
238
+ }
239
+ const code = CONTRACT_CODES.has(body?.error?.code) ? body.error.code : "server_error";
240
+ const explained = errorDetails(body.error.details, op, code, [token, clientId, clientSecret]);
241
+ throw new OdooToolError(code, { status, ...(explained ? { reply: explained } : {}) });
242
+ }
243
+
244
+ module.exports = {
245
+ BUSY_WAIT_MS,
246
+ CONTRACT_CODES,
247
+ DEFAULT_TIMEOUT_MS,
248
+ MAX_RESPONSE_BYTES,
249
+ MAX_DETAIL,
250
+ MAX_SQL_MESSAGE,
251
+ OdooToolError,
252
+ basicCredentials,
253
+ callDataApi,
254
+ };
package/src/index.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+
3
+ module.exports = {
4
+ ...require("./catalog"),
5
+ ...require("./odoo"),
6
+ ...require("./producer"),
7
+ ...require("./render"),
8
+ ...require("./tool-pack"),
9
+ };
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+
3
+ // Every string read from Odoo reaches a concept through one of the contexts
4
+ // below. Each returns a single line that CommonMark, and GitHub-flavoured
5
+ // tables, read back as the same text in that context: it cannot add a link,
6
+ // image, autolink, HTML, entity, emphasis, heading, list, quote, fence, table
7
+ // column or line break.
8
+
9
+ const WORD = /[\p{L}\p{N}]/u;
10
+ // Controls (C0, DEL, C1 including NEL), the byte order mark and the Unicode
11
+ // line and paragraph separators become spaces; runs of spaces collapse.
12
+ const BREAKS = /[\p{Cc}\ufeff\u2028\u2029]/gu;
13
+
14
+ // Normalised plain text: well-formed Unicode on one line, trimmed. Used as is
15
+ // in YAML frontmatter, which js-yaml quotes.
16
+ function clean(value) {
17
+ return String(value ?? "")
18
+ .toWellFormed()
19
+ .replace(BREAKS, " ")
20
+ .replace(/ {2,}/g, " ")
21
+ .trim();
22
+ }
23
+
24
+ // Text in the middle of a line: a paragraph after other words, a heading after
25
+ // its marker, a table cell, link text. Backslash-escapes the characters that
26
+ // open or close inline constructs, plus `|` for table cells and `#` for heading
27
+ // closing sequences. `_` between two letters or digits cannot start emphasis
28
+ // and stays as it is, and `&` only needs escaping where it starts an entity.
29
+ function inline(value) {
30
+ const text = clean(value);
31
+ return text.replace(/[\\`*_[\]<|~#&]/g, (char, offset) => {
32
+ if (char === "_") {
33
+ return WORD.test(text[offset - 1] || "") && WORD.test(text[offset + 1] || "") ? "_" : "\\_";
34
+ }
35
+ if (char === "&") return /^&#?[0-9A-Za-z]+;/.test(text.slice(offset)) ? "\\&" : "&";
36
+ return `\\${char}`;
37
+ });
38
+ }
39
+
40
+ // Text that starts a line or follows a list marker, where a leading `>`, `-`,
41
+ // `+`, `=` or `1.` would open a quote, list, break or setext heading. An empty
42
+ // value becomes a dash, so the line or list item keeps its content.
43
+ function lineStart(value) {
44
+ const text = inline(value)
45
+ .replace(/^[>+=-]/, "\\$&")
46
+ .replace(/^(\d{1,9})([.)])/, "$1\\$2");
47
+ return text || "—";
48
+ }
49
+
50
+ // A code span whose delimiter is longer than any backtick run in the value,
51
+ // padded when the value starts or ends with a backtick. Inside a table cell a
52
+ // `|` is escaped, which GitHub-flavoured tables undo before parsing the span.
53
+ function codeSpan(value, { table = false } = {}) {
54
+ let text = clean(value);
55
+ if (!text) return "—";
56
+ if (table) text = text.replace(/\|/g, "\\|");
57
+ const longest = Math.max(0, ...(text.match(/`+/g) || []).map((run) => run.length));
58
+ const fence = "`".repeat(longest + 1);
59
+ const pad = /^`|`$/.test(text) ? " " : "";
60
+ return `${fence}${pad}${text}${pad}${fence}`;
61
+ }
62
+
63
+ // A table cell, with a dash for an empty value.
64
+ function cell(value) {
65
+ return inline(value) || "—";
66
+ }
67
+
68
+ // A row of a GitHub-flavoured table. The leading pipe keeps the first cell
69
+ // out of line-start position.
70
+ function row(cells) {
71
+ return `| ${cells.join(" | ")} |`;
72
+ }
73
+
74
+ module.exports = {
75
+ cell,
76
+ clean,
77
+ codeSpan,
78
+ inline,
79
+ lineStart,
80
+ linkText: inline,
81
+ row,
82
+ };
package/src/odoo.js ADDED
@@ -0,0 +1,340 @@
1
+ "use strict";
2
+
3
+ // Minimal read-only Odoo client over one of two protocols, chosen by the
4
+ // caller: JSON-2 (Odoo 19 and later), one POST per call to
5
+ // /json/2/<model>/<method> with a bearer API key, or JSON-RPC (Odoo 18 and
6
+ // later), `execute_kw` on /jsonrpc with the user id and the API key as
7
+ // password. Either way only read methods can be called, reads must name the
8
+ // fields they want, and errors carry a fixed code and message, never server
9
+ // text.
10
+
11
+ const READ_METHODS = new Set(["fields_get", "read", "search_read"]);
12
+ // Holds system parameters, which may carry credentials; never metadata.
13
+ const FORBIDDEN_MODELS = new Set(["ir.config_parameter"]);
14
+ const FIELD_NAME = /^[a-z_][a-z0-9_]*$/;
15
+ const APIS = new Set(["json2", "jsonrpc"]);
16
+ const DEFAULT_TIMEOUT_MS = 30000;
17
+ const DEFAULT_PAGE_SIZE = 500;
18
+ const MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
19
+ const MODEL_NAME = /^[a-z_][a-z0-9_]*(\.[a-z0-9_]+)*$/;
20
+
21
+ const MESSAGES = {
22
+ aborted: "The Odoo request was aborted.",
23
+ access_denied: "The Odoo API key's user may not read this metadata.",
24
+ connection_failed: "The Odoo server could not be reached.",
25
+ invalid_api_key: "Odoo rejected the login or API key.",
26
+ invalid_request: "Odoo rejected the request parameters.",
27
+ invalid_response: "Odoo returned a response that is not JSON.",
28
+ json2_unavailable: "The Odoo server offers no JSON-2 API for this database.",
29
+ jsonrpc_unavailable: "The Odoo server offers no JSON-RPC endpoint.",
30
+ fields_required: "A read must name the fields it wants.",
31
+ method_not_allowed: "Only read methods may be called.",
32
+ model_not_allowed: "This Odoo model is never read.",
33
+ model_not_found: "The Odoo model or method does not exist on this database.",
34
+ response_too_large: "The Odoo response exceeds the size limit.",
35
+ server_error: "The Odoo server failed to answer the request.",
36
+ timeout: "The Odoo request timed out.",
37
+ };
38
+
39
+ class OdooError extends Error {
40
+ constructor(code, details = {}) {
41
+ const subject = details.model
42
+ ? ` (${details.model}${details.method ? `.${details.method}` : ""})`
43
+ : "";
44
+ super(`${MESSAGES[code] || "The Odoo request failed."}${subject}`);
45
+ this.name = "OdooError";
46
+ this.code = code;
47
+ Object.assign(this, details);
48
+ }
49
+ }
50
+
51
+ function normalizeBaseUrl(value) {
52
+ let parsed;
53
+ try {
54
+ parsed = new URL(String(value || ""));
55
+ } catch {
56
+ throw new TypeError("The Odoo url must be an absolute http or https URL.");
57
+ }
58
+ if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password) {
59
+ throw new TypeError("The Odoo url must be an http or https URL without credentials.");
60
+ }
61
+ if (parsed.search || parsed.hash) {
62
+ throw new TypeError("The Odoo url must not carry a query or fragment.");
63
+ }
64
+ // The API key travels as a bearer token, so plain http is only for a server
65
+ // on this machine.
66
+ if (parsed.protocol === "http:" && !isLoopback(parsed.hostname)) {
67
+ throw new TypeError("The Odoo url must use https unless the host is a loopback address.");
68
+ }
69
+ return `${parsed.origin}${parsed.pathname.replace(/\/+$/, "")}`;
70
+ }
71
+
72
+ function isLoopback(hostname) {
73
+ return hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname);
74
+ }
75
+
76
+ // The JSON-2 dispatcher answers an unknown model or method with 404 and a JSON
77
+ // error body. A server without the route answers 404 with an HTML page (no rpc
78
+ // module) or redirects to its login page (Odoo 18 and older).
79
+ function errorForStatus(response, isJson, details) {
80
+ const status = response.status;
81
+ if (status >= 300 && status < 400)
82
+ return new OdooError("json2_unavailable", { ...details, status });
83
+ if (status === 401) return new OdooError("invalid_api_key", { ...details, status });
84
+ if (status === 403) return new OdooError("access_denied", { ...details, status });
85
+ if (status === 404) {
86
+ return new OdooError(isJson ? "model_not_found" : "json2_unavailable", { ...details, status });
87
+ }
88
+ if (status === 400 || status === 415 || status === 422) {
89
+ return new OdooError("invalid_request", { ...details, status });
90
+ }
91
+ return new OdooError("server_error", { ...details, status });
92
+ }
93
+
94
+ // Reads the body chunk by chunk and stops as soon as it passes the limit, so
95
+ // an oversized or endless response is never buffered whole.
96
+ async function readBody(response, details, limit) {
97
+ const length = Number(response.headers.get("content-length"));
98
+ if (Number.isFinite(length) && length > limit) {
99
+ await response.body?.cancel().catch(() => {});
100
+ throw new OdooError("response_too_large", details);
101
+ }
102
+ if (!response.body) return "";
103
+ const reader = response.body.getReader();
104
+ const chunks = [];
105
+ let total = 0;
106
+ for (;;) {
107
+ const { done, value } = await reader.read();
108
+ if (done) break;
109
+ total += value.byteLength;
110
+ if (total > limit) {
111
+ await reader.cancel().catch(() => {});
112
+ throw new OdooError("response_too_large", details);
113
+ }
114
+ chunks.push(value);
115
+ }
116
+ return Buffer.concat(chunks).toString("utf8");
117
+ }
118
+
119
+ // Checks done before any request: a read method, a well-formed model that is
120
+ // not refused, an explicit list of field names, a printable key.
121
+ function checkRead({ model, method, params, apiKey }) {
122
+ if (!READ_METHODS.has(method)) throw new OdooError("method_not_allowed", { model, method });
123
+ if (typeof model !== "string" || !MODEL_NAME.test(model)) {
124
+ throw new TypeError("The Odoo model name is malformed.");
125
+ }
126
+ if (FORBIDDEN_MODELS.has(model)) throw new OdooError("model_not_allowed", { model, method });
127
+ if (typeof apiKey !== "string" || !/^[\x21-\x7e]+$/.test(apiKey)) {
128
+ throw new TypeError("An Odoo API key must be a non-empty printable token.");
129
+ }
130
+ if (!params || typeof params !== "object" || Array.isArray(params)) {
131
+ throw new TypeError("Odoo call parameters must be an object.");
132
+ }
133
+ if (
134
+ method !== "fields_get" &&
135
+ (!Array.isArray(params.fields) ||
136
+ params.fields.length === 0 ||
137
+ params.fields.some((field) => typeof field !== "string" || !FIELD_NAME.test(field)))
138
+ ) {
139
+ throw new OdooError("fields_required", { model, method });
140
+ }
141
+ }
142
+
143
+ // One JSON POST with the timeout, the caller's abort signal and the streamed
144
+ // size limit. Transport failures become fixed codes.
145
+ async function post(options, path, headers, payload, details) {
146
+ const {
147
+ url,
148
+ signal,
149
+ timeoutMs = DEFAULT_TIMEOUT_MS,
150
+ maxResponseBytes = MAX_RESPONSE_BYTES,
151
+ fetch: fetchImpl = globalThis.fetch,
152
+ } = options;
153
+ if (signal?.aborted) throw new OdooError("aborted", details);
154
+ const endpoint = `${normalizeBaseUrl(url)}${path}`;
155
+ const timeout = AbortSignal.timeout(timeoutMs);
156
+ const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
157
+ let response;
158
+ let text;
159
+ try {
160
+ response = await fetchImpl(endpoint, {
161
+ method: "POST",
162
+ headers: {
163
+ "Content-Type": "application/json; charset=utf-8",
164
+ Accept: "application/json",
165
+ ...headers,
166
+ },
167
+ body: JSON.stringify(payload),
168
+ signal: combined,
169
+ // A redirect is never followed: Odoo answers a route it does not have
170
+ // with a redirect to its login page.
171
+ redirect: "manual",
172
+ });
173
+ text = await readBody(response, details, maxResponseBytes);
174
+ } catch (error) {
175
+ if (error instanceof OdooError) throw error;
176
+ if (signal?.aborted) throw new OdooError("aborted", details);
177
+ if (timeout.aborted) throw new OdooError("timeout", details);
178
+ throw new OdooError("connection_failed", details);
179
+ }
180
+ const isJson = /^application\/json\b/i.test(response.headers.get("content-type") || "");
181
+ let body;
182
+ if (isJson) {
183
+ try {
184
+ body = JSON.parse(text);
185
+ } catch {
186
+ throw new OdooError("invalid_response", { ...details, status: response.status });
187
+ }
188
+ }
189
+ return { response, isJson, body };
190
+ }
191
+
192
+ async function callOdoo(options) {
193
+ const { database, apiKey, model, method, params = {} } = options || {};
194
+ checkRead({ model, method, params, apiKey });
195
+ const details = { model, method };
196
+ const headers = { Authorization: `bearer ${apiKey}` };
197
+ if (database) headers["X-Odoo-Database"] = database;
198
+ const { response, isJson, body } = await post(
199
+ options,
200
+ `/json/2/${model}/${method}`,
201
+ headers,
202
+ params,
203
+ details,
204
+ );
205
+ if (!response.ok) throw errorForStatus(response, isJson, details);
206
+ if (!isJson) throw new OdooError("invalid_response", { ...details, status: response.status });
207
+ return body;
208
+ }
209
+
210
+ // JSON-RPC reports every failure as HTTP 200 with an error object naming the
211
+ // exception class; only that name is used, never the message.
212
+ const RPC_ERRORS = {
213
+ "odoo.exceptions.AccessError": "access_denied",
214
+ "odoo.exceptions.AccessDenied": "invalid_api_key",
215
+ "odoo.exceptions.UserError": "invalid_request",
216
+ "odoo.exceptions.ValidationError": "invalid_request",
217
+ "odoo.exceptions.MissingError": "invalid_request",
218
+ "builtins.AttributeError": "invalid_request",
219
+ "builtins.KeyError": "invalid_request",
220
+ "builtins.TypeError": "invalid_request",
221
+ "builtins.ValueError": "invalid_request",
222
+ };
223
+
224
+ let rpcId = 0;
225
+
226
+ async function rpc(options, service, method, args, details) {
227
+ rpcId += 1;
228
+ const { response, isJson, body } = await post(
229
+ options,
230
+ "/jsonrpc",
231
+ {},
232
+ { jsonrpc: "2.0", method: "call", params: { service, method, args }, id: rpcId },
233
+ details,
234
+ );
235
+ if (!response.ok) {
236
+ const missing =
237
+ (response.status >= 300 && response.status < 400) || (response.status === 404 && !isJson);
238
+ const code = missing ? "jsonrpc_unavailable" : "server_error";
239
+ throw new OdooError(code, { ...details, status: response.status });
240
+ }
241
+ if (!isJson || !body || typeof body !== "object") {
242
+ throw new OdooError("invalid_response", { ...details, status: response.status });
243
+ }
244
+ if (body.error) {
245
+ const name = typeof body.error?.data?.name === "string" ? body.error.data.name : "";
246
+ throw new OdooError(RPC_ERRORS[name] || "server_error", details);
247
+ }
248
+ return body.result;
249
+ }
250
+
251
+ function checkJsonRpcSettings({ database, login }) {
252
+ if (typeof database !== "string" || !/^[A-Za-z0-9_.-]+$/.test(database)) {
253
+ throw new TypeError("JSON-RPC needs the database name.");
254
+ }
255
+ if (typeof login !== "string" || !login || /[\p{Cc}]/u.test(login)) {
256
+ throw new TypeError("JSON-RPC needs the login of the API key's user.");
257
+ }
258
+ }
259
+
260
+ // Resolves the user id once per client through service `common`.
261
+ async function authenticateJsonRpc(options) {
262
+ const { database, login, apiKey } = options;
263
+ checkJsonRpcSettings(options);
264
+ const uid = await rpc(options, "common", "authenticate", [database, login, apiKey, {}], {
265
+ method: "authenticate",
266
+ });
267
+ if (!Number.isInteger(uid) || uid <= 0) {
268
+ throw new OdooError("invalid_api_key", { method: "authenticate" });
269
+ }
270
+ return uid;
271
+ }
272
+
273
+ async function callJsonRpc(options) {
274
+ const { database, apiKey, model, method, params = {}, uid } = options || {};
275
+ checkRead({ model, method, params, apiKey });
276
+ checkJsonRpcSettings(options);
277
+ const userId = typeof uid === "function" ? await uid() : uid;
278
+ if (!Number.isInteger(userId)) throw new TypeError("JSON-RPC needs the user id.");
279
+ return rpc(
280
+ options,
281
+ "object",
282
+ "execute_kw",
283
+ [database, userId, apiKey, model, method, [], params],
284
+ { model, method },
285
+ );
286
+ }
287
+
288
+ // Binds connection settings once and pages search_read by id so a large
289
+ // catalog arrives in bounded responses in a stable order.
290
+ function createOdooClient(settings) {
291
+ const base = { ...settings };
292
+ normalizeBaseUrl(base.url);
293
+ const api = base.api || "json2";
294
+ if (!APIS.has(api)) throw new TypeError("api must be json2 or jsonrpc.");
295
+ const pageSize = base.pageSize || DEFAULT_PAGE_SIZE;
296
+ let call;
297
+ if (api === "json2") {
298
+ call = (model, method, params) => callOdoo({ ...base, model, method, params });
299
+ } else {
300
+ checkJsonRpcSettings(base);
301
+ let session = null;
302
+ const uid = () => {
303
+ session ??= authenticateJsonRpc(base);
304
+ return session;
305
+ };
306
+ call = (model, method, params) => callJsonRpc({ ...base, model, method, params, uid });
307
+ }
308
+ return {
309
+ call,
310
+ fieldsGet(model, attributes) {
311
+ return call(model, "fields_get", { attributes });
312
+ },
313
+ async searchRead(model, { domain = [], fields, context } = {}) {
314
+ const rows = [];
315
+ for (let offset = 0; ; offset += pageSize) {
316
+ const params = { domain, fields, offset, limit: pageSize, order: "id" };
317
+ if (context) params.context = context;
318
+ const page = await call(model, "search_read", params);
319
+ if (!Array.isArray(page)) {
320
+ throw new OdooError("invalid_response", { model, method: "search_read" });
321
+ }
322
+ rows.push(...page);
323
+ if (page.length < pageSize) return rows;
324
+ }
325
+ },
326
+ };
327
+ }
328
+
329
+ module.exports = {
330
+ DEFAULT_PAGE_SIZE,
331
+ MAX_RESPONSE_BYTES,
332
+ OdooError,
333
+ READ_METHODS,
334
+ authenticateJsonRpc,
335
+ callJsonRpc,
336
+ callOdoo,
337
+ createOdooClient,
338
+ normalizeBaseUrl,
339
+ postJson: post,
340
+ };