fnloom 0.1.0 → 0.2.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.
- package/README.md +31 -18
- package/package.json +2 -7
- package/packages/build/package.json +1 -1
- package/packages/cli/package.json +1 -1
- package/packages/cli/src/commands/available.ts +63 -22
- package/packages/cli/src/commands/install.ts +86 -28
- package/packages/cli/src/index.ts +3 -2
- package/packages/cli/src/local.ts +6 -0
- package/packages/cli/src/premade.ts +80 -0
- package/packages/core/package.json +1 -1
- package/packages/hub/package.json +1 -1
- package/packages/hub/src/link/process.ts +6 -1
- package/packages/sdk/package.json +1 -1
- package/packages/web/package.json +1 -1
- package/premade/claude.zip +0 -0
- package/premade/database.zip +0 -0
- package/premade/web.zip +0 -0
- package/scripts/dev-env.ts +4 -4
- package/scripts/stack.ts +42 -27
- package/scripts/start.ts +26 -16
- package/systems/api/package.json +1 -1
- package/systems/code/package.json +1 -1
- package/systems/embedder/package.json +1 -1
- package/systems/fs/package.json +1 -1
- package/systems/google-calendar/package.json +1 -1
- package/systems/input/package.json +1 -1
- package/systems/mcp/package.json +1 -1
- package/systems/ollama/package.json +1 -1
- package/systems/schedule/package.json +1 -1
- package/systems/template/package.json +1 -1
- package/systems/widgets/package.json +1 -1
- package/systems/claude/client/FleetPage.vue +0 -132
- package/systems/claude/client/NewSessionForm.vue +0 -62
- package/systems/claude/client/SessionList.vue +0 -64
- package/systems/claude/client/SessionPage.vue +0 -199
- package/systems/claude/client/TaskList.vue +0 -61
- package/systems/claude/client/fakes.ts +0 -186
- package/systems/claude/client/host.ts +0 -23
- package/systems/claude/client/index.ts +0 -15
- package/systems/claude/client/logic.ts +0 -270
- package/systems/claude/client/state.ts +0 -344
- package/systems/claude/package.json +0 -23
- package/systems/claude/server/agent-sdk.ts +0 -379
- package/systems/claude/server/driver.ts +0 -153
- package/systems/claude/server/env.ts +0 -64
- package/systems/claude/server/fake-driver.ts +0 -112
- package/systems/claude/server/fleet.ts +0 -376
- package/systems/claude/server/impl.ts +0 -568
- package/systems/claude/server/index.ts +0 -8
- package/systems/claude/server/main.ts +0 -38
- package/systems/claude/server/preview.ts +0 -76
- package/systems/claude/server/questions.ts +0 -117
- package/systems/claude/server/transcript.ts +0 -83
- package/systems/claude/shared/index.ts +0 -262
- package/systems/claude/shared/session.ts +0 -284
- package/systems/claude/shared/shapes.ts +0 -106
- package/systems/claude/system.json +0 -18
- package/systems/claude/tsconfig.json +0 -6
- package/systems/database/package.json +0 -25
- package/systems/database/server/author.ts +0 -41
- package/systems/database/server/authoring.ts +0 -322
- package/systems/database/server/catalog.ts +0 -117
- package/systems/database/server/compile.ts +0 -332
- package/systems/database/server/dialects.ts +0 -17
- package/systems/database/server/drivers/database.ts +0 -71
- package/systems/database/server/drivers/index.ts +0 -23
- package/systems/database/server/drivers/postgres.ts +0 -157
- package/systems/database/server/drivers/sqlite.ts +0 -151
- package/systems/database/server/drivers/sqlserver.ts +0 -176
- package/systems/database/server/env.ts +0 -35
- package/systems/database/server/fixture.ts +0 -169
- package/systems/database/server/impl.ts +0 -793
- package/systems/database/server/index.ts +0 -7
- package/systems/database/server/instance.ts +0 -398
- package/systems/database/server/main.ts +0 -47
- package/systems/database/server/pick.ts +0 -97
- package/systems/database/server/queries.ts +0 -390
- package/systems/database/server/results.ts +0 -39
- package/systems/database/server/schema.ts +0 -59
- package/systems/database/server/table-fns.ts +0 -237
- package/systems/database/server/types.ts +0 -253
- package/systems/database/shared/index.ts +0 -544
- package/systems/database/shared/shapes.ts +0 -413
- package/systems/database/system.json +0 -14
- package/systems/database/tsconfig.json +0 -6
- package/systems/web/client/ReadView.vue +0 -110
- package/systems/web/client/SearchView.vue +0 -215
- package/systems/web/client/StatusChip.vue +0 -38
- package/systems/web/client/fakes.ts +0 -48
- package/systems/web/client/index.ts +0 -15
- package/systems/web/client/view.ts +0 -131
- package/systems/web/package.json +0 -22
- package/systems/web/server/chrome.ts +0 -121
- package/systems/web/server/crawl.ts +0 -333
- package/systems/web/server/env.ts +0 -63
- package/systems/web/server/guard.ts +0 -60
- package/systems/web/server/http.ts +0 -89
- package/systems/web/server/impl.ts +0 -203
- package/systems/web/server/index.ts +0 -71
- package/systems/web/server/loader.ts +0 -104
- package/systems/web/server/main.ts +0 -70
- package/systems/web/server/mentions.ts +0 -111
- package/systems/web/server/problem.ts +0 -72
- package/systems/web/server/renderer.ts +0 -243
- package/systems/web/server/robots.ts +0 -75
- package/systems/web/server/searches.ts +0 -29
- package/systems/web/server/tavily.ts +0 -144
- package/systems/web/server/testing.ts +0 -165
- package/systems/web/server/uploads.ts +0 -33
- package/systems/web/shared/index.ts +0 -343
- package/systems/web/shared/urls.ts +0 -60
- package/systems/web/system.json +0 -15
- package/systems/web/tsconfig.json +0 -6
|
@@ -1,237 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Generated fns for a table (`table_fns_available`, `table_fns_generate`). `@aeye/query`'s `tableFns` lists every fn a
|
|
3
|
-
* table's columns, keys and relations make possible (CRUD, column helpers, relation-derived fields and normalized
|
|
4
|
-
* comparisons), each a checked query with its args and signature; no model is involved, so the same tables always give
|
|
5
|
-
* the same fns. Here they are checked against this instance's tables, marked with how they stand in the hub (new,
|
|
6
|
-
* current, or made for an older schema), and kept as `database/query` fns of the instance (`hub/fns_save`), named
|
|
7
|
-
* `<instance>.<table>_<name>`, with instructions and examples. Saving is idempotent by name: an unchanged fn is left
|
|
8
|
-
* alone, a changed one becomes a new version (the hub keeps the old). A generated fn's payload records the op it was
|
|
9
|
-
* built from and the table's schema hash, so its query is rebuilt from the tables as they are now (`refreshPayload`).
|
|
10
|
-
*/
|
|
11
|
-
import { TableFnError, tableFnQuery, tableFns, tableSchemaHash, type TableFn, type TableFnOp, type TableFnOptions, type TableSpec } from '@aeye/query';
|
|
12
|
-
import { Json, qualify, type FnExample } from '@harness/core';
|
|
13
|
-
import { canonicalJson, sampleArgs } from '@harness/sdk';
|
|
14
|
-
import { QUERY_KIND, database } from '../shared/index.ts';
|
|
15
|
-
import { QueryPayload, type GeneratedTableFn, type TableFnEntry, type TableFnGroup, type TableFnOpValue, type TableFnState, type TableFnsList } from '../shared/shapes.ts';
|
|
16
|
-
import { argsTypeOf, signatureOf } from './compile.ts';
|
|
17
|
-
import type { DatabaseInstance } from './instance.ts';
|
|
18
|
-
import type { QueryProblem, QueryRunCtx } from './queries.ts';
|
|
19
|
-
import { identifierOf, qualifiedTypeOf, tableRefOf } from './types.ts';
|
|
20
|
-
|
|
21
|
-
/** The tag every generated fn carries, beside `database`, `query` and its table. */
|
|
22
|
-
export const GENERATED_TAG = 'generated';
|
|
23
|
-
|
|
24
|
-
/** What listing needs from the run: the hub's saved queries as its person, and which of some names exist. */
|
|
25
|
-
export interface TableFnsReadCtx extends Pick<QueryRunCtx, 'getFn' | 'log'> {
|
|
26
|
-
/** Which of these qualified fn names exist as saved queries (`hub/fns_search` by names). */
|
|
27
|
-
existing(names: readonly string[]): Promise<Set<string>>;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/** What generating needs from the run: what listing needs, and saving fns in the hub as its person. */
|
|
31
|
-
export interface TableFnsCtx extends TableFnsReadCtx, Pick<QueryRunCtx, 'saveFn'> {}
|
|
32
|
-
|
|
33
|
-
/** The generators' tunables (`DATABASE_TABLE_FNS_DEPTH`, `DATABASE_TABLE_FNS_CAP`) and the paging every list uses. */
|
|
34
|
-
export interface TableFnLimits {
|
|
35
|
-
readonly depth: number;
|
|
36
|
-
readonly cap: number;
|
|
37
|
-
readonly page: number;
|
|
38
|
-
readonly max: number;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** The hub's local name of a table's generated fn: `<instance>.<table>_<name>` (`main.projects_selectPage`). */
|
|
42
|
-
export function generatedLocal(instance: string, table: string, name: string): string {
|
|
43
|
-
return `${instance}.${identifierOf(table)}_${name}`;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** A stored op as `@aeye/query` takes it (its absent parts left out, not undefined). */
|
|
47
|
-
export function toTableFnOp(op: TableFnOpValue): TableFnOp {
|
|
48
|
-
return {
|
|
49
|
-
kind: op.kind,
|
|
50
|
-
table: op.table,
|
|
51
|
-
...(op.column === undefined ? {} : { column: op.column }),
|
|
52
|
-
...(op.child === undefined ? {} : { child: op.child }),
|
|
53
|
-
...(op.bucket === undefined ? {} : { bucket: op.bucket }),
|
|
54
|
-
...(op.derived === undefined ? {} : { derived: op.derived }),
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/** A generated fn's examples: its required args with sample values, and for a list, the next page. */
|
|
59
|
-
function examplesOf(fn: TableFn): FnExample[] {
|
|
60
|
-
const base = sampleArgs(fn.args);
|
|
61
|
-
const first: FnExample = { args: base, note: Object.keys(base).length === 0 ? 'Every arg may be left out.' : 'Sample values: use real ones.' };
|
|
62
|
-
return fn.list ? [first, { args: { ...base, limit: 20, offset: 20 }, note: 'The second page of 20.' }] : [first];
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/** A generated fn's instructions: what it does, how to call it, and what a write waits for. */
|
|
66
|
-
function instructionsOf(fn: TableFn, label: string): string {
|
|
67
|
-
const optional = fn.optional.length === 0 ? '' : ` Leave out ${fn.optional.join(', ')} for no filter (or, in a change, to keep the value).`;
|
|
68
|
-
const writes = fn.mode === 'read'
|
|
69
|
-
? (fn.list ? ' Page with limit and offset; you get the columns, counts and first rows, and a person watching the chat is shown the rows too.' : ' You get the columns and rows it reads.')
|
|
70
|
-
: ` It ${fn.mode === 'delete' ? 'deletes' : 'changes'} rows: every run waits for the person to approve it.`;
|
|
71
|
-
return `${fn.about} Generated from the ${fn.table} table of the ${label} database; call it as ${fn.signature}.${optional}${writes}`;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/** The payload a generated fn is kept with. */
|
|
75
|
-
function payloadOf(instance: string, fn: TableFn, hash: string): QueryPayload {
|
|
76
|
-
return QueryPayload.parse({
|
|
77
|
-
instance,
|
|
78
|
-
description: fn.about,
|
|
79
|
-
query: Json.parse(fn.query),
|
|
80
|
-
sorters: [...fn.sorters],
|
|
81
|
-
list: fn.list,
|
|
82
|
-
...(fn.optional.length === 0 ? {} : { optional: [...fn.optional] }),
|
|
83
|
-
generated: { op: Json.parse(fn.op), hash },
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/** One instance's generated table fns. */
|
|
88
|
-
export class TableFnService {
|
|
89
|
-
readonly #limits: TableFnLimits;
|
|
90
|
-
|
|
91
|
-
constructor(limits: TableFnLimits) {
|
|
92
|
-
this.#limits = limits;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/** `table_fns_available`: the table's fns by group, marked as they stand in the hub, capped. */
|
|
96
|
-
async list(instance: DatabaseInstance, table: string, ctx: TableFnsReadCtx): Promise<TableFnsList | QueryProblem> {
|
|
97
|
-
const found = this.#table(instance, table);
|
|
98
|
-
if ('invalid' in found) { return found; }
|
|
99
|
-
const listed = tableFns(found.spec.name, found.specs, this.#options(this.#limits.cap));
|
|
100
|
-
const usable = listed.fns.filter((fn) => this.#runs(instance, fn));
|
|
101
|
-
const states = await this.#states(instance, usable, listed.hash, ctx);
|
|
102
|
-
const groups: TableFnGroup[] = [];
|
|
103
|
-
for (const fn of usable) {
|
|
104
|
-
const entry: TableFnEntry = {
|
|
105
|
-
name: fn.name, fn: qualify(database.name, generatedLocal(instance.instance, fn.table, fn.name)), about: fn.about,
|
|
106
|
-
signature: fn.signature, mode: fn.mode, ...(states.get(fn.name) ?? { state: 'new' }),
|
|
107
|
-
};
|
|
108
|
-
const group = groups.find((known) => known.group === fn.group);
|
|
109
|
-
if (group === undefined) { groups.push({ group: fn.group, fns: [entry] }); } else { group.fns.push(entry); }
|
|
110
|
-
}
|
|
111
|
-
return {
|
|
112
|
-
database: instance.info, table: found.spec.name, type: qualifiedTypeOf(instance.instance, found.spec.name), hash: listed.hash, groups,
|
|
113
|
-
more: listed.more + (listed.fns.length - usable.length),
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/** `table_fns_generate`: make or bring up to date the named fns; unchanged ones are left as they are. */
|
|
118
|
-
async generate(instance: DatabaseInstance, table: string, names: readonly string[], derived: readonly string[], ctx: TableFnsCtx): Promise<GeneratedTableFn[] | QueryProblem> {
|
|
119
|
-
const found = this.#table(instance, table);
|
|
120
|
-
if ('invalid' in found) { return found; }
|
|
121
|
-
const all = tableFns(found.spec.name, found.specs, this.#options(Number.MAX_SAFE_INTEGER));
|
|
122
|
-
const unknown = names.filter((name) => !all.fns.some((fn) => fn.name === name));
|
|
123
|
-
if (unknown.length > 0) { return { invalid: `${found.spec.name} has no generated fn ${unknown.join(', ')}: use the names table_fns_available lists.` }; }
|
|
124
|
-
const made: TableFn[] = [];
|
|
125
|
-
for (const name of new Set(names)) {
|
|
126
|
-
const listed = all.fns.find((fn) => fn.name === name);
|
|
127
|
-
if (listed === undefined) { continue; }
|
|
128
|
-
let fn = listed;
|
|
129
|
-
if (fn.kind === 'selectPage' && derived.length > 0) {
|
|
130
|
-
try {
|
|
131
|
-
fn = tableFnQuery({ ...fn.op, derived }, found.specs, this.#options(Number.MAX_SAFE_INTEGER));
|
|
132
|
-
} catch (error) {
|
|
133
|
-
if (error instanceof TableFnError) { return { invalid: error.message }; }
|
|
134
|
-
throw error;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
const why = this.#whyNot(instance, fn);
|
|
138
|
-
if (why !== undefined) { return { invalid: why }; }
|
|
139
|
-
made.push(fn);
|
|
140
|
-
}
|
|
141
|
-
const local = (fn: TableFn) => generatedLocal(instance.instance, fn.table, fn.name);
|
|
142
|
-
const existing = await ctx.existing(made.map((fn) => qualify(database.name, local(fn))));
|
|
143
|
-
const out: GeneratedTableFn[] = [];
|
|
144
|
-
for (const fn of made) {
|
|
145
|
-
const name = qualify(database.name, local(fn));
|
|
146
|
-
const payload = payloadOf(instance.instance, fn, all.hash);
|
|
147
|
-
const compiled = instance.compile(payload);
|
|
148
|
-
if (!('query' in compiled)) { return { failed: `${name} was generated but doesn't check: ${compiled.problems.join(' ')}` }; }
|
|
149
|
-
const signature = signatureOf(name, argsTypeOf(compiled, payload.sorters, this.#limits, payload.optional));
|
|
150
|
-
if (existing.has(name)) {
|
|
151
|
-
const stored = await ctx.getFn(name);
|
|
152
|
-
if (stored.payload !== undefined && canonicalJson(stored.payload) === canonicalJson(Json.parse(payload))) {
|
|
153
|
-
out.push({ fn: name, signature, version: stored.version, status: 'unchanged' });
|
|
154
|
-
continue;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
const saved = await ctx.saveFn({
|
|
158
|
-
kind: QUERY_KIND, name: local(fn), payload: Json.parse(payload),
|
|
159
|
-
description: fn.mode === 'read' ? fn.about : `${fn.about} (Writes: waits for approval.)`,
|
|
160
|
-
instructions: instructionsOf(fn, instance.config.label),
|
|
161
|
-
examples: examplesOf(fn),
|
|
162
|
-
tags: ['database', 'query', GENERATED_TAG, identifierOf(fn.table), ...(fn.mode === 'read' ? [] : ['write'])],
|
|
163
|
-
share: instance.config.audience,
|
|
164
|
-
routing: { to: 'instance', instance: instance.instance },
|
|
165
|
-
...(existing.has(name) ? { replace: true } : {}),
|
|
166
|
-
});
|
|
167
|
-
ctx.log.info('database.generated', { fn: saved.fn, version: saved.version });
|
|
168
|
-
out.push({ fn: saved.fn, signature, version: saved.version, status: saved.created ? 'created' : 'updated' });
|
|
169
|
-
}
|
|
170
|
-
return out;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* A saved query's payload as it runs now: a generated one is rebuilt from its op over the tables as they are, so a
|
|
175
|
-
* schema change reaches it at once (its stored version is brought up to date by `table_fns_generate`). Any other
|
|
176
|
-
* payload, or one whose table or columns are gone, is returned as it is, and its compile says what no longer fits.
|
|
177
|
-
*/
|
|
178
|
-
refreshPayload(instance: DatabaseInstance, payload: QueryPayload): QueryPayload {
|
|
179
|
-
if (payload.generated === undefined) { return payload; }
|
|
180
|
-
const specs = instance.catalog.tables.map((table) => table.scanned.spec);
|
|
181
|
-
try {
|
|
182
|
-
const fn = tableFnQuery(toTableFnOp(payload.generated.op), specs, this.#options(Number.MAX_SAFE_INTEGER));
|
|
183
|
-
return { ...payloadOf(instance.instance, fn, tableSchemaHash(fn.table, specs)), description: payload.description };
|
|
184
|
-
} catch (error) {
|
|
185
|
-
if (error instanceof TableFnError) { return payload; }
|
|
186
|
-
throw error;
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
#options(cap: number): TableFnOptions {
|
|
191
|
-
return { depth: this.#limits.depth, cap, paging: { page: this.#limits.page, max: this.#limits.max } };
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/** The table asked for (by name, local type name or qualified type), and every table's spec. */
|
|
195
|
-
#table(instance: DatabaseInstance, table: string): { spec: TableSpec; specs: TableSpec[] } | { invalid: string } {
|
|
196
|
-
const spec = instance.catalog.spec(tableRefOf(table).table);
|
|
197
|
-
if (spec === undefined) {
|
|
198
|
-
const names = instance.catalog.tables.map((known) => known.scanned.spec.name);
|
|
199
|
-
const listed = names.length === 0 ? 'it has no tables yet' : `its tables are ${names.join(', ')}`;
|
|
200
|
-
return { invalid: `There is no table ${table} in the ${instance.config.label} database: ${listed}. Give \`table\` as one of those names.` };
|
|
201
|
-
}
|
|
202
|
-
return { spec, specs: instance.catalog.tables.map((known) => known.scanned.spec) };
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
/** Whether a generated fn checks against this instance's tables, and may run here (a write only where writes are allowed). */
|
|
206
|
-
#runs(instance: DatabaseInstance, fn: TableFn): boolean {
|
|
207
|
-
return this.#whyNot(instance, fn) === undefined;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
/**
|
|
211
|
-
* Why a generated fn can't be made here, in words the model can act on: it writes rows where rows can only be read
|
|
212
|
-
* (whatever schema changes are allowed), or it doesn't check against the tables as they are; undefined when it can.
|
|
213
|
-
*/
|
|
214
|
-
#whyNot(instance: DatabaseInstance, fn: TableFn): string | undefined {
|
|
215
|
-
if (fn.mode !== 'read' && !instance.writes) {
|
|
216
|
-
const schema = instance.schemaChanges ? '; tables can still be made and changed there, but rows can\'t be added to them' : '';
|
|
217
|
-
return `${fn.name} writes rows, and rows of the ${instance.config.label} database can only be read (an admin can allow row writes on the system's page)${schema}.`;
|
|
218
|
-
}
|
|
219
|
-
const compiled = instance.compile(payloadOf(instance.instance, fn, 'unchecked'));
|
|
220
|
-
return 'query' in compiled ? undefined : `${fn.name} doesn't fit the ${fn.table} table as it is now: ${compiled.problems.join(' ')}`;
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/** How each listed fn stands in the hub: absent (new), made for this schema (current), or for an older one (stale). */
|
|
224
|
-
async #states(instance: DatabaseInstance, fns: readonly TableFn[], hash: string, ctx: TableFnsReadCtx): Promise<Map<string, { state: TableFnState; version?: number }>> {
|
|
225
|
-
const byName = new Map<string, string>(fns.map((fn) => [qualify(database.name, generatedLocal(instance.instance, fn.table, fn.name)), fn.name]));
|
|
226
|
-
const existing = await ctx.existing([...byName.keys()]);
|
|
227
|
-
const states = new Map<string, { state: TableFnState; version?: number }>();
|
|
228
|
-
for (const name of existing) {
|
|
229
|
-
const stored = await ctx.getFn(name);
|
|
230
|
-
const payload = QueryPayload.safeParse(stored.payload);
|
|
231
|
-
const local = byName.get(name);
|
|
232
|
-
if (local === undefined) { continue; }
|
|
233
|
-
states.set(local, { state: payload.success && payload.data.generated?.hash === hash ? 'current' : 'stale', version: stored.version });
|
|
234
|
-
}
|
|
235
|
-
return states;
|
|
236
|
-
}
|
|
237
|
-
}
|
|
@@ -1,253 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tables as types, both ways the system needs them:
|
|
3
|
-
*
|
|
4
|
-
* - **The hub's type** (`<instance>.<table>`): `@aeye/query`'s `tableToGinType` (columns, nullability, defaults,
|
|
5
|
-
* keys, foreign keys in the docs), refined by the table's enrichment when there is one (choices, formats, ranges,
|
|
6
|
-
* descriptions, examples).
|
|
7
|
-
* - **The query engine's type**: an `@aeye/query` `TypeDef` per table, with each single-column foreign key as a
|
|
8
|
-
* `relation` field the model can join over (its physical key in the backing), and the enrichment's descriptions.
|
|
9
|
-
*/
|
|
10
|
-
import type { PropDef, TypeDef as GinDef } from '@aeye/gin';
|
|
11
|
-
import { Value, tableToGinType, type ColumnSpec, type ColumnType, type FieldDef, type FieldTypeDef, type TableSpec, type TypeBacking, type TypeDef } from '@aeye/query';
|
|
12
|
-
import { GinTypeDef, slashedName, type QualifiedName } from '@harness/core';
|
|
13
|
-
import { z } from 'zod';
|
|
14
|
-
import type { ScannedTable } from './schema.ts';
|
|
15
|
-
|
|
16
|
-
// ─── Enrichment ──────────────────────────────────────────────────────────────
|
|
17
|
-
|
|
18
|
-
/** Formats enrichment may give a text column. */
|
|
19
|
-
export const TextFormat = z.enum(['email', 'url', 'uuid', 'phone', 'iso-date', 'country-code', 'currency-code']);
|
|
20
|
-
export type TextFormat = z.infer<typeof TextFormat>;
|
|
21
|
-
|
|
22
|
-
/** The pattern each format becomes. */
|
|
23
|
-
export const FORMAT_PATTERNS: Readonly<Record<TextFormat, string>> = {
|
|
24
|
-
email: '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$',
|
|
25
|
-
url: '^https?://\\S+$',
|
|
26
|
-
uuid: '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$',
|
|
27
|
-
phone: '^\\+?[0-9 ().-]{6,}$',
|
|
28
|
-
'iso-date': '^\\d{4}-\\d{2}-\\d{2}$',
|
|
29
|
-
'country-code': '^[A-Z]{2}$',
|
|
30
|
-
'currency-code': '^[A-Z]{3}$',
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
/** What a model adds to one column. */
|
|
34
|
-
export const ColumnEnrichment = z.object({
|
|
35
|
-
description: z.string().min(1).optional().describe('What the column holds.'),
|
|
36
|
-
/** The closed set of values the column holds (a status, a category), when it clearly has one. */
|
|
37
|
-
values: z.array(z.union([z.string(), z.number()])).min(1).max(40).optional()
|
|
38
|
-
.describe('The closed set of values, only when the column clearly holds one: a status, a type, a category.'),
|
|
39
|
-
format: TextFormat.optional().describe('The format of a text column, when every value has it.'),
|
|
40
|
-
min: z.number().optional().describe('The smallest value, only for a clear bound like a percentage or a rating.'),
|
|
41
|
-
max: z.number().optional().describe('The largest value, only for a clear bound like a percentage or a rating.'),
|
|
42
|
-
examples: z.array(z.string()).max(5).optional().describe('Up to 3 typical values, as text.'),
|
|
43
|
-
});
|
|
44
|
-
export type ColumnEnrichment = z.infer<typeof ColumnEnrichment>;
|
|
45
|
-
|
|
46
|
-
/** What a model adds to one table's type. */
|
|
47
|
-
export const TableEnrichment = z.object({
|
|
48
|
-
description: z.string().min(1).describe('One sentence on what a row is.'),
|
|
49
|
-
columns: z.record(z.string(), ColumnEnrichment),
|
|
50
|
-
});
|
|
51
|
-
export type TableEnrichment = z.infer<typeof TableEnrichment>;
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* The enricher's answer: `TableEnrichment` with its columns as a list, each naming its column, since a structured
|
|
55
|
-
* answer can't have keys of the model's choosing (`enrichmentOf` turns it back into the kept shape).
|
|
56
|
-
*/
|
|
57
|
-
export const EnrichmentAnswer = TableEnrichment.extend({
|
|
58
|
-
columns: z.array(ColumnEnrichment.extend({ column: z.string().min(1).describe('The column\'s name, exactly as given.') }))
|
|
59
|
-
.describe('Only the columns there is something sure to say about.'),
|
|
60
|
-
});
|
|
61
|
-
export type EnrichmentAnswer = z.infer<typeof EnrichmentAnswer>;
|
|
62
|
-
|
|
63
|
-
/** An answer as the enrichment kept with the type, keeping only columns the table has. */
|
|
64
|
-
export function enrichmentOf(answer: EnrichmentAnswer, columns: ReadonlySet<string>): TableEnrichment {
|
|
65
|
-
const kept = answer.columns.filter((entry) => columns.has(entry.column)).map(({ column, ...rest }) => [column, rest] as const);
|
|
66
|
-
return { description: answer.description, columns: Object.fromEntries(kept) };
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* What the system keeps with each table type in the hub (`TypeDecl.meta`, read back through `ctx.types`): the schema
|
|
71
|
-
* hash of the table the type was made from, and its enrichment when a model made one. So a model refines a table once
|
|
72
|
-
* per schema, and the system keeps no store of its own.
|
|
73
|
-
*/
|
|
74
|
-
export const TableMeta = z.object({
|
|
75
|
-
schemaHash: z.string().min(1),
|
|
76
|
-
enrichment: TableEnrichment.optional(),
|
|
77
|
-
});
|
|
78
|
-
export type TableMeta = z.infer<typeof TableMeta>;
|
|
79
|
-
|
|
80
|
-
/** A table type as the hub keeps it: its definition and the meta it was sent with (absent on a type sent before meta). */
|
|
81
|
-
export interface KeptType {
|
|
82
|
-
readonly def: GinTypeDef;
|
|
83
|
-
readonly meta: TableMeta | undefined;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** The meta the hub returned with a type, when it is a table type's meta. */
|
|
87
|
-
export function tableMetaOf(meta: unknown): TableMeta | undefined {
|
|
88
|
-
const parsed = TableMeta.safeParse(meta);
|
|
89
|
-
return parsed.success ? parsed.data : undefined;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
// ─── Names ───────────────────────────────────────────────────────────────────
|
|
93
|
-
|
|
94
|
-
/** A table or column name as an identifier the type systems accept (`order items` becomes `order_items`). */
|
|
95
|
-
export function identifierOf(name: string): string {
|
|
96
|
-
const id = name.replace(/[^A-Za-z0-9_]/g, '_');
|
|
97
|
-
return /^[A-Za-z_]/.test(id) ? id : `_${id}`;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/** The hub's local name of a table's type: `<instance>.<table>`. */
|
|
101
|
-
export function typeNameOf(instance: string, table: string): string {
|
|
102
|
-
return `${instance}.${identifierOf(table)}`;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/** The qualified hub name of a table's type. */
|
|
106
|
-
export function qualifiedTypeOf(instance: string, table: string): QualifiedName {
|
|
107
|
-
return `database/${typeNameOf(instance, table)}`;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* A table as a `table` arg may name it, read as the table and the instance it names (if any): its name (`expenses`),
|
|
112
|
-
* its type's local name (`main.expenses`), its type (`database/main.expenses`), or that type in the tools' spelling
|
|
113
|
-
* (`database__main__expenses`), so whichever spelling the model or a person copies finds the table.
|
|
114
|
-
*/
|
|
115
|
-
export function tableRefOf(given: string): { readonly instance?: string; readonly table: string } {
|
|
116
|
-
const trimmed = given.trim();
|
|
117
|
-
const name = trimmed.startsWith('database__') ? slashedName(trimmed) : trimmed;
|
|
118
|
-
const local = name.startsWith('database/') ? name.slice('database/'.length) : name;
|
|
119
|
-
const dot = local.indexOf('.');
|
|
120
|
-
return dot > 0 && dot < local.length - 1 ? { instance: local.slice(0, dot), table: local.slice(dot + 1) } : { table: local };
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
// ─── The hub's type ──────────────────────────────────────────────────────────
|
|
124
|
-
|
|
125
|
-
const GinOptions = z.record(z.string(), z.unknown());
|
|
126
|
-
const EnumOptions = z.object({ values: z.record(z.string(), z.union([z.string(), z.number()])) });
|
|
127
|
-
|
|
128
|
-
/** A gin def's options, as a plain record (none when it has none). */
|
|
129
|
-
export function ginOptions(def: GinDef): Record<string, unknown> {
|
|
130
|
-
const parsed = GinOptions.safeParse(def.options);
|
|
131
|
-
return parsed.success ? { ...parsed.data } : {};
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/** The values of a gin enum def (none for another def). */
|
|
135
|
-
export function enumValuesOf(def: GinDef): (string | number)[] {
|
|
136
|
-
const parsed = EnumOptions.safeParse(def.options);
|
|
137
|
-
return def.name === 'enum' && parsed.success ? Object.values(parsed.data.values) : [];
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/** A scalar gin def refined by a column's enrichment. */
|
|
141
|
-
function refined(base: GinDef, column: ColumnEnrichment): GinDef {
|
|
142
|
-
const options = ginOptions(base);
|
|
143
|
-
if (column.values !== undefined && (base.name === 'text' || base.name === 'num')) {
|
|
144
|
-
const values: Record<string, string | number> = {};
|
|
145
|
-
for (const value of column.values) { values[String(value)] = value; }
|
|
146
|
-
return { name: 'enum', generic: { V: base }, options: { values } };
|
|
147
|
-
}
|
|
148
|
-
if (base.name === 'text' && column.format !== undefined) { options['pattern'] = FORMAT_PATTERNS[column.format]; }
|
|
149
|
-
if (base.name === 'num' && column.min !== undefined) { options['min'] = column.min; }
|
|
150
|
-
if (base.name === 'num' && column.max !== undefined) { options['max'] = column.max; }
|
|
151
|
-
return Object.keys(options).length === 0 ? { name: base.name } : { ...base, options };
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/** A prop refined by its column's enrichment: the scalar under any `nullable`, and its docs. */
|
|
155
|
-
function refinedProp(prop: PropDef, column: ColumnEnrichment | undefined): PropDef {
|
|
156
|
-
if (column === undefined) { return prop; }
|
|
157
|
-
const nullable = prop.type.name === 'nullable';
|
|
158
|
-
const inner = nullable ? (prop.type.generic?.['T'] ?? { name: 'any' }) : prop.type;
|
|
159
|
-
// a column that already has a closed set keeps it
|
|
160
|
-
const scalar = inner.name === 'enum' ? inner : refined(inner, column);
|
|
161
|
-
const docs = [column.description, prop.docs, column.examples === undefined ? undefined : `E.g. ${column.examples.join(', ')}.`].filter((part): part is string => part !== undefined && part !== '');
|
|
162
|
-
return { ...prop, type: nullable ? { name: 'nullable', generic: { T: scalar } } : scalar, ...(docs.length === 0 ? {} : { docs: docs.join(' ') }) };
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/** The hub's gin type of a table's rows, refined by its enrichment when there is one. */
|
|
166
|
-
export function hubTypeOf(spec: TableSpec, enrichment?: TableEnrichment): GinTypeDef {
|
|
167
|
-
const base = tableToGinType(spec);
|
|
168
|
-
if (enrichment === undefined) { return GinTypeDef.parse(base); }
|
|
169
|
-
const props: Record<string, PropDef> = {};
|
|
170
|
-
for (const [name, prop] of Object.entries(base.props ?? {})) { props[name] = refinedProp(prop, enrichment.columns[name]); }
|
|
171
|
-
return GinTypeDef.parse({ ...base, docs: `${enrichment.description} ${base.docs ?? ''}`.trim(), props });
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
/** The field a type's title is read from: a name-like text column, else none. */
|
|
175
|
-
export function titleOf(spec: TableSpec): string | undefined {
|
|
176
|
-
const text = spec.columns.filter((column) => column.type.kind === 'text');
|
|
177
|
-
return (text.find((column) => /^(name|title|label|full_?name|display_?name)$/i.test(column.name)) ?? text.find((column) => /name|title/i.test(column.name)))?.name;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// ─── The query engine's type ─────────────────────────────────────────────────
|
|
181
|
-
|
|
182
|
-
/** A column's field type in the query engine. */
|
|
183
|
-
export function fieldTypeOf(type: ColumnType, values?: ColumnSpec['values']): FieldTypeDef {
|
|
184
|
-
const members = values === undefined ? {} : { values: values.map((value) => ({ value })) };
|
|
185
|
-
switch (type.kind) {
|
|
186
|
-
case 'text': return { kind: 'text', ...(type.maxLength === undefined ? {} : { maxLength: type.maxLength }), ...members };
|
|
187
|
-
case 'integer': return { kind: 'number', whole: true, ...members };
|
|
188
|
-
case 'decimal': return { kind: 'number', ...(type.scale === undefined ? {} : { maxPlaces: type.scale }), ...members };
|
|
189
|
-
case 'float': return { kind: 'number', ...members };
|
|
190
|
-
case 'bool': return { kind: 'bool' };
|
|
191
|
-
case 'date': return { kind: 'date' };
|
|
192
|
-
case 'timestamp': return { kind: 'timestamp', ...(type.timezone === undefined ? {} : { timezone: type.timezone }) };
|
|
193
|
-
case 'uuid': return { kind: 'text', casing: 'exact' };
|
|
194
|
-
case 'json': return { kind: 'json' };
|
|
195
|
-
case 'bytes': case 'other': return { kind: 'text', ...members };
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/** A relation field's name for a foreign key column: `customer_id` becomes `customer`, never clashing with a column. */
|
|
200
|
-
function relationName(column: string, taken: ReadonlySet<string>): string {
|
|
201
|
-
const base = column.replace(/(_id|Id|_key)$/, '');
|
|
202
|
-
for (const candidate of [base, `${column}_ref`, `${column}_row`]) {
|
|
203
|
-
if (candidate !== '' && candidate !== column && !taken.has(candidate)) { return candidate; }
|
|
204
|
-
}
|
|
205
|
-
return `${column}_${taken.size}`;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
/** An engine type, and the backing that maps it to its physical table and keys. */
|
|
209
|
-
export interface EngineType {
|
|
210
|
-
readonly def: TypeDef;
|
|
211
|
-
readonly backing: TypeBacking;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/** The query engine's type of one table (and its backing), refined by the enrichment's descriptions. */
|
|
215
|
-
export function engineTypeOf(table: ScannedTable, enrichment?: TableEnrichment): EngineType {
|
|
216
|
-
const spec = table.spec;
|
|
217
|
-
const name = identifierOf(spec.name);
|
|
218
|
-
const taken = new Set(spec.columns.map((column) => identifierOf(column.name)));
|
|
219
|
-
const backingFields: NonNullable<TypeBacking['fields']> = {};
|
|
220
|
-
const fields: FieldDef[] = spec.columns.map((column) => {
|
|
221
|
-
const field = identifierOf(column.name);
|
|
222
|
-
const extra = enrichment?.columns[column.name];
|
|
223
|
-
const usual = extra?.values !== undefined && column.values === undefined ? `Usually one of: ${extra.values.join(', ')}.` : undefined;
|
|
224
|
-
const description = [extra?.description, usual].filter((part): part is string => part !== undefined).join(' ');
|
|
225
|
-
const optionalOnInsert = column.generated === true || column.default !== undefined;
|
|
226
|
-
if (field !== column.name || optionalOnInsert) {
|
|
227
|
-
backingFields[field] = { ...(field === column.name ? {} : { name: column.name }), ...(optionalOnInsert ? { default: Value.null() } : {}) };
|
|
228
|
-
}
|
|
229
|
-
return {
|
|
230
|
-
name: field,
|
|
231
|
-
type: fieldTypeOf(column.type, column.values),
|
|
232
|
-
nullable: column.nullable,
|
|
233
|
-
...(description === '' ? {} : { description }),
|
|
234
|
-
...(column.generated === true ? { insertable: false, updatable: false } : {}),
|
|
235
|
-
};
|
|
236
|
-
});
|
|
237
|
-
for (const key of spec.foreignKeys) {
|
|
238
|
-
const [local] = key.columns;
|
|
239
|
-
if (key.columns.length !== 1 || local === undefined) { continue; }
|
|
240
|
-
const relation = relationName(identifierOf(local), taken);
|
|
241
|
-
taken.add(relation);
|
|
242
|
-
fields.push({ name: relation, type: { kind: 'relation', to: identifierOf(key.table), count: 1 }, nullable: spec.columns.find((column) => column.name === local)?.nullable ?? true, insertable: false, updatable: false, description: `The ${key.table} row ${local} refers to.` });
|
|
243
|
-
backingFields[relation] = { relation: { keys: [{ local, foreign: key.references[0] ?? 'id' }] } };
|
|
244
|
-
}
|
|
245
|
-
const def: TypeDef = {
|
|
246
|
-
name,
|
|
247
|
-
fields,
|
|
248
|
-
count: Math.max(table.rows, 1),
|
|
249
|
-
...(spec.primaryKey.length === 0 ? {} : { identity: spec.primaryKey.length === 1 ? identifierOf(spec.primaryKey[0] ?? '') : spec.primaryKey.map(identifierOf) }),
|
|
250
|
-
...(enrichment === undefined ? {} : { description: enrichment.description }),
|
|
251
|
-
};
|
|
252
|
-
return { def, backing: { ...(name === spec.name ? {} : { name: spec.name }), fields: backingFields } };
|
|
253
|
-
}
|