UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

474 lines (473 loc) • 18.9 kB
import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs"; import { C as ReferenceNode, D as IdentifierNode, E as AliasNode, S as ValueNode, T as TableNode, _ as sql, b as ExpressionWrapper, s as getNodeSqliteKysely, v as expressionBuilder, w as ColumnNode } from "./kysely-sync-YJo2lmGV.mjs"; //#region node_modules/.pnpm/kysely@0.29.7/node_modules/kysely/dist/util/json-object-args.js function getJsonObjectArgs(e, t) { const n = []; for (const { selection: r } of e.selections ?? []) if (ReferenceNode.is(r) && ColumnNode.is(r.column)) n.push(colName(r.column.column.name), colRef(t, r.column.column.name)); else if (ColumnNode.is(r)) n.push(colName(r.column.name), colRef(t, r.column.name)); else if (AliasNode.is(r) && IdentifierNode.is(r.alias)) n.push(colName(r.alias.name), colRef(t, r.alias.name)); else throw new Error(`can't extract column names from the select query node`); return n; } function colName(e) { return new ExpressionWrapper(ValueNode.createImmediate(e)); } function colRef(e, t) { return new ExpressionWrapper(ReferenceNode.create(ColumnNode.create(t), TableNode.create(e))); } //#endregion //#region node_modules/.pnpm/kysely@0.29.7/node_modules/kysely/dist/helpers/sqlite.js /** * A SQLite helper for aggregating a subquery into a JSON array. * * NOTE: This helper only works correctly if you've installed the `ParseJSONResultsPlugin`. * Otherwise the nested selections will be returned as JSON strings. * * The plugin can be installed like this: * * ```ts * import * as Sqlite from 'better-sqlite3' * import { Kysely, ParseJSONResultsPlugin, SqliteDialect } from 'kysely' * import type { Database } from 'type-editor' // imaginary module * * const db = new Kysely<Database>({ * dialect: new SqliteDialect({ * database: new Sqlite(':memory:') * }), * plugins: [new ParseJSONResultsPlugin()] * }) * ``` * * ### Examples * * ```ts * import { jsonArrayFrom } from 'kysely/helpers/sqlite' * * const result = await db * .selectFrom('person') * .select((eb) => [ * 'id', * jsonArrayFrom( * eb.selectFrom('pet') * .select(['pet.id as pet_id', 'pet.name']) * .whereRef('pet.owner_id', '=', 'person.id') * .orderBy('pet.name') * ).as('pets') * ]) * .execute() * * result[0]?.id * result[0]?.pets[0].pet_id * result[0]?.pets[0].name * ``` * * The generated SQL (SQLite): * * ```sql * select "id", ( * select coalesce(json_group_array(json_object( * 'pet_id', "agg"."pet_id", * 'name', "agg"."name" * )), '[]') from ( * select "pet"."id" as "pet_id", "pet"."name" * from "pet" * where "pet"."owner_id" = "person"."id" * order by "pet"."name" * ) as "agg" * ) as "pets" * from "person" * ``` */ function jsonArrayFrom$1(e) { return sql`(select coalesce(json_group_array(json_object(${sql.join(getSqliteJsonObjectArgs(e.toOperationNode(), "agg"))})), '[]') from ${e} as agg)`; } /** * A SQLite helper for turning a subquery into a JSON object. * * The subquery must only return one row. * * NOTE: This helper only works correctly if you've installed the `ParseJSONResultsPlugin`. * Otherwise the nested selections will be returned as JSON strings. * * The plugin can be installed like this: * * ```ts * import * as Sqlite from 'better-sqlite3' * import { Kysely, ParseJSONResultsPlugin, SqliteDialect } from 'kysely' * import type { Database } from 'type-editor' // imaginary module * * const db = new Kysely<Database>({ * dialect: new SqliteDialect({ * database: new Sqlite(':memory:') * }), * plugins: [new ParseJSONResultsPlugin()] * }) * ``` * * ### Examples * * ```ts * import { jsonObjectFrom } from 'kysely/helpers/sqlite' * * const result = await db * .selectFrom('person') * .select((eb) => [ * 'id', * jsonObjectFrom( * eb.selectFrom('pet') * .select(['pet.id as pet_id', 'pet.name']) * .whereRef('pet.owner_id', '=', 'person.id') * .where('pet.is_favorite', '=', true) * ).as('favorite_pet') * ]) * .execute() * * result[0]?.id * result[0]?.favorite_pet?.pet_id * result[0]?.favorite_pet?.name * ``` * * The generated SQL (SQLite): * * ```sql * select "id", ( * select json_object( * 'pet_id', "obj"."pet_id", * 'name', "obj"."name" * ) from ( * select "pet"."id" as "pet_id", "pet"."name" * from "pet" * where "pet"."owner_id" = "person"."id" * and "pet"."is_favorite" = ? * ) as obj * ) as "favorite_pet" * from "person"; * ``` */ function jsonObjectFrom$1(e) { return sql`(select json_object(${sql.join(getSqliteJsonObjectArgs(e.toOperationNode(), "obj"))}) from ${e} as obj)`; } function getSqliteJsonObjectArgs(e, t) { try { return getJsonObjectArgs(e, t); } catch { throw new Error("SQLite jsonArrayFrom and jsonObjectFrom functions can only handle explicit selections due to limitations of the json_object function. selectAll() is not allowed in the subquery."); } } //#endregion //#region src/state/json-predicate-fields.ts /** Select raw root members without constructing objects for opaque JSON bodies. */ function scanJsonObjectFields(e, t) { const n = /* @__PURE__ */ new Map(); const r = /* @__PURE__ */ new Map(); const i = /* @__PURE__ */ new Set(); const a = new Set(t); let o = 0; let s = 0; const c = /[\t\n\r ]*/y; const l = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y; const u = /["\\\u0000-\u001f]/g; function fail() { throw new SyntaxError("Invalid JSON predicate source"); } const skipWhitespace = () => { c.lastIndex = o; c.exec(e); o = c.lastIndex; }; const string = () => { if (e[o++] !== "\"") fail(); while (o < e.length) { u.lastIndex = o; const t = u.exec(e); if (!t) fail(); o = u.lastIndex; if (t[0] === "\"") return; if (t[0] !== "\\") fail(); const n = e[o++]; if (n === "u") { if (!/^[0-9a-fA-F]{4}$/.test(e.slice(o, o + 4))) fail(); o += 4; } else if (n === void 0 || !"\"\\/bfnrt".includes(n)) fail(); } fail(); }; const value = (t) => { skipWhitespace(); const c = e[o]; s = Math.max(s, t + (c === "{" || c === "[" ? 1 : 0)); if (c === "\"") { string(); return "string"; } if (c === "{" || c === "[") { const s = c === "{"; const l = s ? "}" : "]"; o++; skipWhitespace(); if (e[o] === l) { o++; return s ? "object" : "array"; } while (o < e.length) { let c; if (s) { const n = o; string(); if (t === 0) c = JSON.parse(e.slice(n, o)); skipWhitespace(); if (e[o++] !== ":") fail(); } skipWhitespace(); const u = o; const d = value(t + 1); if (c !== void 0) { const t = c.indexOf("\0"); const s = t < 0 ? c : c.slice(0, t); const l = a.has(s) && !n.has(s); const f = a.has(c); if (l || f) { const t = { kind: d, text: e.slice(u, o) }; if (l) n.set(s, t); if (f) { if (r.has(c)) i.add(c); r.set(c, t); } } } skipWhitespace(); const f = e[o++]; if (f === l) return s ? "object" : "array"; if (f !== ",") fail(); skipWhitespace(); } fail(); } const u = c === "t" ? "true" : c === "f" ? "false" : c === "n" ? "null" : void 0; if (u && e.startsWith(u, o)) { o += u.length; return u === "null" ? "null" : "boolean"; } l.lastIndex = o; if (!l.test(e)) fail(); o = l.lastIndex; return "number"; }; try { value(0); skipWhitespace(); if (o !== e.length && e[o] !== "\0") fail(); return { valid: true, maximumDepth: s, first: n, last: r, duplicateKeys: i }; } catch { return { valid: false, maximumDepth: s, first: /* @__PURE__ */ new Map(), last: /* @__PURE__ */ new Map(), duplicateKeys: /* @__PURE__ */ new Set() }; } } function readJsonPredicateScalar(e) { if (!e || e.kind === "object" || e.kind === "array") return; return JSON.parse(e.text); } //#endregion //#region src/infra/database-engine/json-values.ts /** Project caller-selected rows as JSON text, retaining their explicit order. */ function jsonArrayFrom(e, t, n) { if (!isPostgresSqlConnection(e)) return jsonArrayFrom$1(t); const r = expressionBuilder(); const i = n.length ? sql`order by ${sql.join(n.map((e) => sql`${r.ref(`agg.${e}`)} asc nulls first`))}` : sql``; return sql`(select coalesce(json_agg(agg ${i}), '[]')::text from ${t} as agg)`; } /** Project at most one caller-selected row, preserving SQL NULL when absent. */ function jsonObjectFrom(e, t) { return isPostgresSqlConnection(e) ? sql`(select row_to_json(obj)::text from ${t} as obj)` : jsonObjectFrom$1(t); } function jsonArrayValue(e, t) { return sql`${sql.raw(isPostgresSqlConnection(e) ? "json_build_array" : "json_array")}(${sql.join(t)})`; } function jsonObjectValue(e, t) { return sql`${sql.raw(isPostgresSqlConnection(e) ? "json_build_object" : "json_object")}(${sql.join(Object.entries(t).flatMap(([e, t]) => [sql.lit(e), t]))})`; } /** Parse serialized JSON while retaining its native type in JSON value arguments. */ function jsonValue(e, t) { return isPostgresSqlConnection(e) ? sql`${t}::json` : sql`json(${t})`; } /** JSON-valued inputs remain JSON instead of becoming quoted strings. */ function jsonOrderedArray(e, t, n, r = "first") { const i = isPostgresSqlConnection(e); let a = expressionBuilder().fn.agg(i ? "json_agg" : "json_group_array", [t]); for (const e of n) a = a.orderBy(e, (e) => r === "first" ? e.asc().nullsFirst() : e.asc()); return i ? sql`coalesce(${a}::text, '[]')` : a; } /** Read a string from a caller-owned JSON tuple. */ function jsonArrayTextElement(e, t, n) { return isPostgresSqlConnection(e) ? getNodeSqliteKysely(e).fn("json_extract_path_text", [sql`${t}::json`, sql.val(String(n))]) : getNodeSqliteKysely(e).fn("json_extract", [t, sql.val(`$[${n}]`)]); } function jsonKeyPath(e) { return `$.${/^[A-Za-z_][A-Za-z0-9_]*$/u.test(e) ? e : JSON.stringify(e)}`; } function jsonExtractText(e, t, n) { const r = expressionBuilder(); return isPostgresSqlConnection(e) ? r.fn("json_extract_path_text", [sql`${t}::json`, r.val(n)]) : r.fn("json_extract", [t, r.val(jsonKeyPath(n))]); } function jsonOrderedTextArray(e, t, n) { return isPostgresSqlConnection(e) ? sql`coalesce(array_to_json(array_agg(${t} order by ${n}))::text, '[]')` : expressionBuilder().fn("json_group_array", [t]); } function jsonRemoveKey(e, t, n) { if (isPostgresSqlConnection(e)) return sql`(${t}::jsonb - ${n}::text)::text`; return expressionBuilder().fn("json_remove", [t, expressionBuilder().val(jsonKeyPath(n))]); } /** SQLite JSON paths at these boundaries name object keys, including nested keys. */ function objectPath(e) { return sql`string_to_array(substr(${e}, 3), '.')`; } function jsonPathValue(e, t, n, r = "text") { if (!isPostgresSqlConnection(e)) return sql`json_extract(${t}, ${n})`; const i = sql`(${t}::jsonb ${sql.raw(r === "json" ? "#>" : "#>>")} ${objectPath(n)})`; return sql`${i}${sql.raw(r === "number" ? "::double precision" : r === "json" ? "::text" : "")}`; } function jsonValid(e, t) { return isPostgresSqlConnection(e) ? sql`pg_input_is_valid(${t}, 'json')` : sql`json_valid(${t})`; } function jsonType(e, t) { return isPostgresSqlConnection(e) ? sql`jsonb_typeof(${t}::jsonb)` : sql`json_type(${t})`; } function jsonRemovePaths(e, t, n) { if (!isPostgresSqlConnection(e)) return sql`json_remove(${t}, ${sql.join(n)})`; let r = sql`${t}::jsonb`; for (const e of n) r = sql`(${r} #- ${objectPath(e)})`; return sql`${r}::text`; } /** Set text/null, or a JSON-producing expression when json is true. */ function jsonSetPath(e, t, n, r, i = false) { if (!isPostgresSqlConnection(e)) return sql`json_set(${t}, ${n}, ${r})`; const a = i ? sql`${r}::jsonb` : sql`to_jsonb(${r}::text)`; return sql`jsonb_set(${t}::jsonb, ${objectPath(n)}, coalesce(${a}, 'null'::jsonb))::text`; } function jsonArrayElements(e, t) { return sql`${sql.raw(isPostgresSqlConnection(e) ? "jsonb_array_elements" : "json_each")}(${t}${sql.raw(isPostgresSqlConnection(e) ? "::jsonb" : "")})`; } function jsonPickObject(e, t, n) { return isPostgresSqlConnection(e) ? sql`(SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb)::text FROM jsonb_each(CASE WHEN jsonb_typeof(${t}::jsonb) = 'object' THEN ${t}::jsonb ELSE '{}'::jsonb END) WHERE key IN (${sql.join(n)}))` : sql`(SELECT json_group_object(key, CASE type WHEN 'object' THEN json(value) WHEN 'array' THEN json(value) WHEN 'true' THEN json('true') WHEN 'false' THEN json('false') ELSE value END) FROM json_each(${t}) WHERE key IN (${sql.join(n)}))`; } /** Whether native JSON field access can decode this value without losing escaped code units. */ function jsonNativeFieldsValid(e, t) { return isPostgresSqlConnection(e) ? sql`coalesce(pg_input_is_valid(${t}, 'jsonb'), false)` : sql`coalesce(json_valid(${t}), 0)`; } /** * Compact native JSON for the lexical scanner, preserving duplicate member order. * Malformed/deep input and PostgreSQL values with undecodable escapes retain raw * text. SQLite also retains escaped NULs because JSON aggregation truncates member * names at NUL. Callers select tokens with scanJsonObjectFields, never hydrate the * returned document. */ function jsonObjectFieldsForScan(e, t, n) { const r = expressionBuilder(); if (!isPostgresSqlConnection(e)) { const projectSqlite = (e, t, n) => { const i = `sqlite_field_${n}`; const a = r.ref(`${i}.key`); const o = r.ref(`${i}.value`); const s = r.ref(`${i}.type`); const c = r.fn("json_each", [e]).as(i); const l = Object.entries(t).filter((e) => e[1] !== true); const u = sql`CASE ${s} WHEN 'object' THEN json(${o}) WHEN 'array' THEN json(${o}) WHEN 'true' THEN json('true') WHEN 'false' THEN json('false') ELSE ${o} END`; const d = l.length === 0 ? u : sql`CASE ${sql.join(l.map(([e, t]) => sql`WHEN ${a} = ${sql.lit(e)} AND ${s} = 'object' THEN json(${projectSqlite(o, t, n + 1)})`), sql` `)} ELSE ${u} END`; return sql`(SELECT json_group_object(${a}, ${d}) FROM ${c} WHERE ${a} IN (${sql.join(Object.keys(t).map((e) => sql.lit(e)))}))`; }; return sql`CASE WHEN json_valid(${t}) AND instr(${t}, ${String.raw`\u0000`}) = 0 THEN CASE WHEN json_type(${t}) = 'object' THEN ${projectSqlite(t, n, 0)} ELSE ${t} END ELSE ${t} END`; } const project = (e, t, n) => { const i = `json_field_${n}`; const a = r.ref(`${i}.key`); const o = r.ref(`${i}.value`); const s = r.ref(`${i}.ordinality`); const c = sql`CASE WHEN json_typeof(${e}) = 'object' THEN ${e} ELSE '{}'::json END`; const l = sql`${r.fn("json_each", [c])} WITH ORDINALITY`.as(i); const u = Object.entries(t).filter((e) => e[1] !== true); const d = u.length === 0 ? o : sql`CASE ${sql.join(u.map(([e, t]) => sql`WHEN ${a} = ${sql.lit(e)} AND json_typeof(${o}) = 'object' THEN ${project(o, t, n + 1)}`), sql` `)} ELSE ${o} END`; return sql`(SELECT coalesce(json_object_agg(${a}, ${d} ORDER BY ${s}), '{}'::json) FROM ${l} WHERE ${a} IN (${sql.join(Object.keys(t).map((e) => sql.lit(e)))}))`; }; return sql`CASE WHEN ${jsonNativeFieldsValid(e, t)} THEN CASE WHEN json_typeof(${t}::json) = 'object' THEN ${project(sql`${t}::json`, n, 0)}::text ELSE ${t} END ELSE ${t} END`; } /** First-member string lookup, used only as a native candidate filter; exceptional text needs the scanner. */ function jsonFirstStringValue(e, t, n) { if (!isPostgresSqlConnection(e)) { const e = n.reduce((e, t) => `${e}.${/^[A-Za-z_][A-Za-z0-9_]*$/u.test(t) ? t : JSON.stringify(t)}`, "$"); return sql`CASE WHEN json_valid(${t}) THEN CASE WHEN json_type(${t}, ${sql.lit(e)}) = 'text' THEN json_extract(${t}, ${sql.lit(e)}) END END`; } const r = expressionBuilder(); let i = sql`${t}::json`; for (const [e, t] of n.entries()) { const n = `first_field_${e}`; const a = sql`CASE WHEN json_typeof(${i}) = 'object' THEN ${i} ELSE '{}'::json END`; const o = sql`${r.fn("json_each", [a])} WITH ORDINALITY`.as(n); i = sql`(SELECT ${r.ref(`${n}.value`)} FROM ${o} WHERE ${r.ref(`${n}.key`)} = ${t} ORDER BY ${r.ref(`${n}.ordinality`)} LIMIT 1)`; } return sql`CASE WHEN ${jsonNativeFieldsValid(e, t)} THEN CASE WHEN json_typeof(${i}) = 'string' THEN ${i} #>> '{}' END END`; } /** Last-member string lookup matching JSON.parse; exceptional input remains caller-owned. */ function jsonLastStringValue(e, t, n) { let r; if (isPostgresSqlConnection(e)) { const e = sql`(${t}::jsonb #> ARRAY[${sql.join(n.map((e) => sql.lit(e)))}]::text[])`; r = sql`CASE WHEN jsonb_typeof(${e}) = 'string' THEN ${e} #>> '{}' END`; } else { const i = getNodeSqliteKysely(e); let a = t; for (const [e, t] of n.entries()) { const r = e === n.length - 1; const o = i.fn("json_each", [a]).as("member"); a = i.selectFrom(o).select((e) => e.case().when("member.type", "=", r ? "text" : "object").then(e.ref("member.value")).else(r ? null : "{}").end().as("value")).where("member.key", "=", t).orderBy("member.id", "desc").limit(1); } r = sql`${a}`; } return sql`CASE WHEN ${jsonNativeFieldsValid(e, t)} THEN ${r} END`; } /** Enumerate every string-valued object member, including duplicate keys. */ function jsonObjectStringEntries(e, t) { return isPostgresSqlConnection(e) ? sql`(SELECT key, value #>> '{}' AS value FROM json_each(CASE WHEN ${jsonNativeFieldsValid(e, t)} THEN CASE WHEN json_typeof(${t}::json) = 'object' THEN ${t}::json ELSE '{}'::json END ELSE '{}'::json END) WHERE json_typeof(value) = 'string')` : sql`(SELECT key, value FROM json_each(CASE WHEN json_valid(${t}) THEN ${t} ELSE '{}' END) WHERE type = 'text')`; } /** Decode one extracted JSON1 value without constructing unrelated object fields. */ function jsonScannedValue(e, t) { if (!e) return null; if (e.kind === "object" || e.kind === "array") return JSON.parse(e.text); const n = readJsonPredicateScalar(e); if (t === "numeric" && typeof n === "string") { const e = n.indexOf("\0"); const t = e < 0 ? n : n.slice(0, e); if (/^[\t\n\v\f\r ]*[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[\t\n\v\f\r ]*$/u.test(t)) return Number(t); } return typeof n === "string" ? n.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "���") : typeof n === "boolean" ? Number(n) : n; } //#endregion export { jsonValue as C, jsonValid as S, scanJsonObjectFields as T, jsonRemoveKey as _, jsonExtractText as a, jsonSetPath as b, jsonNativeFieldsValid as c, jsonObjectStringEntries as d, jsonObjectValue as f, jsonPickObject as g, jsonPathValue as h, jsonArrayValue as i, jsonObjectFieldsForScan as l, jsonOrderedTextArray as m, jsonArrayFrom as n, jsonFirstStringValue as o, jsonOrderedArray as p, jsonArrayTextElement as r, jsonLastStringValue as s, jsonArrayElements as t, jsonObjectFrom as u, jsonRemovePaths as v, readJsonPredicateScalar as w, jsonType as x, jsonScannedValue as y };