symmetria 3.6.0 → 3.7.1

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.
Files changed (70) hide show
  1. package/dist/better-auth.js +1 -1
  2. package/dist/{binding-QAk-KW4L.js → binding-evmthxTh.js} +2 -2
  3. package/dist/{binding-QAk-KW4L.js.map → binding-evmthxTh.js.map} +1 -1
  4. package/dist/bun.d.ts +2 -2
  5. package/dist/bun.js +2 -2
  6. package/dist/cohere.d.ts +1 -1
  7. package/dist/cohere.js +1 -1
  8. package/dist/{compile-D02-A2r9.js → compile-BXdzzNE_.js} +27 -17
  9. package/dist/compile-BXdzzNE_.js.map +1 -0
  10. package/dist/{core-BHndSuCB.js → core-DL4rAoIx.js} +30 -8
  11. package/dist/core-DL4rAoIx.js.map +1 -0
  12. package/dist/driver.d.ts +3 -3
  13. package/dist/driver.js +2 -2
  14. package/dist/google.d.ts +1 -1
  15. package/dist/google.js +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.js +225 -67
  18. package/dist/index.js.map +1 -1
  19. package/dist/{inspection-DK0UJaG0.js → inspection-UwhuSrBe.js} +4 -4
  20. package/dist/{inspection-DK0UJaG0.js.map → inspection-UwhuSrBe.js.map} +1 -1
  21. package/dist/internal.d.ts +6 -2
  22. package/dist/internal.js +6 -5
  23. package/dist/jina.d.ts +1 -1
  24. package/dist/jina.js +1 -1
  25. package/dist/{metadata-BzA69T0R.js → metadata-kSK6_Ygx.js} +2 -2
  26. package/dist/{metadata-BzA69T0R.js.map → metadata-kSK6_Ygx.js.map} +1 -1
  27. package/dist/mistral.d.ts +1 -1
  28. package/dist/mistral.js +1 -1
  29. package/dist/ollama.d.ts +1 -1
  30. package/dist/ollama.js +1 -1
  31. package/dist/openai.d.ts +1 -1
  32. package/dist/openai.js +1 -1
  33. package/dist/opentelemetry.d.ts +1 -1
  34. package/dist/opentelemetry.js +2 -2
  35. package/dist/{pg-CcmvCsRo.d.ts → pg-C1ao8jyc.d.ts} +3 -3
  36. package/dist/{pg-DxC503O5.js → pg-CWyQOkxm.js} +43 -20
  37. package/dist/pg-CWyQOkxm.js.map +1 -0
  38. package/dist/pg.d.ts +3 -3
  39. package/dist/pg.js +2 -2
  40. package/dist/{pool-BTrHoEWY.js → pool-CEeO5spd.js} +4 -4
  41. package/dist/{pool-BTrHoEWY.js.map → pool-CEeO5spd.js.map} +1 -1
  42. package/dist/{pool-C7rw4zkO.d.ts → pool-CRsOlJ3h.d.ts} +2 -2
  43. package/dist/{profiling-DMJLtQEj.js → profiling-CeH3c42X.js} +4 -4
  44. package/dist/{profiling-DMJLtQEj.js.map → profiling-CeH3c42X.js.map} +1 -1
  45. package/dist/{search-BeNPJPTA.js → search-0TyudCVL.js} +3 -3
  46. package/dist/{search-BeNPJPTA.js.map → search-0TyudCVL.js.map} +1 -1
  47. package/dist/{search-BRkAlGfT.js → search-gbO7xe_u.js} +6 -6
  48. package/dist/{search-BRkAlGfT.js.map → search-gbO7xe_u.js.map} +1 -1
  49. package/dist/search.d.ts +1 -1
  50. package/dist/search.js +1 -1
  51. package/dist/{table-AFCbXHL8.js → table-Cgtbk2zk.js} +10 -7
  52. package/dist/table-Cgtbk2zk.js.map +1 -0
  53. package/dist/timestamp-key-MxtHruRY.js +26 -0
  54. package/dist/timestamp-key-MxtHruRY.js.map +1 -0
  55. package/dist/{types-t7LyUyKP.d.ts → types--seX1C2D.d.ts} +32 -9
  56. package/dist/{types-CBBesvuC.js → types-BKbG6MO1.js} +34 -4
  57. package/dist/types-BKbG6MO1.js.map +1 -0
  58. package/dist/{values-BxqBvh27.js → values-CkYX-ZMl.js} +3 -3
  59. package/dist/values-CkYX-ZMl.js.map +1 -0
  60. package/dist/vector.d.ts +1 -1
  61. package/dist/vector.js +2 -2
  62. package/dist/voyage.d.ts +1 -1
  63. package/dist/voyage.js +1 -1
  64. package/package.json +1 -1
  65. package/dist/compile-D02-A2r9.js.map +0 -1
  66. package/dist/core-BHndSuCB.js.map +0 -1
  67. package/dist/pg-DxC503O5.js.map +0 -1
  68. package/dist/table-AFCbXHL8.js.map +0 -1
  69. package/dist/types-CBBesvuC.js.map +0 -1
  70. package/dist/values-BxqBvh27.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { S as not, T as or, g as coalesce, m as and } from "./core-BHndSuCB.js";
1
+ import { C as not, E as or, g as coalesce, m as and } from "./core-DL4rAoIx.js";
2
2
  import { createAdapterFactory } from "better-auth/adapters";
3
3
  //#region src/entries/better-auth.ts
4
4
  const escapeLike = (value) => String(value).replace(/[\\%_]/g, (character) => `\\${character}`);
@@ -1,4 +1,4 @@
1
- import { r as IsolationLevel } from "./types-CBBesvuC.js";
1
+ import { r as IsolationLevel } from "./types-BKbG6MO1.js";
2
2
  import { a as scopeViolation } from "./errors-CLFkJWgJ.js";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  //#region src/driver/serial.ts
