symmetria 3.1.0 → 3.3.0

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 (72) hide show
  1. package/README.md +3 -0
  2. package/dist/better-auth.js +1 -1
  3. package/dist/binding-CD-0xNaB.js +12 -0
  4. package/dist/binding-CD-0xNaB.js.map +1 -0
  5. package/dist/bun.d.ts +2 -2
  6. package/dist/bun.js +2 -2
  7. package/dist/cohere.d.ts +1 -1
  8. package/dist/cohere.js +1 -1
  9. package/dist/{compile-Cfv7061C.js → compile-ZwOWiPod.js} +9 -373
  10. package/dist/compile-ZwOWiPod.js.map +1 -0
  11. package/dist/{core-j8XuMGmY.js → core-Dww__AzP.js} +341 -15
  12. package/dist/core-Dww__AzP.js.map +1 -0
  13. package/dist/driver.d.ts +3 -3
  14. package/dist/driver.js +2 -2
  15. package/dist/{binding-jM09pXvJ.js → errors-DNyJuu6e.js} +2 -11
  16. package/dist/errors-DNyJuu6e.js.map +1 -0
  17. package/dist/freeze-D2-KMR2m.js +12 -0
  18. package/dist/freeze-D2-KMR2m.js.map +1 -0
  19. package/dist/google.d.ts +1 -1
  20. package/dist/google.js +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +142 -47
  23. package/dist/index.js.map +1 -1
  24. package/dist/{inspection-WNNakwoE.js → inspection-CMwwt5mS.js} +4 -3
  25. package/dist/{inspection-WNNakwoE.js.map → inspection-CMwwt5mS.js.map} +1 -1
  26. package/dist/internal.d.ts +1 -1
  27. package/dist/internal.js +4 -3
  28. package/dist/jina.d.ts +1 -1
  29. package/dist/jina.js +1 -1
  30. package/dist/mistral.d.ts +1 -1
  31. package/dist/mistral.js +1 -1
  32. package/dist/ollama.d.ts +1 -1
  33. package/dist/ollama.js +1 -1
  34. package/dist/openai.d.ts +1 -1
  35. package/dist/openai.js +1 -1
  36. package/dist/opentelemetry.d.ts +41 -0
  37. package/dist/opentelemetry.js +119 -0
  38. package/dist/opentelemetry.js.map +1 -0
  39. package/dist/{pg-CFB1A5bi.d.ts → pg-BR0PaxkR.d.ts} +3 -3
  40. package/dist/{pg-D642sWtx.js → pg-mrOCZi9Z.js} +4 -4
  41. package/dist/{pg-D642sWtx.js.map → pg-mrOCZi9Z.js.map} +1 -1
  42. package/dist/pg.d.ts +3 -3
  43. package/dist/pg.js +2 -2
  44. package/dist/{pool-DLmybA--.d.ts → pool-DpIlCXfo.d.ts} +2 -2
  45. package/dist/{pool-dF8wVzv2.js → pool-FCcF1emD.js} +4 -4
  46. package/dist/{pool-dF8wVzv2.js.map → pool-FCcF1emD.js.map} +1 -1
  47. package/dist/profiling-Ca4rPFVy.js +381 -0
  48. package/dist/profiling-Ca4rPFVy.js.map +1 -0
  49. package/dist/{search-D953bVPb.js → search-DFEDMdX8.js} +22 -12
  50. package/dist/search-DFEDMdX8.js.map +1 -0
  51. package/dist/search-uCUvhR3s.js +49 -0
  52. package/dist/search-uCUvhR3s.js.map +1 -0
  53. package/dist/search.d.ts +1 -1
  54. package/dist/search.js +1 -1
  55. package/dist/{table-x4L0cE1T.js → table-B89jb16u.js} +6 -370
  56. package/dist/table-B89jb16u.js.map +1 -0
  57. package/dist/{types-r3vlr_gE.d.ts → types-TJDae-ar.d.ts} +72 -37
  58. package/dist/{types-NVB9dmsW.js → types-ojhCorK7.js} +5 -2
  59. package/dist/{types-NVB9dmsW.js.map → types-ojhCorK7.js.map} +1 -1
  60. package/dist/{values-CnN8eqP3.js → values-JeB3Fwkt.js} +2 -2
  61. package/dist/{values-CnN8eqP3.js.map → values-JeB3Fwkt.js.map} +1 -1
  62. package/dist/vector.d.ts +13 -1
  63. package/dist/vector.js +27 -9
  64. package/dist/vector.js.map +1 -1
  65. package/dist/voyage.d.ts +1 -1
  66. package/dist/voyage.js +1 -1
  67. package/package.json +5 -1
  68. package/dist/binding-jM09pXvJ.js.map +0 -1
  69. package/dist/compile-Cfv7061C.js.map +0 -1
  70. package/dist/core-j8XuMGmY.js.map +0 -1
  71. package/dist/search-D953bVPb.js.map +0 -1
  72. package/dist/table-x4L0cE1T.js.map +0 -1
