@niscorp/vex 0.4.0 → 0.4.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/DESIGN.md +12 -7
  3. package/DOCS.md +64 -19
  4. package/README.md +2 -2
  5. package/dist/adapters/express/index.cjs +1 -1
  6. package/dist/adapters/express/index.cjs.map +1 -1
  7. package/dist/adapters/express/index.d.cts +2 -2
  8. package/dist/adapters/express/index.d.ts +2 -2
  9. package/dist/adapters/express/index.js +1 -1
  10. package/dist/adapters/hono/index.cjs +1 -1
  11. package/dist/adapters/hono/index.cjs.map +1 -1
  12. package/dist/adapters/hono/index.d.cts +2 -2
  13. package/dist/adapters/hono/index.d.ts +2 -2
  14. package/dist/adapters/hono/index.js +1 -1
  15. package/dist/adapters/pg/index.cjs +44 -0
  16. package/dist/adapters/pg/index.cjs.map +1 -0
  17. package/dist/adapters/pg/index.d.cts +28 -0
  18. package/dist/adapters/pg/index.d.ts +28 -0
  19. package/dist/adapters/pg/index.js +31 -0
  20. package/dist/adapters/pg/index.js.map +1 -0
  21. package/dist/adapters/pglite/index.cjs +3 -1
  22. package/dist/adapters/pglite/index.cjs.map +1 -1
  23. package/dist/adapters/pglite/index.d.cts +5 -4
  24. package/dist/adapters/pglite/index.d.ts +5 -4
  25. package/dist/adapters/pglite/index.js +3 -3
  26. package/dist/adapters/pglite/index.js.map +1 -1
  27. package/dist/agent/index.cjs +144 -22
  28. package/dist/agent/index.cjs.map +1 -1
  29. package/dist/agent/index.d.cts +1 -1
  30. package/dist/agent/index.d.ts +1 -1
  31. package/dist/agent/index.js +144 -22
  32. package/dist/agent/index.js.map +1 -1
  33. package/dist/chunk-DFWYYBJU.js +7 -0
  34. package/dist/chunk-DFWYYBJU.js.map +1 -0
  35. package/dist/{chunk-7F2OH4IP.js → chunk-RGJRUOGQ.js} +7 -4
  36. package/dist/chunk-RGJRUOGQ.js.map +1 -0
  37. package/dist/date-parsers-BaUuE_ax.d.cts +4 -0
  38. package/dist/date-parsers-BaUuE_ax.d.ts +4 -0
  39. package/dist/{handler-Bw7xVmBM.d.ts → handler-CoJxInw-.d.ts} +1 -1
  40. package/dist/{handler-Cy0gNM6K.d.cts → handler-CsFbanZA.d.cts} +1 -1
  41. package/dist/index.cjs +6 -3
  42. package/dist/index.cjs.map +1 -1
  43. package/dist/index.d.cts +3 -3
  44. package/dist/index.d.ts +3 -3
  45. package/dist/index.js +3 -3
  46. package/dist/index.js.map +1 -1
  47. package/dist/{types-DO-rYZci.d.cts → types-B2HEmyNq.d.cts} +1 -1
  48. package/dist/{types-Bs_9VM9p.d.ts → types-DC68ZUuq.d.ts} +1 -1
  49. package/package.json +13 -1
  50. package/dist/chunk-7F2OH4IP.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import { Env, Context, Hono } from 'hono';
2
- import { a as QueryEngine, aa as ScopeValues, S as ScopePolicy } from '../../types-DO-rYZci.cjs';
3
- import { M as MutationClient, W as WriteEvent, E as ExecuteRecord } from '../../handler-Cy0gNM6K.cjs';
2
+ import { a as QueryEngine, aa as ScopeValues, S as ScopePolicy } from '../../types-B2HEmyNq.cjs';
3
+ import { M as MutationClient, W as WriteEvent, E as ExecuteRecord } from '../../handler-CsFbanZA.cjs';
4
4
  import '../../query.schema-B-LVNfyX.cjs';
5
5
  import 'zod';
6
6
  import '@niscorp/prism';
@@ -1,6 +1,6 @@
1
1
  import { Env, Context, Hono } from 'hono';
2
- import { a as QueryEngine, aa as ScopeValues, S as ScopePolicy } from '../../types-Bs_9VM9p.js';
3
- import { M as MutationClient, W as WriteEvent, E as ExecuteRecord } from '../../handler-Bw7xVmBM.js';
2
+ import { a as QueryEngine, aa as ScopeValues, S as ScopePolicy } from '../../types-DC68ZUuq.js';
3
+ import { M as MutationClient, W as WriteEvent, E as ExecuteRecord } from '../../handler-CoJxInw-.js';
4
4
  import '../../query.schema-B-LVNfyX.js';
5
5
  import 'zod';
6
6
  import '@niscorp/prism';
@@ -1,4 +1,4 @@
1
- import { handleDiscovery, handleQuery, handleFingerprintPatch, handleFingerprintDelete } from '../../chunk-7F2OH4IP.js';
1
+ import { handleDiscovery, handleQuery, handleFingerprintPatch, handleFingerprintDelete } from '../../chunk-RGJRUOGQ.js';
2
2
  import '../../chunk-XTOK7YOR.js';
3
3
  import '../../chunk-UPQMKAAX.js';