@@ -270,4 +270,4 @@ const createDatabase = ({ schema: model, driver }) => {
270
270
  //#endregion
271
271
  export { whenCursorEnds as a, createSerialQueue as c, holders as d, nestedFrame as f, transactionOptionsSQL as i, currentFrame as l, runInFrame as m, createDatabase as n, createPendingTasks as o, runHolding as p, runTransaction as r, callerInside as s, SCHEMA_BIND as t, currentHolders as u };
272
272
 
273
- //# sourceMappingURL=binding-QAk-KW4L.js.map
273
+ //# sourceMappingURL=binding-evmthxTh.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"binding-QAk-KW4L.js","names":[],"sources":["../src/driver/serial.ts","../src/driver/pending.ts","../src/driver/transactions.ts","../src/schema/binding.ts"],"sourcesContent":["/**\n * Ordering on a reserved connection, shared by sessions and transactions: one\n * operation at a time in call order, and the async context that tells whether\n * a call comes from inside a nested callback that holds the connection.\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\ntype SerialQueue = {\n readonly run: <Value>(operation: () => Promise<Value>) => Promise<Value>;\n};\n\nconst ignore = () => {};\n\n/**\n * Runs each operation after the previous one settled. node-postgres\n * deprecates overlapping `client.query()` calls; Bun.SQL would pipeline them.\n */\nexport const createSerialQueue = (): SerialQueue => {\n let tail: Promise<unknown> = Promise.resolve();\n\n return {\n run: (operation) => {\n const result = tail.then(operation);\n tail = result.then(ignore, ignore);\n\n return result;\n },\n };\n};\n\n/** A nested callback (savepoint or session transaction) that holds its parent's connection. */\nexport type NestedFrame = { readonly parent: NestedFrame | undefined };\n\nconst frames = new AsyncLocalStorage<NestedFrame>();\n\n/** A frame for a nested callback started from the current context. */\nexport const nestedFrame = (): NestedFrame => ({ parent: frames.getStore() });\n\n/** Runs the nested operation so that calls made from its callbacks are recognised. */\nexport const runInFrame = <Value>(\n frame: NestedFrame,\n operation: () => Promise<Value>,\n): Promise<Value> => frames.run(frame, operation);\n\n/**\n * A pool connection the running code holds through a transaction, session or\n * stream loop of that pool; see `free()` in pool.ts.\n */\nexport type Holder = {\n readonly pool: object;\n open: boolean;\n readonly stream?: true;\n /**\n * The stream claim this entry stands for in the code that started the\n * stream, which may or may not be the code that reads it (see `free()`).\n */\n readonly started?: Holder;\n /** How many rows the stream's reader has asked for so far. */\n progress?: () => number;\n /** Whether the stream is busy: its reader asked for a row it fetches or hands out. */\n busy?: () => boolean;\n};\n\n/** The holders of the running code, of every pool, carried as its async context. */\nexport const holders = new AsyncLocalStorage<readonly Holder[]>();\n\n/**\n * What the running code holds: the nested callback it runs in and the pool\n * connections. A read that starts later than it was made runs in the context\n * where it was made, but with these from where it starts, so that it is\n * refused where it would wait for itself instead of waiting forever.\n */\nexport const currentFrame = (): NestedFrame | undefined => frames.getStore();\n\nexport const currentHolders = (): readonly Holder[] | undefined =>\n holders.getStore();\n\nexport const runHolding = <Value>(\n frame: NestedFrame | undefined,\n held: readonly Holder[] | undefined,\n run: () => Value,\n): Value => frames.run(frame!, () => holders.run(held!, run));\n\n/**\n * Whether the caller runs inside the frame. A parent operation queued behind\n * its nested callback while that callback waits for it would never run.\n */\nexport const callerInside = (frame: NestedFrame): boolean => {\n for (let current = frames.getStore(); current; current = current.parent) {\n if (current === frame) {\n return true;\n }\n }\n\n return false;\n};\n","/**\n * In-flight promise tracking shared by the pool, sessions and transactions:\n * a scope settles everything it started before it closes or releases its\n * connection, and rejections are observed so they never surface as unhandled.\n */\ntype PendingTasks = {\n readonly track: <Value>(task: Promise<Value>) => Promise<Value>;\n readonly size: () => number;\n /** Resolves once every tracked task has settled; never rejects. */\n readonly settle: () => Promise<void>;\n};\n\nexport const createPendingTasks = (): PendingTasks => {\n const pending = new Set<Promise<unknown>>();\n\n return {\n track: (task) => {\n pending.add(task);\n\n const done = () => {\n pending.delete(task);\n };\n\n void task.then(done, done);\n\n return task;\n },\n size: () => pending.size,\n settle: async () => {\n await Promise.allSettled([...pending]);\n },\n };\n};\n","/**\n * Transaction lifecycle shared by both adapters: BEGIN options, savepoints, scope poisoning after a\n * failed statement, one operation at a time per connection and nested-scope serialisation.\n */\nimport {\n IsolationLevel,\n type CompiledQuery,\n type ExecutionResult,\n type TransactionDriver,\n type TransactionOptions,\n} from \"../query/plan/types\";\nimport type { PostgresConnection } from \"./pool\";\nimport { scopeViolation } from \"./errors\";\nimport { createPendingTasks } from \"./pending\";\nimport {\n callerInside,\n createSerialQueue,\n nestedFrame,\n runInFrame,\n type NestedFrame,\n} from \"./serial\";\n\nconst transactionStatements = (): TransactionStatements<PostgresConnection> => {\n let nextSavepoint = 0;\n\n const execute = (connection: PostgresConnection, sql: string) =>\n connection.execute({ sql, parameters: [] });\n\n return {\n execute: (connection, query) => connection.execute(query),\n savepoint: async (connection, callback) => {\n const name = `symmetria_savepoint_${++nextSavepoint}`;\n await execute(connection, `SAVEPOINT ${name}`);\n\n try {\n const result = await callback(connection);\n await execute(connection, `RELEASE SAVEPOINT ${name}`);\n\n return result;\n } catch (error) {\n try {\n await execute(connection, `ROLLBACK TO SAVEPOINT ${name}`);\n await execute(connection, `RELEASE SAVEPOINT ${name}`);\n } catch (rollbackError) {\n throw Object.assign(\n rollbackError instanceof Error\n ? rollbackError\n : new Error(String(rollbackError)),\n { cause: error },\n );\n }\n\n throw error;\n }\n },\n };\n};\n\nexport const runTransaction = async <Result>(\n connection: PostgresConnection,\n callback: (driver: TransactionDriver) => Promise<Result>,\n options?: TransactionOptions,\n): Promise<Result> => {\n const settings = transactionOptionsSQL(options);\n\n await connection.execute({\n sql: `BEGIN${settings ? ` ${settings}` : \"\"}`,\n parameters: [],\n });\n\n try {\n const result = await transactionScope(\n connection,\n transactionStatements(),\n callback,\n );\n await connection.execute({ sql: \"COMMIT\", parameters: [] });\n\n return result;\n } catch (error) {\n try {\n await connection.execute({ sql: \"ROLLBACK\", parameters: [] });\n } catch (rollbackError) {\n connection.release(\n rollbackError instanceof Error\n ? rollbackError\n : new Error(String(rollbackError)),\n );\n }\n\n throw error;\n }\n};\n\nexport const transactionOptionsSQL = (\n options: TransactionOptions = {},\n): string => {\n const fragments: string[] = [];\n\n if (options.isolationLevel !== undefined) {\n if (\n ![\n IsolationLevel.ReadCommitted,\n IsolationLevel.RepeatableRead,\n IsolationLevel.Serializable,\n ].includes(options.isolationLevel)\n ) {\n throw new Error(\"symmetria: invalid transaction isolation level\");\n }\n\n fragments.push(`ISOLATION LEVEL ${options.isolationLevel.toUpperCase()}`);\n }\n\n for (const name of [\"readOnly\", \"deferrable\"] as const) {\n if (options[name] !== undefined && typeof options[name] !== \"boolean\") {\n throw new Error(`symmetria: ${name} must be a boolean`);\n }\n }\n\n if (options.readOnly !== undefined) {\n fragments.push(options.readOnly ? \"READ ONLY\" : \"READ WRITE\");\n }\n\n if (\n options.deferrable === true &&\n (options.isolationLevel !== IsolationLevel.Serializable ||\n options.readOnly !== true)\n ) {\n throw new Error(\"symmetria: DEFERRABLE requires SERIALIZABLE READ ONLY\");\n }\n\n if (options.deferrable !== undefined) {\n fragments.push(options.deferrable ? \"DEFERRABLE\" : \"NOT DEFERRABLE\");\n }\n\n return fragments.join(\", \");\n};\n\n/** Connection-specific statement execution and savepoint handling for a transaction scope. */\ntype TransactionStatements<Connection> = {\n readonly execute: (\n connection: Connection,\n query: CompiledQuery,\n ) => Promise<ExecutionResult>;\n readonly savepoint: <Result>(\n connection: Connection,\n callback: (connection: Connection) => Promise<Result>,\n ) => Promise<Result>;\n};\n\n/** The cursor of a `stream()` (see streamRows in query/select/query.ts). */\nconst STREAM_CURSOR = /^(DECLARE|CLOSE) (\"__symmetria_stream_\\d+\")/;\n\n/** What each open stream does when its transaction ends under it, by cursor name. */\nconst cursorEndings = new Map<string, () => void>();\n\n/**\n * Called when the transaction or savepoint that declared this cursor ends\n * while the cursor is still open: it rolled back, and so did the cursor. A\n * stream then stops instead of handing out rows it fetched before. Returns\n * the function that stops listening.\n */\nexport const whenCursorEnds = (\n cursor: string,\n ended: () => void,\n): (() => void) => {\n cursorEndings.set(cursor, ended);\n\n return () => {\n cursorEndings.delete(cursor);\n };\n};\n\nconst NO_ROWS: ExecutionResult = Object.freeze({ rows: [], affectedRows: 0 });\n\n/** What an operation still waiting to start returns once the scope has closed. */\nconst ABANDONED = Symbol(\"symmetria.abandoned\");\n\n/**\n * Shared transaction lifecycle: operations run one at a time in call order,\n * closed contexts reject late queries, a failed statement poisons the scope,\n * and a nested savepoint holds the connection until it ends; parent operations\n * issued meanwhile wait for it. An operation still pending when the callback\n * returns rejects, since the transaction then rolls back.\n */\nconst transactionScope = async <Connection, Result>(\n connection: Connection,\n statements: TransactionStatements<Connection>,\n callback: (driver: TransactionDriver) => Promise<Result>,\n): Promise<Result> => {\n const pending = createPendingTasks();\n const queue = createSerialQueue();\n // Cursors of streams that have not finished: open work like a pending query.\n const cursors = new Set<string>();\n // Streams of this scope that ended inside its savepoint: closed after it.\n const closeAfterNested: CompiledQuery[] = [];\n\n let closed = false;\n let unsettled = 0;\n let nested: NestedFrame | undefined;\n let failure: { error: unknown } | undefined;\n\n const close = (): void => {\n if (closed) {\n return;\n }\n\n closed = true;\n\n for (const cursor of cursors) {\n cursorEndings.get(cursor)?.();\n // Also for an iterator dropped halfway, which never stops listening.\n cursorEndings.delete(cursor);\n }\n };\n\n const assertAvailable = (): void => {\n if (closed) {\n throw new Error(\"symmetria: transaction context is closed\");\n }\n\n // Queued behind the nested transaction, a call from inside its own\n // callback would wait for itself.\n if (nested && callerInside(nested)) {\n throw new Error(\n \"symmetria: await the nested transaction before using its parent context\",\n );\n }\n\n if (failure) {\n throw failure.error;\n }\n };\n\n // A failed statement poisons the scope; savepoints report through their own scope.\n const schedule = <Value>(\n operation: () => Promise<Value>,\n statement: boolean,\n ): Promise<Value> => {\n unsettled += 1;\n\n return pending.track(\n queue\n .run(async (): Promise<Value | typeof ABANDONED> => {\n if (closed) {\n return ABANDONED;\n }\n\n if (failure) {\n throw failure.error;\n }\n\n return operation();\n })\n .then(\n (value) => {\n unsettled -= 1;\n\n if (closed) {\n throw new Error(\n \"symmetria: the transaction ended before this operation was awaited; it was rolled back\",\n );\n }\n\n return value as Value;\n },\n (error: unknown) => {\n unsettled -= 1;\n\n if (!statement) {\n throw error;\n }\n\n // Later operations report a failed $scope() write check as such too.\n const reported = scopeViolation(error);\n failure ??= { error: reported };\n\n throw reported;\n },\n ),\n );\n };\n\n const driver: TransactionDriver = Object.freeze({\n execute: (query) => {\n const cursor = STREAM_CURSOR.exec(query.sql);\n\n // A stream of this scope left inside one of its savepoints (`break`,\n // or a fetch refused there): the savepoint holds the connection, and\n // the code waiting for this CLOSE would hold up the savepoint, so the\n // cursor is closed as soon as the savepoint ends.\n if (\n cursor?.[1] === \"CLOSE\" &&\n !closed &&\n nested &&\n callerInside(nested) &&\n cursors.delete(cursor[2]!)\n ) {\n closeAfterNested.push(query);\n\n return Promise.resolve(NO_ROWS);\n }\n\n try {\n assertAvailable();\n } catch (error) {\n return Promise.reject(error);\n }\n\n return schedule(async () => {\n if (cursor?.[1] === \"CLOSE\") {\n cursors.delete(cursor[2]!);\n }\n\n const result = await statements.execute(connection, query);\n\n if (cursor?.[1] === \"DECLARE\") {\n cursors.add(cursor[2]!);\n }\n\n return result;\n }, true);\n },\n transaction: async <Value>(\n callback: (driver: TransactionDriver) => Promise<Value>,\n ): Promise<Value> => {\n assertAvailable();\n const frame = nestedFrame();\n\n return schedule(async () => {\n nested = frame;\n\n try {\n return await runInFrame(frame, () =>\n statements.savepoint(connection, (reserved) =>\n transactionScope(reserved, statements, callback),\n ),\n );\n } finally {\n nested = undefined;\n\n for (const query of closeAfterNested.splice(0)) {\n try {\n await statements.execute(connection, query);\n } catch (error) {\n failure ??= { error };\n }\n }\n }\n }, false);\n },\n });\n\n try {\n const result = await callback(driver);\n close();\n const unfinished = unsettled > 0;\n const streaming = cursors.size > 0;\n\n await pending.settle();\n\n if (failure) {\n throw failure.error;\n }\n\n if (unfinished) {\n throw new Error(\n \"symmetria: await all transaction operations before returning from the callback\",\n );\n }\n\n if (streaming) {\n throw new Error(\n \"symmetria: finish or break out of every stream() before returning from the transaction callback\",\n );\n }\n\n return result;\n } finally {\n close();\n await pending.settle();\n }\n};\n","import type { Driver } from \"../query/plan/types\";\n\n/** Rebind compiled schema metadata without evaluating declaration callbacks again. */\nexport const SCHEMA_BIND = Symbol(\"symmetria.schema.bind\");\nexport type BindableSchema = {\n readonly [SCHEMA_BIND]: (driver: Driver) => unknown;\n};\n\nexport type DatabaseOptions<Model extends BindableSchema> = {\n readonly schema: Model;\n readonly driver: Driver;\n};\n\n/** Bind a reusable schema to a driver, retaining its inferred query API and scopes. */\nexport const createDatabase = <Model extends BindableSchema>({\n schema: model,\n driver,\n}: DatabaseOptions<Model>): ReturnType<Model[typeof SCHEMA_BIND]> => {\n if (!model || typeof model[SCHEMA_BIND] !== \"function\") {\n throw new Error(\n \"symmetria: createDatabase() expects a schema() declaration\",\n );\n }\n\n return model[SCHEMA_BIND](driver) as ReturnType<Model[typeof SCHEMA_BIND]>;\n};\n"],"mappings":";;;;;;;;;AAWA,MAAM,eAAe,CAAC;;;;;AAMtB,MAAa,0BAAuC;CAClD,IAAI,OAAyB,QAAQ,QAAQ;CAE7C,OAAO,EACL,MAAM,cAAc;EAClB,MAAM,SAAS,KAAK,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;GACF,GAAG,KAAK;EACV;CACF,CAAC;CAED,IAAI;EACF,MAAM,SAAS,MAAM,SAAS,MAAM;EACpC,MAAM;EACN,MAAM,aAAa,YAAY;EAC/B,MAAM,YAAY,QAAQ,OAAO;EAEjC,MAAM,QAAQ,OAAO;EAErB,IAAI,SACF,MAAM,QAAQ;EAGhB,IAAI,YACF,MAAM,IAAI,MACR,gFACF;EAGF,IAAI,WACF,MAAM,IAAI,MACR,iGACF;EAGF,OAAO;CACT,UAAU;EACR,MAAM;EACN,MAAM,QAAQ,OAAO;CACvB;AACF;;;;AC3XA,MAAa,cAAc,OAAO,uBAAuB;;AAWzD,MAAa,kBAAgD,EAC3D,QAAQ,OACR,aACmE;CACnE,IAAI,CAAC,SAAS,OAAO,MAAM,iBAAiB,YAC1C,MAAM,IAAI,MACR,4DACF;CAGF,OAAO,MAAM,YAAY,CAAC,MAAM;AAClC"}
1
+ {"version":3,"file":"binding-evmthxTh.js","names":[],"sources":["../src/driver/serial.ts","../src/driver/pending.ts","../src/driver/transactions.ts","../src/schema/binding.ts"],"sourcesContent":["/**\n * Ordering on a reserved connection, shared by sessions and transactions: one\n * operation at a time in call order, and the async context that tells whether\n * a call comes from inside a nested callback that holds the connection.\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\ntype SerialQueue = {\n readonly run: <Value>(operation: () => Promise<Value>) => Promise<Value>;\n};\n\nconst ignore = () => {};\n\n/**\n * Runs each operation after the previous one settled. node-postgres\n * deprecates overlapping `client.query()` calls; Bun.SQL would pipeline them.\n */\nexport const createSerialQueue = (): SerialQueue => {\n let tail: Promise<unknown> = Promise.resolve();\n\n return {\n run: (operation) => {\n const result = tail.then(operation);\n tail = result.then(ignore, ignore);\n\n return result;\n },\n };\n};\n\n/** A nested callback (savepoint or session transaction) that holds its parent's connection. */\nexport type NestedFrame = { readonly parent: NestedFrame | undefined };\n\nconst frames = new AsyncLocalStorage<NestedFrame>();\n\n/** A frame for a nested callback started from the current context. */\nexport const nestedFrame = (): NestedFrame => ({ parent: frames.getStore() });\n\n/** Runs the nested operation so that calls made from its callbacks are recognised. */\nexport const runInFrame = <Value>(\n frame: NestedFrame,\n operation: () => Promise<Value>,\n): Promise<Value> => frames.run(frame, operation);\n\n/**\n * A pool connection the running code holds through a transaction, session or\n * stream loop of that pool; see `free()` in pool.ts.\n */\nexport type Holder = {\n readonly pool: object;\n open: boolean;\n readonly stream?: true;\n /**\n * The stream claim this entry stands for in the code that started the\n * stream, which may or may not be the code that reads it (see `free()`).\n */\n readonly started?: Holder;\n /** How many rows the stream's reader has asked for so far. */\n progress?: () => number;\n /** Whether the stream is busy: its reader asked for a row it fetches or hands out. */\n busy?: () => boolean;\n};\n\n/** The holders of the running code, of every pool, carried as its async context. */\nexport const holders = new AsyncLocalStorage<readonly Holder[]>();\n\n/**\n * What the running code holds: the nested callback it runs in and the pool\n * connections. A read that starts later than it was made runs in the context\n * where it was made, but with these from where it starts, so that it is\n * refused where it would wait for itself instead of waiting forever.\n */\nexport const currentFrame = (): NestedFrame | undefined => frames.getStore();\n\nexport const currentHolders = (): readonly Holder[] | undefined =>\n holders.getStore();\n\nexport const runHolding = <Value>(\n frame: NestedFrame | undefined,\n held: readonly Holder[] | undefined,\n run: () => Value,\n): Value => frames.run(frame!, () => holders.run(held!, run));\n\n/**\n * Whether the caller runs inside the frame. A parent operation queued behind\n * its nested callback while that callback waits for it would never run.\n */\nexport const callerInside = (frame: NestedFrame): boolean => {\n for (let current = frames.getStore(); current; current = current.parent) {\n if (current === frame) {\n return true;\n }\n }\n\n return false;\n};\n","/**\n * In-flight promise tracking shared by the pool, sessions and transactions:\n * a scope settles everything it started before it closes or releases its\n * connection, and rejections are observed so they never surface as unhandled.\n */\ntype PendingTasks = {\n readonly track: <Value>(task: Promise<Value>) => Promise<Value>;\n readonly size: () => number;\n /** Resolves once every tracked task has settled; never rejects. */\n readonly settle: () => Promise<void>;\n};\n\nexport const createPendingTasks = (): PendingTasks => {\n const pending = new Set<Promise<unknown>>();\n\n return {\n track: (task) => {\n pending.add(task);\n\n const done = () => {\n pending.delete(task);\n };\n\n void task.then(done, done);\n\n return task;\n },\n size: () => pending.size,\n settle: async () => {\n await Promise.allSettled([...pending]);\n },\n };\n};\n","/**\n * Transaction lifecycle shared by both adapters: BEGIN options, savepoints, scope poisoning after a\n * failed statement, one operation at a time per connection and nested-scope serialisation.\n */\nimport {\n IsolationLevel,\n type CompiledQuery,\n type ExecutionResult,\n type TransactionDriver,\n type TransactionOptions,\n} from \"../query/plan/types\";\nimport type { PostgresConnection } from \"./pool\";\nimport { scopeViolation } from \"./errors\";\nimport { createPendingTasks } from \"./pending\";\nimport {\n callerInside,\n createSerialQueue,\n nestedFrame,\n runInFrame,\n type NestedFrame,\n} from \"./serial\";\n\nconst transactionStatements = (): TransactionStatements<PostgresConnection> => {\n let nextSavepoint = 0;\n\n const execute = (connection: PostgresConnection, sql: string) =>\n connection.execute({ sql, parameters: [] });\n\n return {\n execute: (connection, query) => connection.execute(query),\n savepoint: async (connection, callback) => {\n const name = `symmetria_savepoint_${++nextSavepoint}`;\n await execute(connection, `SAVEPOINT ${name}`);\n\n try {\n const result = await callback(connection);\n await execute(connection, `RELEASE SAVEPOINT ${name}`);\n\n return result;\n } catch (error) {\n try {\n await execute(connection, `ROLLBACK TO SAVEPOINT ${name}`);\n await execute(connection, `RELEASE SAVEPOINT ${name}`);\n } catch (rollbackError) {\n throw Object.assign(\n rollbackError instanceof Error\n ? rollbackError\n : new Error(String(rollbackError)),\n { cause: error },\n );\n }\n\n throw error;\n }\n },\n };\n};\n\nexport const runTransaction = async <Result>(\n connection: PostgresConnection,\n callback: (driver: TransactionDriver) => Promise<Result>,\n options?: TransactionOptions,\n): Promise<Result> => {\n const settings = transactionOptionsSQL(options);\n\n await connection.execute({\n sql: `BEGIN${settings ? ` ${settings}` : \"\"}`,\n parameters: [],\n });\n\n try {\n const result = await transactionScope(\n connection,\n transactionStatements(),\n callback,\n );\n await connection.execute({ sql: \"COMMIT\", parameters: [] });\n\n return result;\n } catch (error) {\n try {\n await connection.execute({ sql: \"ROLLBACK\", parameters: [] });\n } catch (rollbackError) {\n connection.release(\n rollbackError instanceof Error\n ? rollbackError\n : new Error(String(rollbackError)),\n );\n }\n\n throw error;\n }\n};\n\nexport const transactionOptionsSQL = (\n options: TransactionOptions = {},\n): string => {\n const fragments: string[] = [];\n\n if (options.isolationLevel !== undefined) {\n if (\n ![\n IsolationLevel.ReadCommitted,\n IsolationLevel.RepeatableRead,\n IsolationLevel.Serializable,\n ].includes(options.isolationLevel)\n ) {\n throw new Error(\"symmetria: invalid transaction isolation level\");\n }\n\n fragments.push(`ISOLATION LEVEL ${options.isolationLevel.toUpperCase()}`);\n }\n\n for (const name of [\"readOnly\", \"deferrable\"] as const) {\n if (options[name] !== undefined && typeof options[name] !== \"boolean\") {\n throw new Error(`symmetria: ${name} must be a boolean`);\n }\n }\n\n if (options.readOnly !== undefined) {\n fragments.push(options.readOnly ? \"READ ONLY\" : \"READ WRITE\");\n }\n\n if (\n options.deferrable === true &&\n (options.isolationLevel !== IsolationLevel.Serializable ||\n options.readOnly !== true)\n ) {\n throw new Error(\"symmetria: DEFERRABLE requires SERIALIZABLE READ ONLY\");\n }\n\n if (options.deferrable !== undefined) {\n fragments.push(options.deferrable ? \"DEFERRABLE\" : \"NOT DEFERRABLE\");\n }\n\n return fragments.join(\", \");\n};\n\n/** Connection-specific statement execution and savepoint handling for a transaction scope. */\ntype TransactionStatements<Connection> = {\n readonly execute: (\n connection: Connection,\n query: CompiledQuery,\n ) => Promise<ExecutionResult>;\n readonly savepoint: <Result>(\n connection: Connection,\n callback: (connection: Connection) => Promise<Result>,\n ) => Promise<Result>;\n};\n\n/** The cursor of a `stream()` (see streamRows in query/select/query.ts). */\nconst STREAM_CURSOR = /^(DECLARE|CLOSE) (\"__symmetria_stream_\\d+\")/;\n\n/** What each open stream does when its transaction ends under it, by cursor name. */\nconst cursorEndings = new Map<string, () => void>();\n\n/**\n * Called when the transaction or savepoint that declared this cursor ends\n * while the cursor is still open: it rolled back, and so did the cursor. A\n * stream then stops instead of handing out rows it fetched before. Returns\n * the function that stops listening.\n */\nexport const whenCursorEnds = (\n cursor: string,\n ended: () => void,\n): (() => void) => {\n cursorEndings.set(cursor, ended);\n\n return () => {\n cursorEndings.delete(cursor);\n };\n};\n\nconst NO_ROWS: ExecutionResult = Object.freeze({ rows: [], affectedRows: 0 });\n\n/** What an operation still waiting to start returns once the scope has closed. */\nconst ABANDONED = Symbol(\"symmetria.abandoned\");\n\n/**\n * Shared transaction lifecycle: operations run one at a time in call order,\n * closed contexts reject late queries, a failed statement poisons the scope,\n * and a nested savepoint holds the connection until it ends; parent operations\n * issued meanwhile wait for it. An operation still pending when the callback\n * returns rejects, since the transaction then rolls back.\n */\nconst transactionScope = async <Connection, Result>(\n connection: Connection,\n statements: TransactionStatements<Connection>,\n callback: (driver: TransactionDriver) => Promise<Result>,\n): Promise<Result> => {\n const pending = createPendingTasks();\n const queue = createSerialQueue();\n // Cursors of streams that have not finished: open work like a pending query.\n const cursors = new Set<string>();\n // Streams of this scope that ended inside its savepoint: closed after it.\n const closeAfterNested: CompiledQuery[] = [];\n\n let closed = false;\n let unsettled = 0;\n let nested: NestedFrame | undefined;\n let failure: { error: unknown } | undefined;\n\n const close = (): void => {\n if (closed) {\n return;\n }\n\n closed = true;\n\n for (const cursor of cursors) {\n cursorEndings.get(cursor)?.();\n // Also for an iterator dropped halfway, which never stops listening.\n cursorEndings.delete(cursor);\n }\n };\n\n const assertAvailable = (): void => {\n if (closed) {\n throw new Error(\"symmetria: transaction context is closed\");\n }\n\n // Queued behind the nested transaction, a call from inside its own\n // callback would wait for itself.\n if (nested && callerInside(nested)) {\n throw new Error(\n \"symmetria: await the nested transaction before using its parent context\",\n );\n }\n\n if (failure) {\n throw failure.error;\n }\n };\n\n // A failed statement poisons the scope; savepoints report through their own scope.\n const schedule = <Value>(\n operation: () => Promise<Value>,\n statement: boolean,\n ): Promise<Value> => {\n unsettled += 1;\n\n return pending.track(\n queue\n .run(async (): Promise<Value | typeof ABANDONED> => {\n if (closed) {\n return ABANDONED;\n }\n\n if (failure) {\n throw failure.error;\n }\n\n return operation();\n })\n .then(\n (value) => {\n unsettled -= 1;\n\n if (closed) {\n throw new Error(\n \"symmetria: the transaction ended before this operation was awaited; it was rolled back\",\n );\n }\n\n return value as Value;\n },\n (error: unknown) => {\n unsettled -= 1;\n\n if (!statement) {\n throw error;\n }\n\n // Later operations report a failed $scope() write check as such too.\n const reported = scopeViolation(error);\n failure ??= { error: reported };\n\n throw reported;\n },\n ),\n );\n };\n\n const driver: TransactionDriver = Object.freeze({\n execute: (query) => {\n const cursor = STREAM_CURSOR.exec(query.sql);\n\n // A stream of this scope left inside one of its savepoints (`break`,\n // or a fetch refused there): the savepoint holds the connection, and\n // the code waiting for this CLOSE would hold up the savepoint, so the\n // cursor is closed as soon as the savepoint ends.\n if (\n cursor?.[1] === \"CLOSE\" &&\n !closed &&\n nested &&\n callerInside(nested) &&\n cursors.delete(cursor[2]!)\n ) {\n closeAfterNested.push(query);\n\n return Promise.resolve(NO_ROWS);\n }\n\n try {\n assertAvailable();\n } catch (error) {\n return Promise.reject(error);\n }\n\n return schedule(async () => {\n if (cursor?.[1] === \"CLOSE\") {\n cursors.delete(cursor[2]!);\n }\n\n const result = await statements.execute(connection, query);\n\n if (cursor?.[1] === \"DECLARE\") {\n cursors.add(cursor[2]!);\n }\n\n return result;\n }, true);\n },\n transaction: async <Value>(\n callback: (driver: TransactionDriver) => Promise<Value>,\n ): Promise<Value> => {\n assertAvailable();\n const frame = nestedFrame();\n\n return schedule(async () => {\n nested = frame;\n\n try {\n return await runInFrame(frame, () =>\n statements.savepoint(connection, (reserved) =>\n transactionScope(reserved, statements, callback),\n ),\n );\n } finally {\n nested = undefined;\n\n for (const query of closeAfterNested.splice(0)) {\n try {\n await statements.execute(connection, query);\n } catch (error) {\n failure ??= { error };\n }\n }\n }\n }, false);\n },\n });\n\n try {\n const result = await callback(driver);\n close();\n const unfinished = unsettled > 0;\n const streaming = cursors.size > 0;\n\n await pending.settle();\n\n if (failure) {\n throw failure.error;\n }\n\n if (unfinished) {\n throw new Error(\n \"symmetria: await all transaction operations before returning from the callback\",\n );\n }\n\n if (streaming) {\n throw new Error(\n \"symmetria: finish or break out of every stream() before returning from the transaction callback\",\n );\n }\n\n return result;\n } finally {\n close();\n await pending.settle();\n }\n};\n","import type { Driver } from \"../query/plan/types\";\n\n/** Rebind compiled schema metadata without evaluating declaration callbacks again. */\nexport const SCHEMA_BIND = Symbol(\"symmetria.schema.bind\");\nexport type BindableSchema = {\n readonly [SCHEMA_BIND]: (driver: Driver) => unknown;\n};\n\nexport type DatabaseOptions<Model extends BindableSchema> = {\n readonly schema: Model;\n readonly driver: Driver;\n};\n\n/** Bind a reusable schema to a driver, retaining its inferred query API and scopes. */\nexport const createDatabase = <Model extends BindableSchema>({\n schema: model,\n driver,\n}: DatabaseOptions<Model>): ReturnType<Model[typeof SCHEMA_BIND]> => {\n if (!model || typeof model[SCHEMA_BIND] !== \"function\") {\n throw new Error(\n \"symmetria: createDatabase() expects a schema() declaration\",\n );\n }\n\n return model[SCHEMA_BIND](driver) as ReturnType<Model[typeof SCHEMA_BIND]>;\n};\n"],"mappings":";;;;;;;;;AAWA,MAAM,eAAe,CAAC;;;;;AAMtB,MAAa,0BAAuC;CAClD,IAAI,OAAyB,QAAQ,QAAQ;CAE7C,OAAO,EACL,MAAM,cAAc;EAClB,MAAM,SAAS,KAAK,KAAK,SAAS;EAClC,OAAO,OAAO,KAAK,QAAQ,MAAM;EAEjC,OAAO;CACT,EACF;AACF;AAKA,MAAM,SAAS,IAAI,kBAA+B;;AAGlD,MAAa,qBAAkC,EAAE,QAAQ,OAAO,SAAS,EAAE;;AAG3E,MAAa,cACX,OACA,cACmB,OAAO,IAAI,OAAO,SAAS;;AAsBhD,MAAa,UAAU,IAAI,kBAAqC;;;;;;;AAQhE,MAAa,qBAA8C,OAAO,SAAS;AAE3E,MAAa,uBACX,QA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M;EACN,MAAM,QAAQ,OAAO;CACvB;AACF;;;;AC3XA,MAAa,cAAc,OAAO,uBAAuB;;AAWzD,MAAa,kBAAgD,EAC3D,QAAQ,OACR,aACmE;CACnE,IAAI,CAAC,SAAS,OAAO,MAAM,iBAAiB,YAC1C,MAAM,IAAI,MACR,4DACF;CAGF,OAAO,MAAM,YAAY,CAAC,MAAM;AAClC"}
package/dist/bun.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { c as SessionDriver, dt as BindableSchema, l as TransactionDriver, nt as QueryProfiler, pt as SCHEMA_BIND, r as Driver } from "./types-t7LyUyKP.js";
2
- import { t as PostgresDriver } from "./pool-C7rw4zkO.js";
1
+ import { c as SessionDriver, dt as BindableSchema, l as TransactionDriver, nt as QueryProfiler, pt as SCHEMA_BIND, r as Driver } from "./types--seX1C2D.js";
2
+ import { t as PostgresDriver } from "./pool-CRsOlJ3h.js";
3
3
  import { SQL } from "bun";
4
4
  //#region src/driver/bun.d.ts
5
5
  type PostgresOptions = Omit<SQL.PostgresOrMySQLOptions, "adapter" | "bigint"> & {
package/dist/bun.js CHANGED
@@ -1,5 +1,5 @@
1
- import { t as SCHEMA_BIND } from "./binding-QAk-KW4L.js";
2
- import { n as postgresParameters, t as createPostgresDriver } from "./pool-BTrHoEWY.js";
1
+ import { t as SCHEMA_BIND } from "./binding-evmthxTh.js";
2
+ import { n as postgresParameters, t as createPostgresDriver } from "./pool-CEeO5spd.js";
3
3
  import { SQL } from "bun";
4
4
  //#region src/driver/bun.ts
5
5
  /**
package/dist/cohere.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { K as EmbeddingModel, cn as SelectedColumn, q as MeaningSearch } from "./types-t7LyUyKP.js";
1
+ import { K as EmbeddingModel, cn as SelectedColumn, q as MeaningSearch } from "./types--seX1C2D.js";
2
2
  import { t as RequestOptions } from "./http-BHV8rkKW.js";
3
3
  //#region src/entries/cohere.d.ts
4
4
  export type CohereOptions = RequestOptions & {
package/dist/cohere.js CHANGED
@@ -1,4 +1,4 @@
1
- import { r as embedder } from "./search-BRkAlGfT.js";
1
+ import { r as embedder } from "./search-gbO7xe_u.js";
2
2
  import { a as requestOptions, i as postJson, r as inBatches, t as apiKey } from "./http-BWqJ9rei.js";
3
3
  //#region src/entries/cohere.ts
4
4
  /**
@@ -1,10 +1,10 @@
1
- import { A as createCompilation, C as numericCodec, D as canonicalType, L as throwDataErrors, M as parameter, N as quoteIdentifier, O as isBuiltInType, P as renderContext, c as containsBinding, d as numberedAlias, h as cloneParameter, j as keyAlias, k as aliasSql, l as mergeBindings, n as DEFAULT_VALUE, p as bigintCodec, u as normalizeResult, y as createRowDecoder } from "./types-CBBesvuC.js";
2
- import { c as negatable, l as negatedJsonOperand, n as bareJsonOperand, o as jsonNullAnswer } from "./core-BHndSuCB.js";
1
+ import { A as canonicalType, B as throwDataErrors, F as parameter, I as quoteIdentifier, L as renderContext, M as aliasSql, N as createCompilation, P as keyAlias, T as numericCodec, _ as cloneParameter, c as containsBinding, d as numberedAlias, j as isBuiltInType, l as mergeBindings, m as bigintCodec, n as DEFAULT_VALUE, u as normalizeResult, x as createRowDecoder } from "./types-BKbG6MO1.js";
2
+ import { b as isFloatType, c as negatable, l as negatedJsonOperand, n as bareJsonOperand, o as jsonNullAnswer } from "./core-DL4rAoIx.js";
3
3
  import { _ as QueryError, o as scopeViolationText } from "./errors-CLFkJWgJ.js";
4
- import { G as closedRawSql } from "./table-AFCbXHL8.js";
5
- import { a as containsNode, i as childNodes, n as expressionSqlType, r as valueSqlType, s as freeze } from "./metadata-BzA69T0R.js";
6
- import { a as shapeRenderer, i as postgresRenderer, n as executorProfiling, o as unconstrained } from "./profiling-DMJLtQEj.js";
7
- import { a as searchTextSql, i as searchRankSql, l as tsquerySql, n as isJsonType, o as searchValueType, r as searchHeadlineSql, s as searchVectorSql, t as headlineOptionsText, u as tsvectorSql } from "./search-BeNPJPTA.js";
4
+ import { G as closedRawSql } from "./table-Cgtbk2zk.js";
5
+ import { a as containsNode, i as childNodes, n as expressionSqlType, r as valueSqlType, s as freeze } from "./metadata-kSK6_Ygx.js";
6
+ import { a as shapeRenderer, i as postgresRenderer, n as executorProfiling, o as unconstrained } from "./profiling-CeH3c42X.js";
7
+ import { a as searchTextSql, i as searchRankSql, l as tsquerySql, n as isJsonType, o as searchValueType, r as searchHeadlineSql, s as searchVectorSql, t as headlineOptionsText, u as tsvectorSql } from "./search-0TyudCVL.js";
8
8
  import { isDeepStrictEqual } from "node:util";
9
9
  //#region src/query/plan/batching.ts
10
10
  const batchCollectors = /* @__PURE__ */ new WeakMap();
@@ -56,6 +56,7 @@ const sameExpression = (left, right, bindings) => {
56
56
  /**
57
57
  * Renders value expressions, operands, orderings and projections to SQL with the right codecs and casts.
58
58
  */
59
+ const BARE_PARAMETER = /^\(*\$\d+\)*$/;
59
60
  /**
60
61
  * bigint and numeric values travel as text inside JSON to keep their precision,
61
62
  * by any of their names (`int8`, `DECIMAL(30,10)`) and as a customType's base.
@@ -66,19 +67,17 @@ const jsonPrecisionSql = (compilation, expression, value) => {
66
67
  const array = type.endsWith("[]") || expression.codec?.parameterCast?.endsWith("[]");
67
68
  const codec = array ? expression.codec?.element : expression.codec;
68
69
  const scalarType = compilation.shapeOnly ? array ? sqlType.slice(0, -2) : sqlType : type.endsWith("[]") ? type.slice(0, -2) : type;
69
- if (codec !== bigintCodec && codec !== numericCodec && scalarType !== "bigint" && !scalarType.startsWith("numeric")) {
70
- if ((expression.node.kind === "placeholder" || expression.node.kind === "parameter") && sqlType !== "derived") return compilation.renderer.cast(value, {
71
- kind: "typed",
72
- type: sqlType === "enum" ? "text" : sqlType
73
- });
74
- return value;
75
- }
76
- return compilation.renderer.cast(value, {
70
+ const parameter = (expression.node.kind === "placeholder" || expression.node.kind === "parameter") && sqlType !== "derived";
71
+ const typed = () => compilation.renderer.cast(value, {
72
+ kind: "typed",
73
+ type: sqlType === "enum" ? "text" : sqlType
74
+ });
75
+ if (codec !== bigintCodec && codec !== numericCodec && scalarType !== "bigint" && !scalarType.startsWith("numeric")) return parameter ? typed() : value;
76
+ return compilation.renderer.cast(parameter && !compilation.shapeOnly && BARE_PARAMETER.test(value) ? typed() : value, {
77
77
  kind: "text",
78
78
  array: !!array
79
79
  });
80
80
  };
81
- const BARE_PARAMETER = /^\(*\$\d+\)*$/;
82
81
  const buildsJson = (node) => node.kind === "jsonObject" || node.kind === "jsonRows";
83
82
  const valueSql = (compilation, node, bindings, jsonOutput = false) => {
84
83
  const aggregate = node.kind === "subquery" ? compilation.aggregateReferences?.get(bindings)?.get(node) : void 0;
@@ -135,16 +134,27 @@ const rowQuerySql = (compilation, node, bindings, language, mode) => {
135
134
  * if any, is added right after the call. MIN and MAX of a type
136
135
  * without them take the first element of the aggregated one-element arrays,
137
136
  * which order by the type's comparison, skipping NULL and JSON null.
137
+ *
138
+ * SUM and AVG of a real or a double precision are floats, and PostgreSQL's
139
+ * cast of a float to numeric keeps 6 significant digits of a real and 15 of a
140
+ * double precision, fewer than the float holds. Its text is the shortest
141
+ * decimal that reads back as the same float, so the decimal is read from the
142
+ * text. A page cursor's fingerprint keeps the plain cast, the form earlier
143
+ * versions sent, so their cursors stay valid.
138
144
  */
139
145
  const aggregateSql = (compilation, node, bindings) => {
140
146
  const value = node.value ? valueSql(compilation, node.value, bindings) : "*";
147
+ const float = !!node.numeric && !!node.value && !compilation.shapeOnly && isFloatType(searchValueType(node.value));
141
148
  return (over = "") => {
142
149
  if (node.element) {
143
150
  const present = node.element === "json" ? `${value} <> 'null'::jsonb` : `${value} IS NOT NULL`;
144
151
  return `(${node.name}(ARRAY[${value}]) FILTER (WHERE ${present})${over})[1]`;
145
152
  }
146
153
  const aggregate = `${node.name}(${value})${over}`;
147
- return node.numeric ? compilation.renderer.cast(aggregate, { kind: "numeric" }) : aggregate;
154
+ return node.numeric ? compilation.renderer.cast(float ? compilation.renderer.cast(aggregate, {
155
+ kind: "text",
156
+ array: false
157
+ }) : aggregate, { kind: "numeric" }) : aggregate;
148
158
  };
149
159
  };
150
160
  /**
@@ -1409,4 +1419,4 @@ const rowDecoder = (plan) => {
1409
1419
  //#endregion
1410
1420
  export { currentScopes as a, rowDecoder as c, rebindPlan as d, sameExpression as f, compileTemplate as i, writeKeySubqueries as l, compileQuery as n, executeCompiled as o, batchCollectors as p, compileShape as r, executePlan as s, compilePlan as t, queryOccurrence as u };
1411
1421
 
1412
- //# sourceMappingURL=compile-D02-A2r9.js.map
1422
+ //# sourceMappingURL=compile-BXdzzNE_.js.map