package/README.md CHANGED
@@ -361,6 +361,9 @@ decode timings. Pass it to `postgres({ url, profiler })`, wrap requests with
361
361
  `SYMMETRIA_PROFILE_TOKEN` for the application and the CLI, then open
362
362
  `bunx --package symmetria-kit symmetria profile`.
363
363
 
364
+ `traced(driver, { tracer })` from `symmetria/opentelemetry` reports every
365
+ statement and transaction as an OpenTelemetry span.
366
+
364
367
  ## Drivers
365
368
 
366
369
  Official drivers ship with `symmetria` and are maintained and released together:
@@ -1,4 +1,4 @@
1
- import { _ as not, b as or, l as and } from "./core-j8XuMGmY.js";
1
+ import { u as and, v as not, x as or } from "./core-Dww__AzP.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}`);
@@ -0,0 +1,12 @@
1
+ //#region src/schema/binding.ts
2
+ /** Rebind compiled schema metadata without evaluating declaration callbacks again. */
3
+ const SCHEMA_BIND = Symbol("symmetria.schema.bind");
4
+ /** Bind a reusable schema to a driver, retaining its inferred query API and scopes. */
5
+ const createDatabase = ({ schema: model, driver }) => {
6
+ if (!model || typeof model[SCHEMA_BIND] !== "function") throw new Error("symmetria: createDatabase() expects a schema() declaration");
7
+ return model[SCHEMA_BIND](driver);
8
+ };
9
+ //#endregion
10
+ export { createDatabase as n, SCHEMA_BIND as t };
11
+
12
+ //# sourceMappingURL=binding-CD-0xNaB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binding-CD-0xNaB.js","names":[],"sources":["../src/schema/binding.ts"],"sourcesContent":["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":";;AAGA,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-r3vlr_gE.js";
2
- import { t as PostgresDriver } from "./pool-DLmybA--.js";
1
+ import { c as SessionDriver, dt as BindableSchema, l as TransactionDriver, nt as QueryProfiler, pt as SCHEMA_BIND, r as Driver } from "./types-TJDae-ar.js";
2
+ import { t as PostgresDriver } from "./pool-DpIlCXfo.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-jM09pXvJ.js";
2
- import { n as postgresParameters, t as createPostgresDriver } from "./pool-dF8wVzv2.js";
1
+ import { t as SCHEMA_BIND } from "./binding-CD-0xNaB.js";
2
+ import { n as postgresParameters, t as createPostgresDriver } from "./pool-FCcF1emD.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-r3vlr_gE.js";
1
+ import { K as EmbeddingModel, cn as SelectedColumn, q as MeaningSearch } from "./types-TJDae-ar.js";
2
2
  //#region src/entries/cohere.d.ts