4
4
  import { Hono } from 'hono';
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+
3
+ var pg = require('pg');
4
+
5
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
+
7
+ var pg__default = /*#__PURE__*/_interopDefault(pg);
8
+
9
+ // src/adapters/pg/index.ts
10
+
11
+ // src/adapters/postgres/date-parsers.ts
12
+ var RAW = (value) => value;
13
+ var RAW_DATE_PARSERS = { 1082: RAW, 1184: RAW };
14
+
15
+ // src/adapters/pg/index.ts
16
+ var queryOn = (target, parsers) => {
17
+ const types = parsers === void 0 ? void 0 : { getTypeParser: (oid, format) => parsers[oid] ?? pg__default.default.types.getTypeParser(oid, format) };
18
+ return async (text, values) => {
19
+ const { rows, fields } = await target.query({ text, ...values === void 0 ? {} : { values }, ...types === void 0 ? {} : { types } });
20
+ return { rows, fields: fields.map(({ name, dataTypeID }) => ({ name, dataTypeID })) };
21
+ };
22
+ };
23
+ var createPgPool = (pool, parsers) => ({
24
+ query: queryOn(pool, parsers),
25
+ transaction: async (fn) => {
26
+ const client = await pool.connect();
27
+ try {
28
+ await client.query({ text: "BEGIN" });
29
+ const result = await fn({ query: queryOn(client, parsers) });
30
+ await client.query({ text: "COMMIT" });
31
+ return result;
32
+ } catch (error) {
33
+ await client.query({ text: "ROLLBACK" });
34
+ throw error;
35
+ } finally {
36
+ client.release();
37
+ }
38
+ }
39
+ });
40
+
41
+ exports.RAW_DATE_PARSERS = RAW_DATE_PARSERS;
42
+ exports.createPgPool = createPgPool;
43
+ //# sourceMappingURL=index.cjs.map
44
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/adapters/postgres/date-parsers.ts","../../../src/adapters/pg/index.ts"],"names":["pg"],"mappings":";;;;;;;;;;;AAEA,IAAM,GAAA,GAAM,CAAC,KAAA,KAA0B,KAAA;AAIhC,IAAM,gBAAA,GAAgC,EAAE,IAAA,EAAM,GAAA,EAAK,MAAM,GAAA;;;ACYhE,IAAM,OAAA,GAAU,CAAC,MAAA,EAAmB,OAAA,KAA8C;AAGhF,EAAA,MAAM,QACJ,OAAA,KAAY,MAAA,GACR,MAAA,GACA,EAAE,eAAe,CAAC,GAAA,EAAa,MAAA,KAA+B,OAAA,CAAQ,GAAG,CAAA,IAAKA,mBAAA,CAAG,MAAM,aAAA,CAAc,GAAA,EAAK,MAAM,CAAA,EAAE;AACxH,EAAA,OAAO,OAAO,MAAM,MAAA,KAAW;AAC7B,IAAA,MAAM,EAAE,IAAA,EAAM,MAAA,EAAO,GAAI,MAAM,OAAO,KAAA,CAAM,EAAE,IAAA,EAAM,GAAI,MAAA,KAAW,MAAA,GAAY,EAAC,GAAI,EAAE,MAAA,EAAO,EAAI,GAAI,KAAA,KAAU,MAAA,GAAY,EAAC,GAAI,EAAE,KAAA,EAAM,EAAI,CAAA;AAC5I,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,MAAA,CAAO,IAAI,CAAC,EAAE,IAAA,EAAM,UAAA,EAAW,MAAO,EAAE,IAAA,EAAM,UAAA,GAAa,CAAA,EAAE;AAAA,EACtF,CAAA;AACF,CAAA;AAEO,IAAM,YAAA,GAAe,CAAC,IAAA,EAAwB,OAAA,MAAmC;AAAA,EACtF,KAAA,EAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AAAA,EAC5B,WAAA,EAAa,OAAO,EAAA,KAAO;AACzB,IAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,OAAA,EAAQ;AAClC,IAAA,IAAI;AACF,MAAA,MAAM,MAAA,CAAO,KAAA,CAAM,EAAE,IAAA,EAAM,SAAS,CAAA;AACpC,MAAA,MAAM,MAAA,GAAS,MAAM,EAAA,CAAG,EAAE,OAAO,OAAA,CAAQ,MAAA,EAAQ,OAAO,CAAA,EAAG,CAAA;AAC3D,MAAA,MAAM,MAAA,CAAO,KAAA,CAAM,EAAE,IAAA,EAAM,UAAU,CAAA;AACrC,MAAA,OAAO,MAAA;AAAA,IACT,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,MAAA,CAAO,KAAA,CAAM,EAAE,IAAA,EAAM,YAAY,CAAA;AACvC,MAAA,MAAM,KAAA;AAAA,IACR,CAAA,SAAE;AACA,MAAA,MAAA,CAAO,OAAA,EAAQ;AAAA,IACjB;AAAA,EACF;AACF,CAAA","file":"index.cjs","sourcesContent":["export type TypeParsers = Record<number, (value: string) => unknown>;\n\nconst RAW = (value: string): string => value;\n\n// OIDs: DATE is 1082, TIMESTAMPTZ is 1184. Not for a pool handed to the vex\n// cache, which reads its timestamp columns as Dates.\nexport const RAW_DATE_PARSERS: TypeParsers = { 1082: RAW, 1184: RAW };\n","import pg from 'pg';\nimport type { PgPool, PgQuery } from '../postgres/introspect.js';\nimport type { TypeParsers } from '../postgres/date-parsers.js';\n\nexport { RAW_DATE_PARSERS } from '../postgres/date-parsers.js';\n\ntype QueryConfig = {\n text: string;\n values?: unknown[];\n types?: { getTypeParser: (oid: number, format?: 'text' | 'binary') => (value: string) => unknown };\n};\n\ntype Queryable = {\n query: (config: QueryConfig) => Promise<{ rows: Record<string, unknown>[]; fields: Array<{ name: string; dataTypeID: number }> }>;\n};\n\ntype NodePostgresPool = Queryable & { connect: () => Promise<Queryable & { release: () => void }> };\n\nconst queryOn = (target: Queryable, parsers: TypeParsers | undefined): PgQuery => {\n // A query's own `types` replaces pg's lookup entirely, so every OID the\n // parsers leave out falls back to pg's.\n const types =\n parsers === undefined\n ? undefined\n : { getTypeParser: (oid: number, format?: 'text' | 'binary') => parsers[oid] ?? pg.types.getTypeParser(oid, format) };\n return async (text, values) => {\n const { rows, fields } = await target.query({ text, ...(values === undefined ? {} : { values }), ...(types === undefined ? {} : { types }) });\n return { rows, fields: fields.map(({ name, dataTypeID }) => ({ name, dataTypeID })) };\n };\n};\n\nexport const createPgPool = (pool: NodePostgresPool, parsers?: TypeParsers): PgPool => ({\n query: queryOn(pool, parsers),\n transaction: async (fn) => {\n const client = await pool.connect();\n try {\n await client.query({ text: 'BEGIN' });\n const result = await fn({ query: queryOn(client, parsers) });\n await client.query({ text: 'COMMIT' });\n return result;\n } catch (error) {\n await client.query({ text: 'ROLLBACK' });\n throw error;\n } finally {\n client.release();\n }\n },\n});\n"]}
@@ -0,0 +1,28 @@
1
+ import { P as PgPool } from '../../introspect-D3OaXHBc.cjs';
2
+ import { T as TypeParsers } from '../../date-parsers-BaUuE_ax.cjs';
3
+ export { R as RAW_DATE_PARSERS } from '../../date-parsers-BaUuE_ax.cjs';
4
+
5
+ type QueryConfig = {
6
+ text: string;
7
+ values?: unknown[];
8
+ types?: {
9
+ getTypeParser: (oid: number, format?: 'text' | 'binary') => (value: string) => unknown;
10
+ };
11
+ };
12
+ type Queryable = {
13
+ query: (config: QueryConfig) => Promise<{
14
+ rows: Record<string, unknown>[];
15
+ fields: Array<{
16
+ name: string;
17
+ dataTypeID: number;
18
+ }>;
19
+ }>;
20
+ };
21
+ type NodePostgresPool = Queryable & {
22
+ connect: () => Promise<Queryable & {
23
+ release: () => void;
24
+ }>;
25
+ };
26
+ declare const createPgPool: (pool: NodePostgresPool, parsers?: TypeParsers) => PgPool;
27
+
28
+ export { createPgPool };
@@ -0,0 +1,28 @@
1
+ import { P as PgPool } from '../../introspect-D3OaXHBc.js';
2
+ import { T as TypeParsers } from '../../date-parsers-BaUuE_ax.js';
3
+ export { R as RAW_DATE_PARSERS } from '../../date-parsers-BaUuE_ax.js';
4
+
5
+ type QueryConfig = {
6
+ text: string;
7
+ values?: unknown[];
8
+ types?: {
9
+ getTypeParser: (oid: number, format?: 'text' | 'binary') => (value: string) => unknown;
10
+ };
11
+ };
12
+ type Queryable = {
13
+ query: (config: QueryConfig) => Promise<{
14
+ rows: Record<string, unknown>[];
15
+ fields: Array<{
16
+ name: string;
17
+ dataTypeID: number;
18
+ }>;
19
+ }>;
20
+ };
21
+ type NodePostgresPool = Queryable & {
22
+ connect: () => Promise<Queryable & {
23
+ release: () => void;
24
+ }>;
25
+ };
26
+ declare const createPgPool: (pool: NodePostgresPool, parsers?: TypeParsers) => PgPool;
27
+
28
+ export { createPgPool };
@@ -0,0 +1,31 @@
1
+ export { RAW_DATE_PARSERS } from '../../chunk-DFWYYBJU.js';
2
+ import pg from 'pg';
3
+
4
+ var queryOn = (target, parsers) => {
5
+ const types = parsers === void 0 ? void 0 : { getTypeParser: (oid, format) => parsers[oid] ?? pg.types.getTypeParser(oid, format) };
6
+ return async (text, values) => {
7
+ const { rows, fields } = await target.query({ text, ...values === void 0 ? {} : { values }, ...types === void 0 ? {} : { types } });
8
+ return { rows, fields: fields.map(({ name, dataTypeID }) => ({ name, dataTypeID })) };
9
+ };
10
+ };
11
+ var createPgPool = (pool, parsers) => ({
12
+ query: queryOn(pool, parsers),
13
+ transaction: async (fn) => {
14
+ const client = await pool.connect();
15
+ try {
16
+ await client.query({ text: "BEGIN" });
17
+ const result = await fn({ query: queryOn(client, parsers) });
18
+ await client.query({ text: "COMMIT" });
19
+ return result;
20
+ } catch (error) {
21
+ await client.query({ text: "ROLLBACK" });
22
+ throw error;
23
+ } finally {
24
+ client.release();
25
+ }
26
+ }
27
+ });
28
+
29
+ export { createPgPool };
30
+ //# sourceMappingURL=index.js.map
31
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/adapters/pg/index.ts"],"names":[],"mappings":";;;AAkBA,IAAM,OAAA,GAAU,CAAC,MAAA,EAAmB,OAAA,KAA8C;AAGhF,EAAA,MAAM,QACJ,OAAA,KAAY,MAAA,GACR,MAAA,GACA,EAAE,eAAe,CAAC,GAAA,EAAa,MAAA,KAA+B,OAAA,CAAQ,GAAG,CAAA,IAAK,EAAA,CAAG,MAAM,aAAA,CAAc,GAAA,EAAK,MAAM,CAAA,EAAE;AACxH,EAAA,OAAO,OAAO,MAAM,MAAA,KAAW;AAC7B,IAAA,MAAM,EAAE,IAAA,EAAM,MAAA,EAAO,GAAI,MAAM,OAAO,KAAA,CAAM,EAAE,IAAA,EAAM,GAAI,MAAA,KAAW,MAAA,GAAY,EAAC,GAAI,EAAE,MAAA,EAAO,EAAI,GAAI,KAAA,KAAU,MAAA,GAAY,EAAC,GAAI,EAAE,KAAA,EAAM,EAAI,CAAA;AAC5I,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,MAAA,CAAO,IAAI,CAAC,EAAE,IAAA,EAAM,UAAA,EAAW,MAAO,EAAE,IAAA,EAAM,UAAA,GAAa,CAAA,EAAE;AAAA,EACtF,CAAA;AACF,CAAA;AAEO,IAAM,YAAA,GAAe,CAAC,IAAA,EAAwB,OAAA,MAAmC;AAAA,EACtF,KAAA,EAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AAAA,EAC5B,WAAA,EAAa,OAAO,EAAA,KAAO;AACzB,IAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,OAAA,EAAQ;AAClC,IAAA,IAAI;AACF,MAAA,MAAM,MAAA,CAAO,KAAA,CAAM,EAAE,IAAA,EAAM,SAAS,CAAA;AACpC,MAAA,MAAM,MAAA,GAAS,MAAM,EAAA,CAAG,EAAE,OAAO,OAAA,CAAQ,MAAA,EAAQ,OAAO,CAAA,EAAG,CAAA;AAC3D,MAAA,MAAM,MAAA,CAAO,KAAA,CAAM,EAAE,IAAA,EAAM,UAAU,CAAA;AACrC,MAAA,OAAO,MAAA;AAAA,IACT,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,MAAA,CAAO,KAAA,CAAM,EAAE,IAAA,EAAM,YAAY,CAAA;AACvC,MAAA,MAAM,KAAA;AAAA,IACR,CAAA,SAAE;AACA,MAAA,MAAA,CAAO,OAAA,EAAQ;AAAA,IACjB;AAAA,EACF;AACF,CAAA","file":"index.js","sourcesContent":["import pg from 'pg';\nimport type { PgPool, PgQuery } from '../postgres/introspect.js';\nimport type { TypeParsers } from '../postgres/date-parsers.js';\n\nexport { RAW_DATE_PARSERS } from '../postgres/date-parsers.js';\n\ntype QueryConfig = {\n text: string;\n values?: unknown[];\n types?: { getTypeParser: (oid: number, format?: 'text' | 'binary') => (value: string) => unknown };\n};\n\ntype Queryable = {\n query: (config: QueryConfig) => Promise<{ rows: Record<string, unknown>[]; fields: Array<{ name: string; dataTypeID: number }> }>;\n};\n\ntype NodePostgresPool = Queryable & { connect: () => Promise<Queryable & { release: () => void }> };\n\nconst queryOn = (target: Queryable, parsers: TypeParsers | undefined): PgQuery => {\n // A query's own `types` replaces pg's lookup entirely, so every OID the\n // parsers leave out falls back to pg's.\n const types =\n parsers === undefined\n ? undefined\n : { getTypeParser: (oid: number, format?: 'text' | 'binary') => parsers[oid] ?? pg.types.getTypeParser(oid, format) };\n return async (text, values) => {\n const { rows, fields } = await target.query({ text, ...(values === undefined ? {} : { values }), ...(types === undefined ? {} : { types }) });\n return { rows, fields: fields.map(({ name, dataTypeID }) => ({ name, dataTypeID })) };\n };\n};\n\nexport const createPgPool = (pool: NodePostgresPool, parsers?: TypeParsers): PgPool => ({\n query: queryOn(pool, parsers),\n transaction: async (fn) => {\n const client = await pool.connect();\n try {\n await client.query({ text: 'BEGIN' });\n const result = await fn({ query: queryOn(client, parsers) });\n await client.query({ text: 'COMMIT' });\n return result;\n } catch (error) {\n await client.query({ text: 'ROLLBACK' });\n throw error;\n } finally {\n client.release();\n }\n },\n});\n"]}
@@ -1,8 +1,10 @@
1
1
  'use strict';
2
2
 
3
- // src/adapters/pglite/index.ts
3
+ // src/adapters/postgres/date-parsers.ts
4
4
  var RAW = (value) => value;
5
5
  var RAW_DATE_PARSERS = { 1082: RAW, 1184: RAW };
6
+
7
+ // src/adapters/pglite/index.ts
6
8
  var createPglitePool = (db, parsers) => {
7
9
  const options = parsers !== void 0 ? { parsers } : void 0;
8
10
  const pool = { query: (text, values) => db.query(text, values, options), statementTimeouts: false };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/adapters/pglite/index.ts"],"names":[],"mappings":";;;AAaA,IAAM,GAAA,GAAM,CAAC,KAAA,KAA0B,KAAA;AAIhC,IAAM,gBAAA,GAA+D,EAAE,IAAA,EAAM,GAAA,EAAK,MAAM,GAAA;AAExF,IAAM,gBAAA,GAAmB,CAAC,EAAA,EAAgB,OAAA,KAAiE;AAChH,EAAA,MAAM,OAAA,GAAU,OAAA,KAAY,MAAA,GAAY,EAAE,SAAQ,GAAI,MAAA;AAGtD,EAAA,MAAM,IAAA,GAAe,EAAE,KAAA,EAAO,CAAC,IAAA,EAAM,MAAA,KAAW,EAAA,CAAG,KAAA,CAAM,IAAA,EAAM,MAAA,EAAQ,OAAO,CAAA,EAAG,mBAAmB,KAAA,EAAM;AAI1G,EAAA,IAAI,GAAG,WAAA,KAAgB,MAAA;AACrB,IAAA,IAAA,CAAK,WAAA,GAAc,CAAC,EAAA,KAAO,EAAA,CAAG,YAAa,CAAC,EAAA,KAAO,GAAG,EAAE,KAAA,EAAO,CAAC,IAAA,EAAM,MAAA,KAAW,GAAG,KAAA,CAAM,IAAA,EAAM,QAAQ,OAAO,CAAA,EAAG,CAAC,CAAA;AAErH,EAAA,OAAO,IAAA;AACT","file":"index.cjs","sourcesContent":["import type { PgPool } from '../postgres/introspect.js';\n\ntype PgliteQuery = (\n text: string,\n values?: unknown[],\n options?: { parsers?: Record<number, (value: string) => unknown> },\n) => Promise<{ rows: Record<string, unknown>[]; fields?: Array<{ name: string; dataTypeID: number }> }>;\n\ntype PgliteLike = {\n query: PgliteQuery;\n transaction?: <T>(fn: (tx: { query: PgliteQuery }) => Promise<T>) => Promise<T>;\n};\n\nconst RAW = (value: string): string => value;\n\n// OIDs: DATE is 1082, TIMESTAMPTZ is 1184. Not for a pool handed to the vex\n// cache, which reads its timestamp columns as Dates.\nexport const RAW_DATE_PARSERS: Record<number, (value: string) => unknown> = { 1082: RAW, 1184: RAW };\n\nexport const createPglitePool = (db: PgliteLike, parsers?: Record<number, (value: string) => unknown>): PgPool => {\n const options = parsers !== undefined ? { parsers } : undefined;\n // PGlite runs Postgres on one thread, where `statement_timeout`'s timer\n // never fires.\n const pool: PgPool = { query: (text, values) => db.query(text, values, options), statementTimeouts: false };\n\n // Called on `db`, not destructured off it: PGlite's `transaction` is a class\n // method that needs its receiver.\n if (db.transaction !== undefined)\n pool.transaction = (fn) => db.transaction!((tx) => fn({ query: (text, values) => tx.query(text, values, options) }));\n\n return pool;\n};\n"]}
1
+ {"version":3,"sources":["../../../src/adapters/postgres/date-parsers.ts","../../../src/adapters/pglite/index.ts"],"names":[],"mappings":";;;AAEA,IAAM,GAAA,GAAM,CAAC,KAAA,KAA0B,KAAA;AAIhC,IAAM,gBAAA,GAAgC,EAAE,IAAA,EAAM,GAAA,EAAK,MAAM,GAAA;;;ACUzD,IAAM,gBAAA,GAAmB,CAAC,EAAA,EAAgB,OAAA,KAAkC;AACjF,EAAA,MAAM,OAAA,GAAU,OAAA,KAAY,MAAA,GAAY,EAAE,SAAQ,GAAI,MAAA;AAGtD,EAAA,MAAM,IAAA,GAAe,EAAE,KAAA,EAAO,CAAC,IAAA,EAAM,MAAA,KAAW,EAAA,CAAG,KAAA,CAAM,IAAA,EAAM,MAAA,EAAQ,OAAO,CAAA,EAAG,mBAAmB,KAAA,EAAM;AAI1G,EAAA,IAAI,GAAG,WAAA,KAAgB,MAAA;AACrB,IAAA,IAAA,CAAK,WAAA,GAAc,CAAC,EAAA,KAAO,EAAA,CAAG,YAAa,CAAC,EAAA,KAAO,GAAG,EAAE,KAAA,EAAO,CAAC,IAAA,EAAM,MAAA,KAAW,GAAG,KAAA,CAAM,IAAA,EAAM,QAAQ,OAAO,CAAA,EAAG,CAAC,CAAA;AAErH,EAAA,OAAO,IAAA;AACT","file":"index.cjs","sourcesContent":["export type TypeParsers = Record<number, (value: string) => unknown>;\n\nconst RAW = (value: string): string => value;\n\n// OIDs: DATE is 1082, TIMESTAMPTZ is 1184. Not for a pool handed to the vex\n// cache, which reads its timestamp columns as Dates.\nexport const RAW_DATE_PARSERS: TypeParsers = { 1082: RAW, 1184: RAW };\n","import type { PgPool } from '../postgres/introspect.js';\nimport type { TypeParsers } from '../postgres/date-parsers.js';\n\nexport { RAW_DATE_PARSERS } from '../postgres/date-parsers.js';\n\ntype PgliteQuery = (\n text: string,\n values?: unknown[],\n options?: { parsers?: TypeParsers },\n) => Promise<{ rows: Record<string, unknown>[]; fields?: Array<{ name: string; dataTypeID: number }> }>;\n\ntype PgliteLike = {\n query: PgliteQuery;\n transaction?: <T>(fn: (tx: { query: PgliteQuery }) => Promise<T>) => Promise<T>;\n};\n\nexport const createPglitePool = (db: PgliteLike, parsers?: TypeParsers): PgPool => {\n const options = parsers !== undefined ? { parsers } : undefined;\n // PGlite runs Postgres on one thread, where `statement_timeout`'s timer\n // never fires.\n const pool: PgPool = { query: (text, values) => db.query(text, values, options), statementTimeouts: false };\n\n // Called on `db`, not destructured off it: PGlite's `transaction` is a class\n // method that needs its receiver.\n if (db.transaction !== undefined)\n pool.transaction = (fn) => db.transaction!((tx) => fn({ query: (text, values) => tx.query(text, values, options) }));\n\n return pool;\n};\n"]}
@@ -1,7 +1,9 @@
1
1
  import { P as PgPool } from '../../introspect-D3OaXHBc.cjs';
2
+ import { T as TypeParsers } from '../../date-parsers-BaUuE_ax.cjs';
3
+ export { R as RAW_DATE_PARSERS } from '../../date-parsers-BaUuE_ax.cjs';
2
4
 
3
5
  type PgliteQuery = (text: string, values?: unknown[], options?: {
4
- parsers?: Record<number, (value: string) => unknown>;
6
+ parsers?: TypeParsers;
5
7
  }) => Promise<{
6
8
  rows: Record<string, unknown>[];
7
9
  fields?: Array<{
@@ -15,7 +17,6 @@ type PgliteLike = {
15
17
  query: PgliteQuery;
16
18
  }) => Promise<T>) => Promise<T>;
17
19
  };
18
- declare const RAW_DATE_PARSERS: Record<number, (value: string) => unknown>;
19
- declare const createPglitePool: (db: PgliteLike, parsers?: Record<number, (value: string) => unknown>) => PgPool;
20
+ declare const createPglitePool: (db: PgliteLike, parsers?: TypeParsers) => PgPool;
20
21
 
21
- export { RAW_DATE_PARSERS, createPglitePool };
22
+ export { createPglitePool };
@@ -1,7 +1,9 @@
1
1
  import { P as PgPool } from '../../introspect-D3OaXHBc.js';
2
+ import { T as TypeParsers } from '../../date-parsers-BaUuE_ax.js';
3
+ export { R as RAW_DATE_PARSERS } from '../../date-parsers-BaUuE_ax.js';
2
4
 
3
5
  type PgliteQuery = (text: string, values?: unknown[], options?: {
4
- parsers?: Record<number, (value: string) => unknown>;
6
+ parsers?: TypeParsers;
5
7
  }) => Promise<{
6
8
  rows: Record<string, unknown>[];
7
9
  fields?: Array<{
@@ -15,7 +17,6 @@ type PgliteLike = {
15
17
  query: PgliteQuery;
16
18
  }) => Promise<T>) => Promise<T>;
17
19
  };
