@colin_kerr/query-agent-client 0.0.0-stage → 0.1.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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/dist/cjs/agent-client.d.ts +107 -0
  4. package/dist/cjs/agent-client.js +142 -0
  5. package/dist/cjs/agent-client.js.map +1 -0
  6. package/dist/cjs/caps.d.ts +43 -0
  7. package/dist/cjs/caps.js +51 -0
  8. package/dist/cjs/caps.js.map +1 -0
  9. package/dist/cjs/client.d.ts +145 -0
  10. package/dist/cjs/client.js +270 -0
  11. package/dist/cjs/client.js.map +1 -0
  12. package/dist/cjs/index.d.ts +11 -0
  13. package/dist/cjs/index.js +28 -0
  14. package/dist/cjs/index.js.map +1 -0
  15. package/dist/cjs/node/index.d.ts +27 -0
  16. package/dist/cjs/node/index.js +59 -0
  17. package/dist/cjs/node/index.js.map +1 -0
  18. package/dist/cjs/query-runner.d.ts +34 -0
  19. package/dist/cjs/query-runner.js +41 -0
  20. package/dist/cjs/query-runner.js.map +1 -0
  21. package/dist/cjs/result-pages.d.ts +69 -0
  22. package/dist/cjs/result-pages.js +176 -0
  23. package/dist/cjs/result-pages.js.map +1 -0
  24. package/dist/cjs/selection.d.ts +90 -0
  25. package/dist/cjs/selection.js +222 -0
  26. package/dist/cjs/selection.js.map +1 -0
  27. package/dist/cjs/startup-queries.json +182 -0
  28. package/dist/cjs/turn-api.d.ts +156 -0
  29. package/dist/cjs/turn-api.js +19 -0
  30. package/dist/cjs/turn-api.js.map +1 -0
  31. package/dist/esm/agent-client.d.ts +107 -0
  32. package/dist/esm/agent-client.js +134 -0
  33. package/dist/esm/agent-client.js.map +1 -0
  34. package/dist/esm/caps.d.ts +43 -0
  35. package/dist/esm/caps.js +48 -0
  36. package/dist/esm/caps.js.map +1 -0
  37. package/dist/esm/client.d.ts +145 -0
  38. package/dist/esm/client.js +260 -0
  39. package/dist/esm/client.js.map +1 -0
  40. package/dist/esm/index.d.ts +11 -0
  41. package/dist/esm/index.js +12 -0
  42. package/dist/esm/index.js.map +1 -0
  43. package/dist/esm/query-runner.d.ts +34 -0
  44. package/dist/esm/query-runner.js +38 -0
  45. package/dist/esm/query-runner.js.map +1 -0
  46. package/dist/esm/result-pages.d.ts +69 -0
  47. package/dist/esm/result-pages.js +172 -0
  48. package/dist/esm/result-pages.js.map +1 -0
  49. package/dist/esm/selection.d.ts +90 -0
  50. package/dist/esm/selection.js +212 -0
  51. package/dist/esm/selection.js.map +1 -0
  52. package/dist/esm/startup-queries.json +182 -0
  53. package/dist/esm/turn-api.d.ts +156 -0
  54. package/dist/esm/turn-api.js +16 -0
  55. package/dist/esm/turn-api.js.map +1 -0
  56. package/package.json +67 -4