3
3
  export type CohereOptions = {
4
4
  readonly apiKey?: string;
package/dist/cohere.js CHANGED
@@ -1,4 +1,4 @@
1
- import { r as embedder } from "./search-D953bVPb.js";
1
+ import { r as embedder } from "./search-DFEDMdX8.js";
2
2
  import { i as postJson, r as inBatches, t as apiKey } from "./http-o1fpnTNy.js";
3
3
  //#region src/entries/cohere.ts
4
4
  /**
@@ -1,375 +1,11 @@
1
- import { a as containsBinding, c as numberedAlias, f as cloneParameter, g as createRowDecoder, o as mergeBindings, s as normalizeResult, t as DEFAULT_VALUE, u as bigintCodec, w as throwDataErrors, y as numericCodec } from "./types-NVB9dmsW.js";
2
- import { $ as tsquerySql, G as createCompilation, J as renderContext, K as parameter, Q as sqlString, W as aliasSql, X as searchRankSql, Y as searchHeadlineSql, Z as searchVectorSql, et as tsvectorSql, q as quoteIdentifier } from "./table-x4L0cE1T.js";
3
- import { c as scopeViolationText } from "./binding-jM09pXvJ.js";
4
- import { I as freeze, M as expressionSqlType, N as childNodes, P as containsNode } from "./core-j8XuMGmY.js";
5
- import { AsyncLocalStorage } from "node:async_hooks";
6
- import { randomUUID, timingSafeEqual } from "node:crypto";
7
- import { createServer } from "node:http";
1
+ import { E as throwDataErrors, c as mergeBindings, f as bigintCodec, l as normalizeResult, m as cloneParameter, s as containsBinding, t as DEFAULT_VALUE, u as numberedAlias, v as createRowDecoder, x as numericCodec } from "./types-ojhCorK7.js";
2
+ import { F as containsNode, N as expressionSqlType, P as childNodes } from "./core-Dww__AzP.js";
3
+ import { o as scopeViolationText } from "./errors-DNyJuu6e.js";
4
+ import { G as createCompilation, J as renderContext, K as parameter, W as aliasSql, q as quoteIdentifier } from "./table-B89jb16u.js";
5
+ import { t as freeze } from "./freeze-D2-KMR2m.js";
6
+ import { a as unconstrained, i as postgresRenderer, n as executorProfiling } from "./profiling-Ca4rPFVy.js";
7
+ import { a as tsquerySql, n as searchRankSql, o as tsvectorSql, r as searchVectorSql, t as searchHeadlineSql } from "./search-uCUvhR3s.js";
8
8
  import { isDeepStrictEqual } from "node:util";
9
- //#region src/observability/http.ts
10
- /** Small, portable HTTP listener for the opt-in profiler. */
11
- const serveProfiler = async (options) => {
12
- let port = options.port;
13
- const hostname = options.hostname.includes(":") ? `[${options.hostname}]` : options.hostname;
14
- const server = createServer(async (incoming, outgoing) => {
15
- try {
16
- const headers = new Headers();
17
- for (const [name, value] of Object.entries(incoming.headers)) if (value !== void 0) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
18
- const target = incoming.url ?? "/";
19
- const request = new Request(new URL(`http://${hostname}:${port}${target.startsWith("/") ? target : `/${target}`}`).href, {
20
- method: incoming.method ?? "GET",
21
- headers
22
- });
23
- const response = await options.fetch(request, { port });
24
- outgoing.writeHead(response.status, Object.fromEntries(response.headers));
25
- outgoing.end(Buffer.from(await response.arrayBuffer()));
26
- } catch {
27
- outgoing.writeHead(500);
28
- outgoing.end();
29
- }
30
- });
31
- await new Promise((resolve, reject) => {
32
- server.once("error", reject);
33
- server.listen(options.port, options.hostname, () => {
34
- server.off("error", reject);
35
- resolve();
36
- });
37
- });
38
- port = server.address().port;
39
- let closing;
40
- return Object.freeze({
41
- port,
42
- url: new URL(`http://${hostname}:${port}`),
43
- stop: (force = false) => closing ??= new Promise((resolve, reject) => {
44
- server.close((error) => error ? reject(error) : resolve());
45
- if (force) server.closeAllConnections();
46
- })
47
- });
48
- };
49
- //#endregion
50
- //#region src/query/compile/postgres/render.ts
51
- /**
52
- * PostgreSQL renderer: dialect-specific SQL for casts, JSON aggregation, arrays and operators.
53
- */
54
- const jsonArray = (value) => `NULLIF((${value})::jsonb, 'null'::jsonb)`;
55
- const jsonObject = (entries, jsonOutput) => {
56
- const fields = entries.map(({ key, value }) => `${sqlString(key)}, ${value}`);
57
- if (entries.length <= 50) return `${jsonOutput ? "json_build_object" : "jsonb_build_object"}(${fields.join(", ")})`;
58
- const chunks = [];
59
- for (let position = 0; position < entries.length; position += 50) chunks.push(`jsonb_build_object(${fields.slice(position, position + 50).join(", ")})`);
60
- return `(${chunks.join(" || ")})${jsonOutput ? "::json" : ""}`;
61
- };
62
- /**
63
- * An explicit cast to `varchar(5)` or `numeric(10,2)` silently cuts or rounds
64
- * the value, so a bound value compared with such a column would match rows it
65
- * does not equal. Casts state the base type only; assignment to a column still
66
- * applies the column's own length and scale. `char(5)` becomes `bpchar`, the
67
- * same type without a length: plain `char` would mean `char(1)` and cut the
68
- * value to one character.
69
- */
70
- const unconstrained = (type) => type.replace(/^(?:char|character|bpchar)\s*\([^)]*\)/i, "bpchar").replace(/^(varchar|character varying|numeric|decimal)\s*\([^)]*\)/i, "$1");
71
- /** PostgreSQL SQL rendering, shared by every execution adapter. */
72
- const postgresRenderer = {
73
- placeholder: (position) => `$${position}`,
74
- cast: (value, target) => {
75
- switch (target.kind) {
76
- case "parameter": return `${value}::text::${unconstrained(target.type)}`;
77
- case "numeric": return `${value}::numeric`;
78
- case "text": return target.array ? `(${value})::text[]` : `(${value})::text`;
79
- case "typed": return `(${value})::${unconstrained(target.type)}`;
80
- }
81
- },
82
- limitOffset: (limit, offset) => [...limit === void 0 ? [] : [`LIMIT ${limit}`], ...offset === void 0 ? [] : [`OFFSET ${offset}`]],
83
- rowLock: (lock) => `FOR ${lock.mode}${lock.of ? ` OF ${lock.of.join(", ")}` : ""}${lock.noWait ? " NOWAIT" : lock.skipLocked ? " SKIP LOCKED" : ""}`,
84
- textCast: {
85
- prefix: "",
86
- suffix: "::text"
87
- },
88
- jsonObject,
89
- jsonRows: (nested, many, jsonOutput) => {
90
- return many ? `(SELECT COALESCE(${jsonOutput ? "json_agg" : "jsonb_agg"}("__symmetria_row"), '[]'::${jsonOutput ? "json" : "jsonb"}) FROM (${nested}) AS "__symmetria_row")` : `(SELECT ${jsonOutput ? "row_to_json" : "to_jsonb"}("__symmetria_row") FROM (${nested}) AS "__symmetria_row")`;
91
- },
92
- jsonPath: (value, path, options, context) => `(${value} ${options.scalarType ? "#>>" : "#>"} ARRAY[${path.map((part) => `${context.parameter(String(part))}::text`).join(", ")}])${options.scalarType ? `::${options.scalarType}` : ""}`,
93
- arrayIndex: (value, position, context) => {
94
- const parameter = context.parameter(position);
95
- return `(${value})[(CASE WHEN ${parameter}::bigint < cardinality(${value}) THEN array_lower(${value}, 1)::bigint + ${parameter}::bigint END)::integer]`;
96
- },
97
- arrayLength: (value, json) => json ? `jsonb_array_length(${jsonArray(value)})` : `cardinality(${value})`,
98
- jsonHas: (value, element, options, context) => {
99
- const array = jsonArray(value);
100
- const elementAlias = context.nestedAlias("__symmetria_element");
101
- const other = context.nestedAlias("__symmetria_element_other");
102
- if (options.overlap) {
103
- const operand = options.elementArray ? `to_jsonb(${options.operand})` : element;
104
- return `EXISTS (SELECT 1 FROM jsonb_array_elements(${array}) AS ${elementAlias}("value") CROSS JOIN jsonb_array_elements(${jsonArray(operand)}) AS ${other}("value") WHERE ${elementAlias}."value" = ${other}."value")`;
105
- }
106
- return `EXISTS (SELECT 1 FROM jsonb_array_elements(${array}) AS ${elementAlias}("value") WHERE ${elementAlias}."value" = COALESCE(${options.encoded ? element : `to_jsonb(${element})`}, 'null'::jsonb))`;
107
- },
108
- arrayHas: (value, element) => `${element} = ANY(${value})`,
109
- search: (vector, query) => `${vector} @@ ${query}`,
110
- recursiveUnion: (anchor, recursive, options) => `(${anchor})\nUNION${options.unionAll ? " ALL" : ""}\n(${recursive})`,
111
- explain: (sql, analyze) => ({
112
- sql: `EXPLAIN (FORMAT JSON${analyze ? ", ANALYZE, BUFFERS" : ""}) ${sql}`,
113
- analyzed: analyze,
114
- plan: (rows) => {
115
- const value = rows[0]?.["QUERY PLAN"];
116
- const explanation = typeof value === "string" ? JSON.parse(value) : value;
117
- if (!Array.isArray(explanation) || !explanation.length || explanation.some((entry) => !entry || typeof entry !== "object" || Array.isArray(entry))) throw new Error("symmetria: EXPLAIN did not return a PostgreSQL JSON plan");
118
- return explanation;
119
- }
120
- }),
121
- nullsDefault: (direction) => direction === "ASC" ? "LAST" : "FIRST"
122
- };
123
- freeze(postgresRenderer.textCast);
124
- freeze(postgresRenderer);
125
- //#endregion
126
- //#region src/observability/profiling.ts
127
- /**
128
- * Query profiler: records per-request query timings through AsyncLocalStorage and serves them over HTTP with a token.
129
- */
130
- const executorProfiles = /* @__PURE__ */ new WeakMap();
131
- const executorProfiling = (executor) => executor ? executorProfiles.get(executor) : void 0;
132
- const serialize = (value) => JSON.stringify(value, (_name, entry) => typeof entry === "bigint" ? entry.toString() : entry);
133
- const constantTimeEqual = (candidate, expected) => {
134
- if (candidate === null) return false;
135
- const left = Buffer.from(candidate);
136
- const right = Buffer.from(expected);
137
- return left.length === right.length && timingSafeEqual(left, right);
138
- };
139
- /** Opt-in profiling; async contexts isolate simultaneous named traces and HTTP requests. */
140
- const createProfiler = (options = {}) => {
141
- const capacity = options.capacity ?? 200;
142
- const queryCapacity = options.queryCapacity ?? 1e3;
143
- if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Error("symmetria: profiler capacity must be a positive integer");
144
- if (!Number.isSafeInteger(queryCapacity) || queryCapacity < 1) throw new Error("symmetria: profiler queryCapacity must be a positive integer");
145
- const context = new AsyncLocalStorage();
146
- const requests = [];
147
- const queryRecords = /* @__PURE__ */ new WeakMap();
148
- const queryExecutors = /* @__PURE__ */ new Map();
149
- const wrappedBuilders = /* @__PURE__ */ new WeakSet();
150
- const excluded = /* @__PURE__ */ new Set([
151
- "execute",
152
- "then",
153
- "catch",
154
- "finally",
155
- "toSQL",
156
- "one",
157
- "maybeOne",
158
- "first",
159
- "aggregate",
160
- "get",
161
- "find",
162
- "page",
163
- "pages",
164
- "stream",
165
- "inspect",
166
- "$transaction",
167
- "$close",
168
- "$snapshot"
169
- ]);
170
- let nextRequestId = 1;
171
- let nextQueryId = 1;
172
- let building = 0;
173
- const remember = (request) => {
174
- requests.push(request);
175
- while (requests.length > capacity) {
176
- const removed = requests.shift();
177
- for (const query of removed.queries) queryExecutors.delete(query.id);
178
- }
179
- };
180
- const trace = async (label, operation) => {
181
- const request = {
182
- id: nextRequestId++,
183
- label,
184
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
185
- durationMs: 0,
186
- buildMs: 0,
187
- queries: []
188
- };
189
- const started = performance.now();
190
- try {
191
- return await context.run(request, operation);
192
- } catch (error) {
193
- request.error = error instanceof Error ? error.message : String(error);
194
- throw error;
195
- } finally {
196
- request.durationMs = performance.now() - started;
197
- remember(request);
198
- }
199
- };
200
- const trackBuilder = (builder) => {
201
- if (wrappedBuilders.has(builder)) return builder;
202
- const methods = /* @__PURE__ */ new Map();
203
- const measure = (operation) => {
204
- const request = context.getStore();
205
- const outermost = building++ === 0;
206
- const started = request && outermost ? performance.now() : 0;
207
- try {
208
- return operation();
209
- } finally {
210
- building--;
211
- if (request && outermost) request.buildMs += performance.now() - started;
212
- }
213
- };
214
- const proxy = new Proxy(typeof builder === "function" ? (..._argumentsList) => void 0 : {}, {
215
- apply: (_target, receiver, argumentsList) => measure(() => Reflect.apply(builder, receiver, argumentsList)),
216
- get: (_target, key) => {
217
- const value = Reflect.get(builder, key);
218
- if (typeof value !== "function" || typeof key !== "string" || excluded.has(key)) {
219
- if (key === "by" && value && typeof value === "object") {
220
- if (!methods.has(key)) methods.set(key, trackBuilder(value));
221
- return methods.get(key);
222
- }
223
- return value;
224
- }
225
- if (!methods.has(key)) methods.set(key, (...argumentsList) => {
226
- return measure(() => Reflect.apply(value, builder, argumentsList));
227
- });
228
- return methods.get(key);
229
- },
230
- has: (_target, key) => key in builder,
231
- getPrototypeOf: () => Object.getPrototypeOf(builder),
232
- ownKeys: () => Reflect.ownKeys(builder),
233
- getOwnPropertyDescriptor: (_target, key) => {
234
- const descriptor = Object.getOwnPropertyDescriptor(builder, key);
235
- return descriptor ? {
236
- ...descriptor,
237
- configurable: true
238
- } : void 0;
239
- },
240
- set: () => false,
241
- defineProperty: () => false,
242
- deleteProperty: () => false
243
- });
244
- wrappedBuilders.add(proxy);
245
- return proxy;
246
- };
247
- const wrapExecutor = (executor, explainExecutor = executor) => {
248
- const execute = async (query) => {
249
- const request = context.getStore();
250
- if (!request) return trace("background query", () => execute(query));
251
- const started = performance.now();
252
- const record = {
253
- id: nextQueryId++,
254
- sql: query.sql,
255
- parameters: [],
256
- kind: "raw",
257
- compileMs: 0,
258
- databaseMs: 0,
259
- decodeMs: 0,
260
- rows: 0
261
- };
262
- try {
263
- const result = await executor(query);
264
- record.rows = normalizeResult(result).affectedRows;
265
- return result;
266
- } catch (error) {
267
- record.error = error instanceof Error ? error.message : String(error);
268
- throw error;
269
- } finally {
270
- record.databaseMs = performance.now() - started;
271
- record.parameters = query.parameters.map(cloneParameter);
272
- request.queries.push(record);
273
- queryRecords.set(query, record);
274
- queryExecutors.set(record.id, {
275
- query: {
276
- sql: query.sql,
277
- parameters: record.parameters
278
- },
279
- executor: explainExecutor,
280
- record
281
- });
282
- while (request.queries.length > queryCapacity) {
283
- const dropped = request.queries.shift();
284
- queryExecutors.delete(dropped.id);
285
- request.droppedQueries = (request.droppedQueries ?? 0) + 1;
286
- }
287
- }
288
- };
289
- executorProfiles.set(execute, {
290
- trackBuilder,
291
- annotate: (query, details) => {
292
- const record = queryRecords.get(query);
293
- if (record) Object.assign(record, details);
294
- }
295
- });
296
- return execute;
297
- };
298
- const transactionDriver = (driver, explainExecutor) => Object.freeze({
299
- execute: wrapExecutor(driver.execute, explainExecutor),
300
- transaction: (callback) => driver.transaction((nested) => callback(transactionDriver(nested, explainExecutor)))
301
- });
302
- const wrapDriver = (driver) => Object.freeze({
303
- execute: wrapExecutor(driver.execute, driver.execute),
304
- close: driver.close,
305
- ...driver.session ? { session: driver.session } : {},
306
- ...driver.transaction ? { transaction: (callback, settings) => driver.transaction((scoped) => callback(transactionDriver(scoped, driver.execute)), settings) } : {}
307
- });
308
- const snapshot = () => structuredClone(requests);
309
- const explain = async (identifier, analyze = false) => {
310
- const entry = queryExecutors.get(identifier);
311
- if (!entry || entry.record.kind !== "select") throw new Error("symmetria: EXPLAIN requires a retained SELECT query");
312
- const statement = postgresRenderer.explain(entry.query.sql, analyze);
313
- const result = normalizeResult(await entry.executor({
314
- sql: statement.sql,
315
- parameters: entry.query.parameters.map(cloneParameter)
316
- }));
317
- return statement.plan(result.rows);
318
- };
319
- const fetchHandler = (handler) => (request) => trace(`${request.method} ${new URL(request.url).pathname}`, () => handler(request));
320
- const serve = async (settings = {}) => {
321
- const hostname = settings.hostname ?? "127.0.0.1";
322
- if (hostname !== "127.0.0.1" && hostname !== "::1") throw new Error("symmetria: profiler HTTP server requires a loopback address");
323
- const token = settings.token ?? process.env.SYMMETRIA_PROFILE_TOKEN ?? randomUUID();
324
- if (typeof token !== "string" || token.length < 16 || !/^[\x21-\x7e]+$/.test(token)) throw new Error("symmetria: profiler token must be at least 16 printable ASCII characters");
325
- const headers = {
326
- "content-type": "application/json",
327
- "cache-control": "no-store",
328
- "x-content-type-options": "nosniff"
329
- };
330
- const server = await serveProfiler({
331
- hostname,
332
- port: settings.port ?? 7331,
333
- fetch: async (request, server) => {
334
- const url = new URL(request.url);
335
- const hosts = [hostname === "::1" ? "[::1]" : hostname, "localhost"].flatMap((name) => server.port === 80 ? [name, `${name}:80`] : [`${name}:${server.port}`]);
336
- const origin = request.headers.get("origin");
337
- const site = request.headers.get("sec-fetch-site");
338
- if (url.protocol !== "http:" || !hosts.includes(url.host) || !hosts.includes(request.headers.get("host")?.toLowerCase() ?? "") || origin !== null && origin !== url.origin || site !== null && site !== "same-origin" && site !== "none" || !constantTimeEqual(request.headers.get("x-symmetria-token"), token)) return Response.json({ error: "Forbidden" }, {
339
- status: 403,
340
- headers
341
- });
342
- if (request.method === "GET" && url.pathname === "/requests") return new Response(serialize(snapshot()), { headers });
343
- if (request.method === "POST" && url.pathname === "/explain") try {
344
- const result = await explain(Number(url.searchParams.get("id")), url.searchParams.get("analyze") === "true");
345
- return new Response(serialize(result), { headers });
346
- } catch (error) {
347
- return Response.json({ error: error instanceof Error ? error.message : String(error) }, {
348
- status: 400,
349
- headers
350
- });
351
- }
352
- return Response.json({ error: "Not found" }, {
353
- status: 404,
354
- headers
355
- });
356
- }
357
- });
358
- return Object.freeze({
359
- ...server,
360
- token
361
- });
362
- };
363
- return Object.freeze({
364
- trace,
365
- fetch: fetchHandler,
366
- driver: wrapDriver,
367
- snapshot,
368
- explain,
369
- serve
370
- });
371
- };
372
- //#endregion
373
9
  //#region src/query/plan/batching.ts
374
10
  const batchCollectors = /* @__PURE__ */ new WeakMap();
375
11
  //#endregion
@@ -1604,6 +1240,6 @@ const rowDecoder = (plan) => {
1604
1240
  return decode;
1605
1241
  };
1606
1242
  //#endregion
1607
- export { currentScopes as a, rowDecoder as c, createProfiler as d, executorProfiling as f, compileTemplate as i, queryOccurrence as l, compileQuery as n, executeCompiled as o, postgresRenderer as p, compileShape as r, executePlan as s, compilePlan as t, batchCollectors as u };
1243
+ export { currentScopes as a, rowDecoder as c, compileTemplate as i, queryOccurrence as l, compileQuery as n, executeCompiled as o, compileShape as r, executePlan as s, compilePlan as t, batchCollectors as u };
1608
1244
 
1609
- //# sourceMappingURL=compile-Cfv7061C.js.map
1245
+ //# sourceMappingURL=compile-ZwOWiPod.js.map