18
- declare const RAW_DATE_PARSERS: Record<number, (value: string) => unknown>;
19
- declare const createPglitePool: (db: PgliteLike, parsers?: Record<number, (value: string) => unknown>) => PgPool;
20
+ declare const createPglitePool: (db: PgliteLike, parsers?: TypeParsers) => PgPool;
20
21
 
21
- export { RAW_DATE_PARSERS, createPglitePool };
22
+ export { createPglitePool };
@@ -1,6 +1,6 @@
1
+ export { RAW_DATE_PARSERS } from '../../chunk-DFWYYBJU.js';
2
+
1
3
  // src/adapters/pglite/index.ts
2
- var RAW = (value) => value;
3
- var RAW_DATE_PARSERS = { 1082: RAW, 1184: RAW };
4
4
  var createPglitePool = (db, parsers) => {
5
5
  const options = parsers !== void 0 ? { parsers } : void 0;
6
6
  const pool = { query: (text, values) => db.query(text, values, options), statementTimeouts: false };
@@ -9,6 +9,6 @@ var createPglitePool = (db, parsers) => {
9
9
  return pool;
10
10
  };
11
11
 
12
- export { RAW_DATE_PARSERS, createPglitePool };
12
+ export { createPglitePool };
13
13
  //# sourceMappingURL=index.js.map
14
14
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/adapters/pglite/index.ts"],"names":[],"mappings":";AAaA,IAAM,GAAA,GAAM,CAAC,KAAA,KAA0B,KAAA;AAIhC,IAAM,gBAAA,GAA+D,EAAE,IAAA,EAAM,GAAA,EAAK,MAAM,GAAA;AAExF,IAAM,gBAAA,GAAmB,CAAC,EAAA,EAAgB,OAAA,KAAiE;AAChH,EAAA,MAAM,OAAA,GAAU,OAAA,KAAY,MAAA,GAAY,EAAE,SAAQ,GAAI,MAAA;AAGtD,EAAA,MAAM,IAAA,GAAe,EAAE,KAAA,EAAO,CAAC,IAAA,EAAM,MAAA,KAAW,EAAA,CAAG,KAAA,CAAM,IAAA,EAAM,MAAA,EAAQ,OAAO,CAAA,EAAG,mBAAmB,KAAA,EAAM;AAI1G,EAAA,IAAI,GAAG,WAAA,KAAgB,MAAA;AACrB,IAAA,IAAA,CAAK,WAAA,GAAc,CAAC,EAAA,KAAO,EAAA,CAAG,YAAa,CAAC,EAAA,KAAO,GAAG,EAAE,KAAA,EAAO,CAAC,IAAA,EAAM,MAAA,KAAW,GAAG,KAAA,CAAM,IAAA,EAAM,QAAQ,OAAO,CAAA,EAAG,CAAC,CAAA;AAErH,EAAA,OAAO,IAAA;AACT","file":"index.js","sourcesContent":["import type { PgPool } from '../postgres/introspect.js';\n\ntype PgliteQuery = (\n text: string,\n values?: unknown[],\n options?: { parsers?: Record<number, (value: string) => unknown> },\n) => Promise<{ rows: Record<string, unknown>[]; fields?: Array<{ name: string; dataTypeID: number }> }>;\n\ntype PgliteLike = {\n query: PgliteQuery;\n transaction?: <T>(fn: (tx: { query: PgliteQuery }) => Promise<T>) => Promise<T>;\n};\n\nconst RAW = (value: string): string => value;\n\n// OIDs: DATE is 1082, TIMESTAMPTZ is 1184. Not for a pool handed to the vex\n// cache, which reads its timestamp columns as Dates.\nexport const RAW_DATE_PARSERS: Record<number, (value: string) => unknown> = { 1082: RAW, 1184: RAW };\n\nexport const createPglitePool = (db: PgliteLike, parsers?: Record<number, (value: string) => unknown>): PgPool => {\n const options = parsers !== undefined ? { parsers } : undefined;\n // PGlite runs Postgres on one thread, where `statement_timeout`'s timer\n // never fires.\n const pool: PgPool = { query: (text, values) => db.query(text, values, options), statementTimeouts: false };\n\n // Called on `db`, not destructured off it: PGlite's `transaction` is a class\n // method that needs its receiver.\n if (db.transaction !== undefined)\n pool.transaction = (fn) => db.transaction!((tx) => fn({ query: (text, values) => tx.query(text, values, options) }));\n\n return pool;\n};\n"]}
1
+ {"version":3,"sources":["../../../src/adapters/pglite/index.ts"],"names":[],"mappings":";;;AAgBO,IAAM,gBAAA,GAAmB,CAAC,EAAA,EAAgB,OAAA,KAAkC;AACjF,EAAA,MAAM,OAAA,GAAU,OAAA,KAAY,MAAA,GAAY,EAAE,SAAQ,GAAI,MAAA;AAGtD,EAAA,MAAM,IAAA,GAAe,EAAE,KAAA,EAAO,CAAC,IAAA,EAAM,MAAA,KAAW,EAAA,CAAG,KAAA,CAAM,IAAA,EAAM,MAAA,EAAQ,OAAO,CAAA,EAAG,mBAAmB,KAAA,EAAM;AAI1G,EAAA,IAAI,GAAG,WAAA,KAAgB,MAAA;AACrB,IAAA,IAAA,CAAK,WAAA,GAAc,CAAC,EAAA,KAAO,EAAA,CAAG,YAAa,CAAC,EAAA,KAAO,GAAG,EAAE,KAAA,EAAO,CAAC,IAAA,EAAM,MAAA,KAAW,GAAG,KAAA,CAAM,IAAA,EAAM,QAAQ,OAAO,CAAA,EAAG,CAAC,CAAA;AAErH,EAAA,OAAO,IAAA;AACT","file":"index.js","sourcesContent":["import type { PgPool } from '../postgres/introspect.js';\nimport type { TypeParsers } from '../postgres/date-parsers.js';\n\nexport { RAW_DATE_PARSERS } from '../postgres/date-parsers.js';\n\ntype PgliteQuery = (\n text: string,\n values?: unknown[],\n options?: { parsers?: TypeParsers },\n) => Promise<{ rows: Record<string, unknown>[]; fields?: Array<{ name: string; dataTypeID: number }> }>;\n\ntype PgliteLike = {\n query: PgliteQuery;\n transaction?: <T>(fn: (tx: { query: PgliteQuery }) => Promise<T>) => Promise<T>;\n};\n\nexport const createPglitePool = (db: PgliteLike, parsers?: TypeParsers): PgPool => {\n const options = parsers !== undefined ? { parsers } : undefined;\n // PGlite runs Postgres on one thread, where `statement_timeout`'s timer\n // never fires.\n const pool: PgPool = { query: (text, values) => db.query(text, values, options), statementTimeouts: false };\n\n // Called on `db`, not destructured off it: PGlite's `transaction` is a class\n // method that needs its receiver.\n if (db.transaction !== undefined)\n pool.transaction = (fn) => db.transaction!((tx) => fn({ query: (text, values) => tx.query(text, values, options) }));\n\n return pool;\n};\n"]}
@@ -332,6 +332,114 @@ var createQueryTools = (deps) => {
332
332
  cannotSatisfyTool
333
333
  ];
334
334
  };