@@ -0,0 +1,270 @@
1
+ "use strict";
2
+ /**
3
+ * The client's half of a turn: running the queries the function asks for and reading their rows,
4
+ * and running the startup query list before the first turn.
5
+ *
6
+ * The function never reaches the iModel. Each response names the queries to run and the caps to
7
+ * read them to; the client runs them on its own iModel and sends the rows with the next turn. The
8
+ * startup list's rows go with every turn, and the function writes them into the instructions.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.httpTurns = exports.TurnRefused = void 0;
12
+ exports.earlierQuestion = earlierQuestion;
13
+ exports.driveTurns = driveTurns;
14
+ exports.fetchTurns = fetchTurns;
15
+ exports.readQuery = readQuery;
16
+ exports.expandLists = expandLists;
17
+ exports.runStartupQueries = runStartupQueries;
18
+ const caps_js_1 = require("./caps.js");
19
+ const turn_api_js_1 = require("./turn-api.js");
20
+ /**
21
+ * An answered question as a later question of the chat sends it: as the user saw it, with the
22
+ * answer's rows cut to `HISTORY_CAPS`.
23
+ */
24
+ async function earlierQuestion(question, run) {
25
+ const query = run.structured?.query || run.query;
26
+ return {
27
+ question,
28
+ answer: run.answer,
29
+ ...(query ? { query } : {}),
30
+ ...(run.answerRows ? { rows: await historyRows(run.answerRows) } : {}),
31
+ stoppedBecause: run.stoppedBecause,
32
+ };
33
+ }
34
+ /**
35
+ * Rows read with the live caps, cut again to `HISTORY_CAPS`, by the same rule as a read. A cell the
36
+ * first read already cut keeps its full length.
37
+ */
38
+ async function historyRows(read) {
39
+ if (read.error !== undefined)
40
+ return { error: read.error };
41
+ const cut = await (0, caps_js_1.readCapped)({ columns: read.columns ?? [], rows: (async function* () { yield* read.rows ?? []; })() }, turn_api_js_1.HISTORY_CAPS);
42
+ const before = new Map((read.clipped ?? []).map(([row, column, length]) => [`${row},${column}`, length]));
43
+ const clipped = (cut.clipped ?? []).map(([row, column, length]) => [row, column, before.get(`${row},${column}`) ?? length]);
44
+ for (const [key, length] of before) {
45
+ const [row, column] = key.split(",").map(Number);
46
+ if (row < (cut.rows?.length ?? 0) && !clipped.some(([r, c]) => r === row && c === column))
47
+ clipped.push([row, column, length]);
48
+ }
49
+ const truncatedBy = cut.truncatedBy ?? read.truncatedBy;
50
+ return { columns: cut.columns, rows: cut.rows, ...(clipped.length > 0 ? { clipped } : {}), ...(truncatedBy ? { truncatedBy } : {}) };
51
+ }
52
+ /**
53
+ * Drive a run: send a turn, run the queries the response asks for, send their rows with the next
54
+ * turn, until the response says the run is over. When the user stops the run, the next turn says
55
+ * so, and the function ends it.
56
+ */
57
+ async function driveTurns(question, client, turn) {
58
+ const { runQuery } = client;
59
+ let token = client.token;
60
+ let results;
61
+ for (;;) {
62
+ const request = {
63
+ question, canQuery: runQuery !== undefined, imodel: client.imodel, editorText: client.editorText,
64
+ ...(client.earlier && client.earlier.length > 0 ? { earlier: [...client.earlier] } : {}),
65
+ ...(token ? { token } : {}),
66
+ ...(results ? { results } : {}),
67
+ ...(client.signal?.aborted ? { aborted: true } : {}),
68
+ ...(client.answerMode ? { answerMode: client.answerMode } : {}),
69
+ };
70
+ client.onPhase?.("thinking");
71
+ const response = await turn(request, client.signal);
72
+ token = response.token;
73
+ const done = response.done;
74
+ if (done) {
75
+ return {
76
+ answer: done.answer,
77
+ ...(done.query ? { query: done.query } : {}),
78
+ stoppedBecause: done.stoppedBecause,
79
+ ...(done.structured ? { structured: done.structured } : {}),
80
+ runId: done.runId,
81
+ token: response.token,
82
+ ...(done.resultType ? { resultType: done.resultType } : {}),
83
+ };
84
+ }
85
+ results = [];
86
+ for (const ecsql of response.queries) {
87
+ client.onPhase?.("querying", ecsql);
88
+ results.push(await readQuery(runQuery, ecsql, response.caps));
89
+ }
90
+ }
91
+ }
92
+ /** The refusals a user can act on: a chat to start again (400), a key to give or replace (401, 403), too long a request (413), a key used up (429). */
93
+ const REFUSALS = new Set([400, 401, 403, 413, 429]);
94
+ /**
95
+ * The function refused a turn for a reason the user can act on. `message` is the function's one
96
+ * sentence, meant to be shown as it is; `status` says which: 401 or 403 ask for an access key, 429
97
+ * means the key is used up, which can happen in the middle of a question, 413 means the request is
98
+ * too long, 400 means the chat must start again.
99
+ */
100
+ class TurnRefused extends Error {
101
+ status;
102
+ constructor(status, message) {
103
+ super(message);
104
+ this.status = status;
105
+ this.name = "TurnRefused";
106
+ }
107
+ }
108
+ exports.TurnRefused = TurnRefused;
109
+ /**
110
+ * Turns over HTTP: `POST <url>/turn`, the same code in a browser and in Node. When the user stops
111
+ * the run while a turn is in flight, the same turn is sent again, saying the run was stopped, so
112
+ * the function ends it with what it has.
113
+ */
114
+ function fetchTurns(url, options = {}) {
115
+ const post = async (request, signal) => {
116
+ const token = await options.getAccessToken?.();
117
+ const response = await fetch(`${url.replace(/\/+$/, "")}/turn`, {
118
+ method: "POST",
119
+ headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
120
+ body: JSON.stringify(request),
121
+ signal,
122
+ });
123
+ const body = await response.json();
124
+ const reason = body.error;
125
+ if (!response.ok && REFUSALS.has(response.status) && reason)
126
+ throw new TurnRefused(response.status, reason);
127
+ if (!response.ok)
128
+ throw new Error(`The agent function refused the turn (HTTP ${response.status}): ${reason ?? "no reason given"}`);
129
+ return body;
130
+ };
131
+ return async (request, signal) => {
132
+ // The turn that says the run was stopped must get through, so it is not tied to the signal.
133
+ if (request.aborted)
134
+ return post(request);
135
+ try {
136
+ return await post(request, signal);
137
+ }
138
+ catch (err) {
139
+ if (!signal?.aborted)
140
+ throw err;
141
+ return post({ ...request, aborted: true });
142
+ }
143
+ };
144
+ }
145
+ /**
146
+ * Run one query and read it up to the caps. A failure, at the start or part way through the
147
+ * rows, is sent as the query's error: the function hands it to the model to correct.
148
+ */
149
+ async function readQuery(runQuery, ecsql, caps) {
150
+ const started = Date.now();
151
+ try {
152
+ const read = await (0, caps_js_1.readCapped)(await runQuery(ecsql), caps);
153
+ return { ecsql, ...read, ms: Date.now() - started };
154
+ }
155
+ catch (err) {
156
+ return { ecsql, error: err instanceof Error ? err.message : String(err), ms: Date.now() - started };
157
+ }
158
+ }
159
+ /** How many result rows are read at most, whatever `max` says: a guard, not a display limit. */
160
+ const ROW_GUARD = 500;
161
+ function quote(value) {
162
+ return `'${value.replace(/'/g, "''")}'`;
163
+ }
164
+ /** Expand `{{in:list}}`, `{{like:expr:list}}` and `{{notlike:expr:list}}`. An unknown list throws. */
165
+ function expandLists(ecsql, lists) {
166
+ return ecsql.replace(/\{\{(in|like|notlike):([^}]+)\}\}/g, (_whole, kind, rest) => {
167
+ const at = rest.lastIndexOf(":");
168
+ const name = kind === "in" ? rest : rest.slice(at + 1);
169
+ const values = lists[name];
170
+ if (!values || values.length === 0)
171
+ throw new Error(`startup list: no list named "${name}"`);
172
+ if (kind === "in")
173
+ return values.map(quote).join(", ");
174
+ const expression = rest.slice(0, at);
175
+ const terms = values.map((value) => `${expression} ${kind === "like" ? "LIKE" : "NOT LIKE"} ${quote(value.includes("%") ? value : `%${value}%`)}`);
176
+ return `(${terms.join(kind === "like" ? " OR " : " AND ")})`;
177
+ });
178
+ }
179
+ /**
180
+ * A row's values inside the `each` query. They come from the file and land inside `[...]`, so
181
+ * a value that could close the bracket is refused; the row then sends null for `each`.
182
+ */
183
+ function fillIdentifiers(template, row) {
184
+ let safe = true;
185
+ const text = template.replace(/\{(\d+)\}/g, (_whole, index) => {
186
+ const value = String(row[Number(index)] ?? "");
187
+ if (!/^[A-Za-z0-9_]+$/.test(value))
188
+ safe = false;
189
+ return value;
190
+ });
191
+ return safe ? text : undefined;
192
+ }
193
+ async function readRows(runQuery, ecsql) {
194
+ const result = await runQuery(ecsql);
195
+ const rows = [];
196
+ for await (const row of result.rows) {
197
+ rows.push(row);
198
+ if (rows.length >= ROW_GUARD)
199
+ break;
200
+ }
201
+ return rows;
202
+ }
203
+ /** No rows, or the single cell of a count that came back 0. The function applies the same test. */
204
+ function isEmpty(rows) {
205
+ return rows.length === 0 || (rows.length === 1 && rows[0].length === 1 && (rows[0][0] === 0 || rows[0][0] === null));
206
+ }
207
+ /**
208
+ * Run the startup list on the open iModel. Never throws for a query: a failure is an empty
209
+ * result. Only a list that names a list it does not define throws.
210
+ */
211
+ async function runStartupQueries(list, runQuery) {
212
+ const results = [];
213
+ const reports = [];
214
+ const emptyByRule = new Map();
215
+ for (const query of list.queries) {
216
+ const empty = emptyByRule.get(query.rule) ?? new Set();
217
+ emptyByRule.set(query.rule, empty);
218
+ const ecsql = expandLists(query.ecsql, list.lists);
219
+ if (query.onlyIfEmpty && !query.onlyIfEmpty.every((id) => empty.has(id))) {
220
+ reports.push({ rule: query.rule, query: query.id, ecsql, ms: 0, rows: 0, skipped: true });
221
+ results.push({ rule: query.rule, id: query.id, rows: [], count: 0, skipped: true, ms: 0 });
222
+ continue;
223
+ }
224
+ const started = Date.now();
225
+ let rows = [];
226
+ let error;
227
+ try {
228
+ rows = await readRows(runQuery, ecsql);
229
+ }
230
+ catch (caught) {
231
+ error = caught.message;
232
+ }
233
+ const ms = Date.now() - started;
234
+ reports.push({ rule: query.rule, query: query.id, ecsql, ms, rows: rows.length, error });
235
+ const shown = rows.slice(0, query.max ?? 20);
236
+ const result = {
237
+ rule: query.rule, id: query.id, rows: shown, count: rows.length, ms,
238
+ ...(rows.length >= ROW_GUARD ? { guarded: true } : {}), ...(error !== undefined ? { error } : {}),
239
+ };
240
+ if (isEmpty(rows)) {
241
+ empty.add(query.id);
242
+ }
243
+ else if (query.each) {
244
+ const each = [];
245
+ for (const row of shown) {
246
+ const eachSql = fillIdentifiers(query.each, row);
247
+ if (!eachSql) {
248
+ each.push(null);
249
+ continue;
250
+ }
251
+ const eachStarted = Date.now();
252
+ try {
253
+ const found = await readRows(runQuery, eachSql);
254
+ each.push(String(found[0]?.[0] ?? 0));
255
+ reports.push({ rule: query.rule, query: `${query.id}/each`, ecsql: eachSql, ms: Date.now() - eachStarted, rows: found.length });
256
+ }
257
+ catch (caught) {
258
+ each.push(null);
259
+ reports.push({ rule: query.rule, query: `${query.id}/each`, ecsql: eachSql, ms: Date.now() - eachStarted, rows: 0, error: caught.message });
260
+ }
261
+ }
262
+ result.each = each;
263
+ }
264
+ results.push(result);
265
+ }
266
+ return { results, reports };
267
+ }
268
+ /** The earlier name of `fetchTurns`. */
269
+ exports.httpTurns = fetchTurns;
270
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAgEH,0CASC;AA6BD,gCAkCC;AAgCD,gCA6BC;AAMD,8BAQC;AA0CD,kCAaC;AAqCD,8CAqDC;AAlWD,uCAAyD;AAEzD,+CAGuB;AAqDvB;;;GAGG;AACI,KAAK,UAAU,eAAe,CAAC,QAAgB,EAAE,GAAa;IACnE,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,EAAE,KAAK,IAAI,GAAG,CAAC,KAAK,CAAC;IACjD,OAAO;QACL,QAAQ;QACR,MAAM,EAAE,GAAG,CAAC,MAAM;QAClB,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3B,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,W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AAC;gBAClI,CAAC;gBAAC,OAAO,MAAM,EAAE,CAAC;oBAChB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;oBAChB,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,KAAK,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,WAAW,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAG,MAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;gBACzJ,CAAC;YACH,CAAC;YACD,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC;QACrB,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC9B,CAAC;AAED,wCAAwC;AAC3B,QAAA,SAAS,GAAG,UAAU,CAAC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The query agent's client library: it runs the queries on the host's iModel, and drives the
3
+ * turns with the agent function (`docs/design.md`).
4
+ */
5
+ export * from "./turn-api.js";
6
+ export * from "./caps.js";
7
+ export * from "./client.js";
8
+ export * from "./query-runner.js";
9
+ export * from "./agent-client.js";
10
+ export * from "./selection.js";
11
+ export * from "./result-pages.js";
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ /**
3
+ * The query agent's client library: it runs the queries on the host's iModel, and drives the
4
+ * turns with the agent function (`docs/design.md`).
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
18
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ __exportStar(require("./turn-api.js"), exports);
22
+ __exportStar(require("./caps.js"), exports);
23
+ __exportStar(require("./client.js"), exports);
24
+ __exportStar(require("./query-runner.js"), exports);
25
+ __exportStar(require("./agent-client.js"), exports);
26
+ __exportStar(require("./selection.js"), exports);
27
+ __exportStar(require("./result-pages.js"), exports);
28
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;;;;;;;;;;;AAEH,gDAA8B;AAC9B,4CAA0B;AAC1B,8CAA4B;AAC5B,oDAAkC;AAClC,oDAAkC;AAClC,iDAA+B;AAC/B,oDAAkC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The client in Node, with the queries going to a backend by RPC, exactly as a browser's do. For
3
+ * tests and scripts that drive the agent the way the UI does, without a browser.
4
+ *
5
+ * iTwin.js's frontend needs a DOM to start, so a DOM shim (`global-jsdom`) is loaded first, as
6
+ * iTwin.js's own Node frontend tests do. Without it `NoRenderApp.startup` fails with "window is
7
+ * not defined", and a bare `window` object is not enough for the RPC requests (researched and
8
+ * tested 2026-10-28).
9
+ *
10
+ * ```ts
11
+ * await startNodeFrontend(backendUrl);
12
+ * const imodel = connectionFromProps(propsTheBackendGaveForTheOpenIModel);
13
+ * const client = AgentClient.start({ runQuery: queryRunner(imodel), imodelName, functionUrl });
14
+ * ```
15
+ */
16
+ import { type IModelConnectionProps, type RpcInterfaceDefinition } from "@itwin/core-common";
17
+ import { IModelConnection } from "@itwin/core-frontend";
18
+ /**
19
+ * Start iTwin.js's frontend in this process, talking to the backend at `backendUrl`
20
+ * (`BentleyCloudRpcManager`). Once per process; a second call with another URL throws.
21
+ */
22
+ export declare function startNodeFrontend(backendUrl: string, options?: {
23
+ title?: string;
24
+ version?: string;
25
+ interfaces?: RpcInterfaceDefinition[];
26
+ }): Promise<void>;
27
+ export declare function connectionFromProps(props: IModelConnectionProps): IModelConnection;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ /**
3
+ * The client in Node, with the queries going to a backend by RPC, exactly as a browser's do. For
4
+ * tests and scripts that drive the agent the way the UI does, without a browser.
5
+ *
6
+ * iTwin.js's frontend needs a DOM to start, so a DOM shim (`global-jsdom`) is loaded first, as
7
+ * iTwin.js's own Node frontend tests do. Without it `NoRenderApp.startup` fails with "window is
8
+ * not defined", and a bare `window` object is not enough for the RPC requests (researched and
9
+ * tested 2026-10-28).
10
+ *
11
+ * ```ts
12
+ * await startNodeFrontend(backendUrl);
13
+ * const imodel = connectionFromProps(propsTheBackendGaveForTheOpenIModel);
14
+ * const client = AgentClient.start({ runQuery: queryRunner(imodel), imodelName, functionUrl });
15
+ * ```
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.startNodeFrontend = startNodeFrontend;
19
+ exports.connectionFromProps = connectionFromProps;
20
+ const core_common_1 = require("@itwin/core-common");
21
+ const core_frontend_1 = require("@itwin/core-frontend");
22
+ let started;
23
+ /**
24
+ * Start iTwin.js's frontend in this process, talking to the backend at `backendUrl`
25
+ * (`BentleyCloudRpcManager`). Once per process; a second call with another URL throws.
26
+ */
27
+ async function startNodeFrontend(backendUrl, options = {}) {
28
+ if (started !== undefined) {
29
+ if (started !== backendUrl)
30
+ throw new Error(`The frontend is already started for ${started}.`);
31
+ return;
32
+ }
33
+ if (typeof globalThis.window === "undefined")
34
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
35
+ require("global-jsdom")();
36
+ core_common_1.BentleyCloudRpcManager.initializeClient({ info: { title: options.title ?? "imodulator", version: options.version ?? "v1.0" }, uriPrefix: backendUrl }, options.interfaces ?? [core_common_1.IModelReadRpcInterface]);
37
+ await core_frontend_1.NoRenderApp.startup({ applicationId: "query-agent-client" });
38
+ started = backendUrl;
39
+ }
40
+ /** An `IModelConnection` for an iModel the backend already has open, from the props it gave for it. */
41
+ class OpenConnection extends core_frontend_1.IModelConnection {
42
+ closed = false;
43
+ constructor(props) {
44
+ super(props);
45
+ }
46
+ get isClosed() {
47
+ return this.closed;
48
+ }
49
+ async close() {
50
+ if (this.closed)
51
+ return;
52
+ this.closed = true;
53
+ this.beforeClose();
54
+ }
55
+ }
56
+ function connectionFromProps(props) {
57
+ return new OpenConnection(props);
58
+ }
59
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/node/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAWH,8CAeC;AAsBD,kDAEC;AAhDD,oDAA6I;AAC7I,wDAAqE;AAErE,IAAI,OAA2B,CAAC;AAEhC;;;GAGG;AACI,KAAK,UAAU,iBAAiB,CAAC,UAAkB,EAAE,UAAuF,EAAE;IACnJ,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,IAAI,OAAO,KAAK,UAAU;YACxB,MAAM,IAAI,KAAK,CAAC,uCAAuC,OAAO,GAAG,CAAC,CAAC;QACrE,OAAO;IACT,CAAC;IACD,IAAI,OAAQ,UAAmC,CAAC,MAAM,KAAK,WAAW;QACpE,iEAAiE;QAChE,OAAO,CAAC,cAAc,CAAgB,EAAE,CAAC;IAC5C,oCAAsB,CAAC,gBAAgB,CACrC,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,YAAY,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,MAAM,EAAE,EAAE,SAAS,EAAE,UAAU,EAAE,EAC7G,OAAO,CAAC,UAAU,IAAI,CAAC,oCAAsB,CAAC,CAC/C,CAAC;IACF,MAAM,2BAAW,CAAC,OAAO,CAAC,EAAE,aAAa,EAAE,oBAAoB,EAAE,CAAC,CAAC;IACnE,OAAO,GAAG,UAAU,CAAC;AACvB,CAAC;AAED,uGAAuG;AACvG,MAAM,cAAe,SAAQ,gCAAgB;IACnC,MAAM,GAAG,KAAK,CAAC;IAEvB,YAAmB,KAA4B;QAC7C,KAAK,CAAC,KAAK,CAAC,CAAC;IACf,CAAC;IAED,IAAoB,QAAQ;QAC1B,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAEe,KAAK,CAAC,KAAK;QACzB,IAAI,IAAI,CAAC,MAAM;YACb,OAAO;QACT,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,IAAI,CAAC,WAAW,EAAE,CAAC;IACrB,CAAC;CACF;AAED,SAAgB,mBAAmB,CAAC,KAA4B;IAC9D,OAAO,IAAI,cAAc,CAAC,KAAK,CAAC,CAAC;AACnC,CAAC"}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Running ECSql on the host's iModel. Anything with `createQueryReader` will do: an
3
+ * `IModelConnection` in a browser (the queries go to the backend by RPC), or an `IModelDb` in
4
+ * Node. They are typed here by what is used, so this package depends on neither.
5
+ */
6
+ import type { QueryPageOptions, RunRawQuery } from "./caps.js";
7
+ /** The part of iTwin.js's `ECSqlReader` that the runner uses. */
8
+ export interface QueryReader {
9
+ getMetaData(): Promise<{
10
+ name: string;
11
+ }[]>;
12
+ step(): Promise<boolean>;
13
+ readonly current: {
14
+ toArray(): unknown[];
15
+ };
16
+ }
17
+ /** An `IModelConnection` or an `IModelDb`. */
18
+ export interface QuerySource {
19
+ createQueryReader(ecsql: string, params?: undefined, options?: {
20
+ abbreviateBlobs?: boolean;
21
+ } & QueryPageOptions): QueryReader;
22
+ }
23
+ /**
24
+ * The query function the client runs the agent's queries with.
25
+ *
26
+ * - **Blobs are abbreviated.** One `GeometryStream` serialises to thousands of values, so one
27
+ * row could cost more than the whole budget, and the row cap cannot catch it.
28
+ * - **A bad query throws before the first row**, when the reader reads its metadata, so the
29
+ * driver sends the error for the model to correct.
30
+ * - **Short rows are padded with nulls.** `toArray()` drops trailing nulls, and a model reading
31
+ * `["Synchronization"]` under three columns guesses at the missing values.
32
+ * - **A page is the reader's own** (`QueryPageOptions`): its `limit` and `restartToken` options.
33
+ */
34
+ export declare function queryRunner(source: QuerySource): RunRawQuery;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ /**
3
+ * Running ECSql on the host's iModel. Anything with `createQueryReader` will do: an
4
+ * `IModelConnection` in a browser (the queries go to the backend by RPC), or an `IModelDb` in
5
+ * Node. They are typed here by what is used, so this package depends on neither.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.queryRunner = queryRunner;
9
+ /**
10
+ * The query function the client runs the agent's queries with.
11
+ *
12
+ * - **Blobs are abbreviated.** One `GeometryStream` serialises to thousands of values, so one
13
+ * row could cost more than the whole budget, and the row cap cannot catch it.
14
+ * - **A bad query throws before the first row**, when the reader reads its metadata, so the
15
+ * driver sends the error for the model to correct.
16
+ * - **Short rows are padded with nulls.** `toArray()` drops trailing nulls, and a model reading
17
+ * `["Synchronization"]` under three columns guesses at the missing values.
18
+ * - **A page is the reader's own** (`QueryPageOptions`): its `limit` and `restartToken` options.
19
+ */
20
+ function queryRunner(source) {
21
+ return async (ecsql, page) => {
22
+ const reader = source.createQueryReader(ecsql, undefined, {
23
+ abbreviateBlobs: true,
24
+ ...(page?.limit ? { limit: page.limit } : {}),
25
+ ...(page?.restartToken ? { restartToken: page.restartToken } : {}),
26
+ });
27
+ const columns = (await reader.getMetaData()).map((column) => column.name);
28
+ return {
29
+ columns,
30
+ rows: (async function* () {
31
+ while (await reader.step()) {
32
+ const row = reader.current.toArray();
33
+ while (row.length < columns.length)
34
+ row.push(null);
35
+ yield row;
36
+ }
37
+ })(),
38
+ };
39
+ };
40
+ }
41
+ //# sourceMappingURL=query-runner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-runner.js","sourceRoot":"","sources":["../../src/query-runner.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AA2BH,kCAoBC;AA/BD;;;;;;;;;;GAUG;AACH,SAAgB,WAAW,CAAC,MAAmB;IAC7C,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;QAC3B,MAAM,MAAM,GAAG,MAAM,CAAC,iBAAiB,CAAC,KAAK,EAAE,SAAS,EAAE;YACxD,eAAe,EAAE,IAAI;YACrB,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC7C,GAAG,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,IAAI,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACnE,CAAC,CAAC;QACH,MAAM,OAAO,GAAG,CAAC,MAAM,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC1E,OAAO;YACL,OAAO;YACP,IAAI,EAAE,CAAC,KAAK,SAAS,CAAC;gBACpB,OAAO,MAAM,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;oBAC3B,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;oBACrC,OAAO,GAAG,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM;wBAChC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;oBACjB,MAAM,GAAG,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC,EAAE;SACL,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,69 @@
1
+ /**
2
+ * An answer's results with no row limit, read a page at a time for a virtualized table.
3
+ *
4
+ * Each page is its own read through the iTwin.js query reader, with the reader's `limit` option
5
+ * (`QueryPageOptions`), which is how the reader pages internally too: every page it reads is a
6
+ * request with an offset and a count. Nothing here rewrites the query. The total is read once,
7
+ * with `SELECT COUNT(*)` over the query, as the iTwin.js tests count a paged result; until it is
8
+ * known, or when the query cannot be counted that way, the rows read so far are the lower bound.
9
+ *
10
+ * Pages are read one at a time, for the rows the table last asked for: a fast scroll does not queue
11
+ * up every page it passed. Read pages are kept, so scrolling back costs nothing.
12
+ */
13
+ import type { RunRawQuery } from "./caps.js";
14
+ /** How many rows one page reads. */
15
+ export declare const RESULT_PAGE_ROWS = 1000;
16
+ /** Rows already read, which the results start from: the answer's rows as the client first read them. */
17
+ export interface FirstRows {
18
+ columns: string[];
19
+ rows: unknown[][];
20
+ /** The first rows are all the rows. */
21
+ complete: boolean;
22
+ }
23
+ export declare class ResultPages {
24
+ private readonly runQuery;
25
+ readonly ecsql: string;
26
+ readonly pageRows: number;
27
+ private readonly pages;
28
+ private readonly listeners;
29
+ private _columns;
30
+ private _count;
31
+ private _error;
32
+ /** The highest row index known to exist, plus one: the lower bound while the count is unknown. */
33
+ private _known;
34
+ private wanted;
35
+ private loading;
36
+ private counting;
37
+ constructor(runQuery: RunRawQuery, ecsql: string, first?: FirstRows, pageRows?: number);
38
+ /** What a run carrying this says of it when written out as JSON: the query and the count, not the rows. */
39
+ toJSON(): {
40
+ ecsql: string;
41
+ count?: number;
42
+ };
43
+ /** The column names, once the first page (or the first rows) has been read. */
44
+ get columns(): string[] | undefined;
45
+ /** The number of rows, when known. */
46
+ get count(): number | undefined;
47
+ /** How many rows there are at least: the count when known, else the rows found so far. */
48
+ get atLeast(): number;
49
+ /** The error the query gave, if a page failed. */
50
+ get error(): string | undefined;
51
+ /** A row, if its page has been read. */
52
+ row(index: number): unknown[] | undefined;
53
+ /** Called whenever a page, the count or an error arrives. Returns a function that stops it. */
54
+ subscribe(listener: () => void): () => void;
55
+ /**
56
+ * Ask for the rows from `start` up to `end`: their pages are read, one at a time, unless a later
57
+ * call asks for other rows first. The count is read alongside the first call.
58
+ */
59
+ want(start: number, end: number): void;
60
+ /** Read every page up to `end` rows (all of them when undefined): for a host or a test. */
61
+ loadUpTo(end?: number): Promise<void>;
62
+ private notify;
63
+ private readCount;
64
+ /** The next page the wanted rows need that has not been read, or undefined. */
65
+ private nextWantedPage;
66
+ private loadWanted;
67
+ /** Read one page (or return it, read before); undefined when the query failed. */
68
+ private readPage;
69
+ }