335
+
336
+ // src/agent/compact.ts
337
+ var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
338
+ var compactSchema = (schema) => schema.entities.map((entity) => {
339
+ const fields = entity.fields.map((field) => `${field.name} ${field.type}${field.primaryKey ? " key" : ""}${field.nullable ? " null" : ""}`);
340
+ const relations = entity.relations.map((relation) => `${relation.type} ${relation.entity} (${relation.localFields.join(", ")} = ${relation.entity}.${relation.foreignFields.join(", ")})`);
341
+ const indexed = entity.indexes.filter((index) => !(index.unique && index.fields.length === 1 && entity.fields.some((field) => field.primaryKey && field.name === index.fields[0])));
342
+ return [
343
+ `${entity.name}${entity.table === entity.name ? "" : ` (table ${entity.table})`}: ${fields.join(", ")}`,
344
+ ...relations.length > 0 ? [` relations: ${relations.join("; ")}`] : [],
345
+ ...indexed.length > 0 ? [` indexed: ${indexed.map((index) => `${index.fields.join("+")}${index.unique ? " unique" : ""}`).join(", ")}`] : []
346
+ ].join("\n");
347
+ }).join("\n");
348
+ var nameOf = (ref) => ref.replace(/^#\/definitions\/(?:__schema)?/, "D");
349
+ var noteOf = (node) => {
350
+ const limits = ["minItems", "maxItems", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", "pattern", "format", "default"].filter((key) => key in node).map((key) => `${key} ${JSON.stringify(node[key])}`);
351
+ return limits.length > 0 ? ` (${limits.join(", ")})` : "";
352
+ };
353
+ var describedOf = (node) => isRecord(node) && typeof node["description"] === "string" ? ` /* ${node["description"]} */` : "";
354
+ var SPELLED = /* @__PURE__ */ new Set(["$ref", "anyOf", "oneOf", "allOf", "enum", "const", "type", "items", "properties", "required", "additionalProperties", "description", "minItems", "maxItems", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", "pattern", "format", "default", "$schema"]);
355
+ var typeOf = (node, indent) => isRecord(node) && !Object.keys(node).some((key) => !SPELLED.has(key)) ? `${shapeOf(node, indent)}${describedOf(node)}` : JSON.stringify(node);
356
+ var shapeOf = (node, indent) => {
357
+ if (typeof node["$ref"] === "string") return nameOf(node["$ref"]);
358
+ const alternatives = node["anyOf"] ?? node["oneOf"];
359
+ if (Array.isArray(alternatives)) {
360
+ if (!alternatives.some((alternative) => describedOf(alternative) !== "")) return alternatives.map((alternative) => typeOf(alternative, indent)).join(" | ");
361
+ return alternatives.map((alternative) => `
362
+ ${indent} | ${typeOf(alternative, `${indent} `)}`).join("");
363
+ }
364
+ if (Array.isArray(node["allOf"])) return node["allOf"].map((part) => typeOf(part, indent)).join(" & ");
365
+ if (Array.isArray(node["enum"])) return node["enum"].map((value) => JSON.stringify(value)).join(" | ");
366
+ if ("const" in node) return JSON.stringify(node["const"]);
367
+ const kind = node["type"];
368
+ if (kind === "array") {
369
+ const item = typeOf(node["items"], indent);
370
+ return `${/[ |&]/.test(item) ? `(${item})` : item}[]${noteOf(node)}`;
371
+ }
372
+ if (kind === "object" || isRecord(node["properties"])) {
373
+ const required = new Set(Array.isArray(node["required"]) ? node["required"] : []);
374
+ const properties = Object.entries(isRecord(node["properties"]) ? node["properties"] : {}).map(
375
+ ([key, value]) => `${key}${required.has(key) ? "" : "?"}: ${typeOf(value, indent)}`
376
+ );
377
+ const rest = isRecord(node["additionalProperties"]) ? [`[key: string]: ${typeOf(node["additionalProperties"], indent)}`] : [];
378
+ return `{ ${[...properties, ...rest].join(", ")} }`;
379
+ }
380
+ if (Array.isArray(kind)) return kind.join(" | ");
381
+ if (typeof kind === "string") return `${kind}${noteOf(node)}`;
382
+ return JSON.stringify(node);
383
+ };
384
+ var compactSpec = (jsonSchema) => {
385
+ const root = jsonSchema;
386
+ const definitions = isRecord(root["definitions"]) ? root["definitions"] : {};
387
+ const number = (name) => Number(name.replace(/\D/g, "")) || 0;
388
+ return [
389
+ 'The query is one JSON object of type Query; every Dn is defined below. "a?: T" is optional, "A | B" is either.',
390
+ `Query = ${typeOf({ type: "object", properties: root["properties"], required: root["required"] }, "")}`,
391
+ ...Object.entries(definitions).sort(([a], [b]) => number(a) - number(b)).map(([name, node]) => `${nameOf(`#/definitions/${name}`)} = ${typeOf(node, "")}`)
392
+ ].join("\n");
393
+ };
394
+
395
+ // src/agent/declared.ts
396
+ var isRecord2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
397
+ var isExpression = (value) => isRecord2(value) && Object.keys(value).length === 1 && Object.keys(value)[0]?.startsWith("$") === true;
398
+ var templateOf = (shape) => Array.isArray(shape) ? shape[0] : shape;
399
+ var readsOf = (value) => {
400
+ if (Array.isArray(value)) return value.flatMap(readsOf);
401
+ if (!isRecord2(value)) return [];
402
+ const ref = value["$ref"];
403
+ const own = typeof ref === "string" && ref.startsWith("$.") ? [ref.slice(2).split(".")[0] ?? ""] : [];
404
+ return [...own, ...Object.values(value).flatMap(readsOf)].filter((field) => field !== "");
405
+ };
406
+ var fieldsOf = (shape) => {
407
+ const template = templateOf(shape);
408
+ if (!isRecord2(template)) return void 0;
409
+ const entries = Object.entries(template);
410
+ if (entries.some(([, value]) => (isRecord2(value) || Array.isArray(value)) && !isExpression(value))) return void 0;
411
+ return {
412
+ plain: entries.filter(([, value]) => !isExpression(value)).map(([key]) => key),
413
+ declared: entries.filter((entry) => isExpression(entry[1]))
414
+ };
415
+ };
416
+ var storedShape = (shape) => {
417
+ const fields = fieldsOf(shape);
418
+ if (fields === void 0 || fields.declared.length === 0) return { shape, declared: false };
419
+ const template = templateOf(shape);
420
+ const kept = Object.fromEntries(fields.plain.map((key) => [key, template[key]]));
421
+ for (const [, expression] of fields.declared) for (const field of readsOf(expression)) if (!(field in kept)) kept[field] = "";
422
+ return { shape: Array.isArray(shape) ? [kept] : kept, declared: true };
423
+ };
424
+ var onRow = (value) => {
425
+ if (Array.isArray(value)) return value.map(onRow);
426
+ if (!isRecord2(value)) return value;
427
+ const ref = value["$ref"];
428
+ if (typeof ref === "string" && ref.startsWith("$.") && Object.keys(value).length === 1) return { $get: { from: { $var: "row" }, path: ref.slice(2).split("."), fallback: null } };
429
+ return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, onRow(inner)]));
430
+ };
431
+ var declaredMapping = (shape) => {
432
+ const fields = fieldsOf(shape);
433
+ if (fields === void 0) return void 0;
434
+ const template = templateOf(shape);
435
+ const body = Object.fromEntries([
436
+ ...fields.plain.map((key) => [key, { $get: { from: { $var: "row" }, path: [key], fallback: null } }]),
437
+ ...fields.declared.map(([key, expression]) => [key, onRow(expression)])
438
+ ]);
439
+ const reads = [.../* @__PURE__ */ new Set([...fields.plain, ...fields.declared.flatMap(([, expression]) => readsOf(expression))])];
440
+ const config = Array.isArray(shape) ? { $map: { over: { $ref: "$.result" }, as: "row", body } } : { $with: { let: { row: { $ref: "$.result" } }, value: body } };
441
+ return { config, reads, examples: Object.fromEntries(fields.plain.map((key) => [key, template[key]])) };
442
+ };
335
443
  var describeCaller = (bindings) => bindings.length === 0 ? 'The caller: no column in this schema is bound to anything that identifies the caller, so a request about "me", "my" or "mine" cannot be answered.' : [
336
444
  "The caller \u2014 the person or service this query is for \u2014 is identified by server-side scope values bound to these columns:",
337
445
  ...bindings.map((b) => `- ${b.entity}.${b.field} is the caller's { "$scope": "${b.key}" }`),
@@ -341,9 +449,9 @@ var INSTRUCTIONS = `You are Vex's query agent. You turn a caller's request \u201
341
449
 
342
450
  Context gives you two things:
343
451
  - the database schema: the entities, fields, relations, and indexes that actually exist;
344
- - the DSL JSON Schema: the exact structure your query must take. Its field
345
- descriptions ARE the rules \u2014 read them and follow them. They are the single
346
- source of truth for how every part of a query is written.
452
+ - the DSL specification, written as types: the exact structure your query must
453
+ take. Its descriptions ARE the rules \u2014 read them and follow them. They are the
454
+ single source of truth for how every part of a query is written.
347
455
 
348
456
  Your job is to RETRIEVE the data the request needs: choose the entities, columns,
349
457
  filters, computed values, and aggregates the schema supports. A separate step runs
@@ -380,7 +488,7 @@ var vexQueryDslAgent = cortex.defineAgent({
380
488
  ${deps.schemaJson}`,
381
489
  ({ deps }) => deps.caller ?? describeCaller([]),
382
490
  // Named OUTPUT SCHEMA because cortex's finish protocol refers to it by that name.
383
- ({ deps }) => `OUTPUT SCHEMA \u2014 the DSL specification (JSON Schema), the single source of truth for your query:
491
+ ({ deps }) => `OUTPUT SCHEMA \u2014 the DSL specification, written as types, the single source of truth for your query:
384
492
  ${deps.dslSpecJson}`
385
493
  ],
386
494
  // The DSL spec in the context is the schema documentation; with `doc` on it would be injected twice.
@@ -395,11 +503,14 @@ var reasonFrom = (args) => {
395
503
  return typeof reason === "string" ? reason : void 0;
396
504
  };
397
505
  var createQueryDsl = (config) => {
506
+ const dslSpec = compactSpec(config.queryJsonSchema);
398
507
  return async (request, schema, caller) => {
399
508
  const tools = createQueryTools({ getSchema: () => schema, read: caller.read });
509
+ const stored = storedShape(request.shape);
400
510
  const agentInput = {
401
- intent: request.intent,
402
- shape: request.shape,
511
+ intent: stored.declared ? `${request.intent ?? ""}
512
+ Return the stored fields the shape names; how a field is shown is worked out from them after the query.` : request.intent,
513
+ shape: stored.shape,
403
514
  contextKeys: Object.keys(request.context)
404
515
  };
405
516
  let unsatisfiableReason;
@@ -407,8 +518,8 @@ var createQueryDsl = (config) => {
407
518
  run = vexQueryDslAgent.run(agentInput, {
408
519
  llm: config.llm,
409
520
  deps: {
410
- schemaJson: JSON.stringify(schema),
411
- dslSpecJson: JSON.stringify(config.queryJsonSchema),
521
+ schemaJson: compactSchema(schema),
522
+ dslSpecJson: dslSpec,
412
523
  caller: describeCaller(caller.bindings)
413
524
  },
414
525
  tools,
@@ -444,24 +555,35 @@ var rowsFitShape = (rows, shape) => {
444
555
  return value === null || typeof value === typeof sample;
445
556
  });
446
557
  };
447
- var IDENTITY = { $ref: "$.result" };
558
+ var MAPPING_ATTEMPTS = 3;
448
559
  var createShapeMapper = (llm) => {
449
- return async (rows, shape) => {
560
+ return async (rows, shape, intent) => {
450
561
  const single = !Array.isArray(shape);
451
562
  const envelope = { result: single ? rows[0] ?? null : rows };
452
- if (rowsFitShape(rows, shape)) {
453
- const ir2 = await prism.compile(IDENTITY);
454
- return { ir: ir2, config: IDENTITY, transformed: prism.execute(ir2, envelope) };
563
+ const declared = declaredMapping(shape);
564
+ const first = rows[0];
565
+ const carried = first === void 0 || declared !== void 0 && declared.reads.every((field) => field in first) && Object.entries(declared.examples).every(([field, example]) => first[field] === null || typeof first[field] === typeof example);
566
+ if (declared !== void 0 && carried) {
567
+ const ir = await prism.compile(declared.config);
568
+ return { ir, config: declared.config, transformed: prism.execute(ir, envelope) };
569
+ }
570
+ let failed;
571
+ for (let attempt2 = 1; attempt2 <= MAPPING_ATTEMPTS; attempt2 += 1) {
572
+ const notes = [
573
+ ...intent !== void 0 ? [`The request these rows answer: ${intent}. The rows already answer it: they are filtered, sorted and limited. Give each value the form the request names, and keep every row, in order.`] : [],
574
+ ...failed !== void 0 ? [`Your last config failed on these rows: ${failed}. Write one that runs on them.`] : []
575
+ ].join("\n");
576
+ const result = await agent.mappingAgent.run({ sampleInput: envelope, targetShape: shape, ...notes !== "" ? { notes } : {} }, { llm }).result;
577
+ if (!result.ok) throw new VexError("agent_failed", `${result.error.code}: ${result.error.message}`);
578
+ const config = result.output.data;
579
+ try {
580
+ const ir = await prism.compile(config);
581
+ return { ir, config, transformed: prism.execute(ir, envelope) };
582
+ } catch (error) {
583
+ failed = error instanceof Error ? error.message : String(error);
584
+ }
455
585
  }
456
- const result = await agent.mappingAgent.run(
457
- { sampleInput: envelope, targetShape: shape },
458
- { llm }
459
- ).result;
460
- if (!result.ok) throw new VexError("agent_failed", `${result.error.code}: ${result.error.message}`);
461
- const config = result.output.data;
462
- const ir = await prism.compile(config);
463
- const transformed = prism.execute(ir, envelope);
464
- return { ir, config, transformed };
586
+ throw new VexError("agent_failed", `the mapping did not run on the rows it was written for: ${failed ?? "no reason given"}`);
465
587
  };
466
588
  };
467
589