@romedb/studio 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.
- package/LICENSE.md +20 -0
- package/README.md +15 -2
- package/package.json +36 -4
- package/src/components/CodeEditor.ts +298 -0
- package/src/components/studio/BrowseTab.ts +457 -0
- package/src/components/studio/CellEditorSheet.ts +165 -0
- package/src/components/studio/DatabaseTab.ts +148 -0
- package/src/components/studio/GraphCanvas.ts +90 -0
- package/src/components/studio/GraphTab.ts +110 -0
- package/src/components/studio/InsertRowSheet.ts +180 -0
- package/src/components/studio/MapCanvas.ts +177 -0
- package/src/components/studio/MapTab.ts +121 -0
- package/src/components/studio/NewObjectSheet.ts +235 -0
- package/src/components/studio/QueryHistorySheet.ts +111 -0
- package/src/components/studio/RowSheets.ts +226 -0
- package/src/components/studio/SqlConsole.ts +281 -0
- package/src/components/studio/StructureTab.ts +209 -0
- package/src/components/studio/icon-button.ts +21 -0
- package/src/lib/filters.ts +44 -0
- package/src/lib/graph.ts +214 -0
- package/src/lib/romeql.ts +106 -0
- package/src/lib/spatial.ts +518 -0
- package/src/lib/sql-text.ts +208 -0
- package/src/lib/studio-types.ts +268 -0
- package/src/lib/values.ts +305 -0
- package/src/monaco-standalone.d.ts +27 -0
- package/src/schema-draft.ts +41 -0
- package/src/schema-store.ts +8 -0
- package/src/server/backend.ts +77 -0
- package/src/server/data.ts +142 -0
- package/src/server/edits.ts +92 -0
- package/src/server/graph.ts +66 -0
- package/src/server/queries.ts +108 -0
- package/src/server/schema.ts +272 -0
- package/src/server/spatial.ts +74 -0
- package/src/studio-page.ts +84 -0
- package/src/workspace/StudioWorkspace.ts +1984 -0
- package/src/workspace/workspace.css +38 -0
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import type { PortableValue } from '@romedb/client';
|
|
2
|
+
import type { StudioColumn } from './studio-types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Value helpers shared by the grid, the editor sheets and exports.
|
|
6
|
+
*
|
|
7
|
+
* RomeDB values are typed (Integer and Number are distinct, Record IDs and
|
|
8
|
+
* binary data have their own types). The grid shows them as plain text, and
|
|
9
|
+
* the JSON editors use an extended JSON form so editing a row never loses a
|
|
10
|
+
* type: `{"$record":"users:tan"}`, `{"$binary":"0a0b"}`, `{"$vector":"…"}`,
|
|
11
|
+
* `{"$integer":"…"}` for integers outside JavaScript's safe range,
|
|
12
|
+
* `{"$number":3}` for whole floating-point numbers (`{"$number":"-0"}` for
|
|
13
|
+
* negative zero) and `{"$object":{…}}` for an object whose single key is one
|
|
14
|
+
* of these wrapper names.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export type ValueKind =
|
|
18
|
+
| 'text' | 'integer' | 'number' | 'boolean' | 'json' | 'record'
|
|
19
|
+
| 'date' | 'datetime' | 'timestamp' | 'uuid-v4' | 'uuid-v7' | 'binary';
|
|
20
|
+
|
|
21
|
+
export const VALUE_KINDS: Array<{ value: ValueKind; label: string }> = [
|
|
22
|
+
{ value: 'text', label: 'Text' },
|
|
23
|
+
{ value: 'integer', label: 'Integer' },
|
|
24
|
+
{ value: 'number', label: 'Number' },
|
|
25
|
+
{ value: 'boolean', label: 'Boolean' },
|
|
26
|
+
{ value: 'json', label: 'JSON' },
|
|
27
|
+
{ value: 'record', label: 'Record ID' },
|
|
28
|
+
{ value: 'date', label: 'Date' },
|
|
29
|
+
{ value: 'datetime', label: 'Datetime (local)' },
|
|
30
|
+
{ value: 'timestamp', label: 'Timestamp (UTC)' },
|
|
31
|
+
{ value: 'uuid-v4', label: 'UUID v4' },
|
|
32
|
+
{ value: 'uuid-v7', label: 'UUID v7' },
|
|
33
|
+
{ value: 'binary', label: 'Binary (hex)' },
|
|
34
|
+
];
|
|
35
|
+
|
|
36
|
+
export function numberText(bits: string): string {
|
|
37
|
+
if (!/^[0-9a-f]{16}$/.test(bits)) return 'Invalid encoded number';
|
|
38
|
+
const number = new DataView(hexBytes(bits).buffer).getFloat64(0, false);
|
|
39
|
+
return Object.is(number, -0) ? '-0' : String(number);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function numberBits(value: number): string {
|
|
43
|
+
if (!Number.isFinite(value)) throw new Error('Enter a finite number.');
|
|
44
|
+
const bytes = new Uint8Array(8);
|
|
45
|
+
new DataView(bytes.buffer).setFloat64(0, value, false);
|
|
46
|
+
return bytesHex(bytes);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function vectorSummary(bytes: number[]): string {
|
|
50
|
+
const buffer = Uint8Array.from(bytes);
|
|
51
|
+
const view = new DataView(buffer.buffer);
|
|
52
|
+
const tag = bytes[bytes.length - 1];
|
|
53
|
+
if (bytes.length >= 5 && bytes.length % 8 === 5 && tag === 9) {
|
|
54
|
+
return `Sparse float32 · ${view.getUint32(bytes.length - 5, true)} dimensions · ${(bytes.length - 5) / 8} nonzero values`;
|
|
55
|
+
}
|
|
56
|
+
const width = bytes.length >= 9 && bytes.length % 8 === 1 && tag === 2 ? 8 : bytes.length % 4 === 0 ? 4 : 0;
|
|
57
|
+
if (!width) return `Encoded vector · ${bytes.length} bytes`;
|
|
58
|
+
const dimensions = Math.floor(bytes.length / width);
|
|
59
|
+
const preview = Array.from({ length: Math.min(dimensions, 8) }, (_, index) =>
|
|
60
|
+
width === 8 ? view.getFloat64(index * width, true) : view.getFloat32(index * width, true));
|
|
61
|
+
return `Float${width * 8} · ${dimensions} dimensions · [${preview.map(number => Object.is(number, -0) ? '-0' : String(number)).join(', ')}${dimensions > 8 ? ', …' : ''}]`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Record ID in RomeQL form: users:tan, users:42 or users:`a key`. */
|
|
65
|
+
export function recordText(value: Extract<PortableValue, { type: 'Record' }>['value']): string {
|
|
66
|
+
const key = value.key.type === 'String' && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.key.value)
|
|
67
|
+
? `\`${value.key.value.replaceAll('`', '``')}\``
|
|
68
|
+
: value.key.value;
|
|
69
|
+
return `${value.table}:${key}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function parseRecord(text: string): Extract<PortableValue, { type: 'Record' }> {
|
|
73
|
+
const separator = text.indexOf(':');
|
|
74
|
+
const table = text.slice(0, separator).trim();
|
|
75
|
+
const key = text.slice(separator + 1).trim();
|
|
76
|
+
if (separator < 1 || !table || !key) throw new Error('Enter a record ID such as users:tan.');
|
|
77
|
+
if (key.length >= 2 && key.startsWith('`') && key.endsWith('`')) {
|
|
78
|
+
return { type: 'Record', value: { table, key: { type: 'String', value: key.slice(1, -1).replaceAll('``', '`') } } };
|
|
79
|
+
}
|
|
80
|
+
if (/^-?\d+$/.test(key)) return { type: 'Record', value: { table, key: { type: 'Integer', value: integerText(key) } } };
|
|
81
|
+
return { type: 'Record', value: { table, key: { type: 'String', value: key } } };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Short, single-line text for grid cells. */
|
|
85
|
+
export function displayValue(value: PortableValue | undefined): string {
|
|
86
|
+
if (value === undefined) return '';
|
|
87
|
+
switch (value.type) {
|
|
88
|
+
case 'Null': return 'NULL';
|
|
89
|
+
case 'Boolean': return String(value.value);
|
|
90
|
+
case 'String':
|
|
91
|
+
case 'Integer': return value.value;
|
|
92
|
+
case 'Number': return numberText(value.value);
|
|
93
|
+
case 'Record': return recordText(value.value);
|
|
94
|
+
case 'Binary': return `BLOB (${portableBytes(value.value).length} bytes)`;
|
|
95
|
+
case 'Vector': return vectorSummary(portableBytes(value.value));
|
|
96
|
+
case 'Array':
|
|
97
|
+
case 'Object': return JSON.stringify(toJson(value));
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Plain JSON for export: lossless extended JSON, without type wrappers for ordinary values. */
|
|
102
|
+
export function toJson(value: PortableValue): unknown {
|
|
103
|
+
switch (value.type) {
|
|
104
|
+
case 'Null': return null;
|
|
105
|
+
case 'Boolean':
|
|
106
|
+
case 'String': return value.value;
|
|
107
|
+
case 'Integer': {
|
|
108
|
+
const number = Number(value.value);
|
|
109
|
+
return Number.isSafeInteger(number) ? number : { $integer: value.value };
|
|
110
|
+
}
|
|
111
|
+
case 'Number': {
|
|
112
|
+
const number = Number(numberText(value.value));
|
|
113
|
+
if (Object.is(number, -0)) return { $number: '-0' };
|
|
114
|
+
return Number.isInteger(number) ? { $number: number } : number;
|
|
115
|
+
}
|
|
116
|
+
case 'Record': return { $record: recordText(value.value) };
|
|
117
|
+
case 'Binary': return { $binary: bytesHex(portableBytes(value.value)) };
|
|
118
|
+
case 'Vector': return { $vector: bytesHex(portableBytes(value.value)) };
|
|
119
|
+
case 'Array': return value.value.map(toJson);
|
|
120
|
+
case 'Object': {
|
|
121
|
+
const object = Object.fromEntries(Object.entries(value.value).map(([key, entry]) => [key, toJson(entry)]));
|
|
122
|
+
const keys = Object.keys(object);
|
|
123
|
+
return keys.length === 1 && WRAPPERS.has(keys[0]) ? { $object: object } : object;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const WRAPPERS = new Set(['$integer', '$number', '$record', '$binary', '$vector', '$object']);
|
|
129
|
+
|
|
130
|
+
export function fromJson(value: unknown, depth = 0): PortableValue {
|
|
131
|
+
if (depth > 64) throw new Error('JSON values are limited to 64 nested levels.');
|
|
132
|
+
if (value === null) return { type: 'Null' };
|
|
133
|
+
if (typeof value === 'boolean') return { type: 'Boolean', value };
|
|
134
|
+
if (typeof value === 'string') return { type: 'String', value };
|
|
135
|
+
if (typeof value === 'number') {
|
|
136
|
+
if (!Number.isFinite(value)) throw new Error('JSON numbers must be finite.');
|
|
137
|
+
return Number.isSafeInteger(value) ? { type: 'Integer', value: String(value) } : { type: 'Number', value: numberBits(value) };
|
|
138
|
+
}
|
|
139
|
+
if (Array.isArray(value)) return { type: 'Array', value: value.map(entry => fromJson(entry, depth + 1)) };
|
|
140
|
+
if (typeof value === 'object') {
|
|
141
|
+
const entries = Object.entries(value as Record<string, unknown>);
|
|
142
|
+
if (entries.length === 1) {
|
|
143
|
+
const [key, inner] = entries[0];
|
|
144
|
+
if (key === '$integer' && (typeof inner === 'string' || typeof inner === 'number')) return { type: 'Integer', value: integerText(String(inner)) };
|
|
145
|
+
if (key === '$number' && typeof inner === 'number') return { type: 'Number', value: numberBits(inner) };
|
|
146
|
+
if (key === '$number' && inner === '-0') return { type: 'Number', value: numberBits(-0) };
|
|
147
|
+
if (key === '$object' && inner && typeof inner === 'object' && !Array.isArray(inner)) {
|
|
148
|
+
return { type: 'Object', value: Object.fromEntries(Object.entries(inner as Record<string, unknown>).map(([name, entry]) => [name, fromJson(entry, depth + 1)])) };
|
|
149
|
+
}
|
|
150
|
+
if (key === '$record' && typeof inner === 'string') return parseRecord(inner);
|
|
151
|
+
if (key === '$binary' && typeof inner === 'string') return { type: 'Binary', value: hexToBytes(inner) };
|
|
152
|
+
if (key === '$vector' && typeof inner === 'string') return { type: 'Vector', value: hexToBytes(inner) };
|
|
153
|
+
}
|
|
154
|
+
return { type: 'Object', value: Object.fromEntries(entries.map(([key, entry]) => [key, fromJson(entry, depth + 1)])) };
|
|
155
|
+
}
|
|
156
|
+
throw new Error('Unsupported JSON value.');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function sameValue(left: PortableValue | undefined, right: PortableValue | undefined): boolean {
|
|
160
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function integerText(text: string): string {
|
|
164
|
+
if (!/^-?(?:0|[1-9][0-9]*)$/.test(text.trim())) throw new Error('Enter a whole signed 64-bit integer.');
|
|
165
|
+
const integer = BigInt(text.trim());
|
|
166
|
+
if (integer < -9223372036854775808n || integer > 9223372036854775807n) throw new Error('Integer is outside the signed 64-bit range.');
|
|
167
|
+
return integer.toString();
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Editor kind for an existing value, falling back to the declared column type. */
|
|
171
|
+
export function kindForValue(value: PortableValue | undefined, column?: StudioColumn): ValueKind {
|
|
172
|
+
switch (value?.type) {
|
|
173
|
+
case 'String': return column ? textKind(declaredKind(column)) : 'text';
|
|
174
|
+
case 'Integer': return 'integer';
|
|
175
|
+
case 'Number': return 'number';
|
|
176
|
+
case 'Boolean': return 'boolean';
|
|
177
|
+
case 'Record': return 'record';
|
|
178
|
+
case 'Binary': return 'binary';
|
|
179
|
+
case 'Array':
|
|
180
|
+
case 'Object':
|
|
181
|
+
case 'Vector': return 'json';
|
|
182
|
+
default: return column ? declaredKind(column) : 'text';
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function textKind(kind: ValueKind): ValueKind {
|
|
187
|
+
return kind === 'date' || kind === 'datetime' || kind === 'timestamp' ? kind : 'text';
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Default editor kind for a column, from its declared SQL type or document field type. */
|
|
191
|
+
export function declaredKind(column: StudioColumn): ValueKind {
|
|
192
|
+
const type = column.dataType.toLowerCase();
|
|
193
|
+
if (/\b(timestamp)\b/.test(type)) return 'timestamp';
|
|
194
|
+
if (/\bdatetime\b/.test(type)) return 'datetime';
|
|
195
|
+
if (/\bdate\b/.test(type)) return 'date';
|
|
196
|
+
if (/bool/.test(type)) return 'boolean';
|
|
197
|
+
if (/^(record|link)/.test(type)) return 'record';
|
|
198
|
+
if (/json|object|array/.test(type)) return 'json';
|
|
199
|
+
if (/int/.test(type)) return 'integer';
|
|
200
|
+
if (/real|floa|doub|num|dec/.test(type)) return 'number';
|
|
201
|
+
if (/blob|bytes|binary/.test(type)) return 'binary';
|
|
202
|
+
return 'text';
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Text shown in an editor for a value of the chosen kind. */
|
|
206
|
+
export function editableText(value: PortableValue | undefined, kind: ValueKind): string {
|
|
207
|
+
if (!value || value.type === 'Null') return kind === 'json' ? 'null' : '';
|
|
208
|
+
if (kind === 'json') return JSON.stringify(toJson(value), null, 2);
|
|
209
|
+
switch (value.type) {
|
|
210
|
+
case 'String':
|
|
211
|
+
case 'Integer': return value.value;
|
|
212
|
+
case 'Number': return numberText(value.value);
|
|
213
|
+
case 'Boolean': return String(value.value);
|
|
214
|
+
case 'Record': return recordText(value.value);
|
|
215
|
+
case 'Binary': return bytesHex(portableBytes(value.value));
|
|
216
|
+
default: return JSON.stringify(toJson(value), null, 2);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Converts editor text to a typed value. Throws a user-facing message when invalid. */
|
|
221
|
+
export function kindValue(kind: ValueKind, text: string): PortableValue {
|
|
222
|
+
switch (kind) {
|
|
223
|
+
case 'integer': return { type: 'Integer', value: integerText(text) };
|
|
224
|
+
case 'number': {
|
|
225
|
+
if (!/^\s*[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?\s*$/.test(text)) throw new Error('Enter a finite decimal number.');
|
|
226
|
+
return { type: 'Number', value: numberBits(Number(text)) };
|
|
227
|
+
}
|
|
228
|
+
case 'boolean': {
|
|
229
|
+
if (text !== 'true' && text !== 'false') throw new Error('Use true or false for a Boolean.');
|
|
230
|
+
return { type: 'Boolean', value: text === 'true' };
|
|
231
|
+
}
|
|
232
|
+
case 'json': return fromJson(JSON.parse(text));
|
|
233
|
+
case 'record': return parseRecord(text);
|
|
234
|
+
case 'binary': {
|
|
235
|
+
const compact = text.replace(/\s/g, '');
|
|
236
|
+
if (/^(?:[0-9a-fA-F]{2})*$/.test(compact)) return { type: 'Binary', value: hexToBytes(compact) };
|
|
237
|
+
try { return { type: 'Binary', value: Array.from(atob(compact), character => character.charCodeAt(0)) }; }
|
|
238
|
+
catch { throw new Error('Enter hexadecimal byte pairs or base64.'); }
|
|
239
|
+
}
|
|
240
|
+
default: return { type: 'String', value: text };
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export function csvCell(value: string): string {
|
|
245
|
+
return /[",\r\n]/.test(value) ? `"${value.replaceAll('"', '""')}"` : value;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export function formatCount(value: number): string {
|
|
249
|
+
return new Intl.NumberFormat('en-US').format(value);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export function localDateTimeDefaults(): { date: string; datetime: string; timestamp: string } {
|
|
253
|
+
const now = new Date();
|
|
254
|
+
const local = new Date(now.getTime() - now.getTimezoneOffset() * 60_000).toISOString();
|
|
255
|
+
return { date: local.slice(0, 10), datetime: local.slice(0, 16), timestamp: now.toISOString() };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function generateUuid(kind: 'uuid-v4' | 'uuid-v7'): string {
|
|
259
|
+
if (kind === 'uuid-v4') return crypto.randomUUID();
|
|
260
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
261
|
+
let timestamp = Date.now();
|
|
262
|
+
for (let index = 5; index >= 0; index--) {
|
|
263
|
+
bytes[index] = timestamp & 0xff;
|
|
264
|
+
timestamp = Math.floor(timestamp / 256);
|
|
265
|
+
}
|
|
266
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x70;
|
|
267
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
268
|
+
const hex = bytesHex(bytes);
|
|
269
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Fills generated values when an editor switches to a kind that has a natural default. */
|
|
273
|
+
export function kindDefault(kind: ValueKind, current: string): string {
|
|
274
|
+
const now = localDateTimeDefaults();
|
|
275
|
+
if (kind === 'boolean') return current === 'false' ? 'false' : 'true';
|
|
276
|
+
if (kind === 'json' && !current.trim()) return '{}';
|
|
277
|
+
if (kind === 'date' && !current.trim()) return now.date;
|
|
278
|
+
if (kind === 'datetime' && !current.trim()) return now.datetime;
|
|
279
|
+
if (kind === 'timestamp') return now.timestamp;
|
|
280
|
+
if (kind === 'uuid-v4' || kind === 'uuid-v7') return generateUuid(kind);
|
|
281
|
+
return current;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Bytes of a Binary or Vector value. Cloud query version 3 sends them as
|
|
286
|
+
* canonical base64; local services and older versions send byte arrays.
|
|
287
|
+
*/
|
|
288
|
+
export function portableBytes(value: readonly number[] | string): number[] {
|
|
289
|
+
if (typeof value !== 'string') return [...value];
|
|
290
|
+
return Array.from(atob(value), character => character.charCodeAt(0));
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function bytesHex(bytes: ArrayLike<number>): string {
|
|
294
|
+
return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function hexBytes(hex: string): Uint8Array {
|
|
298
|
+
return Uint8Array.from(hex.match(/../g) ?? [], byte => parseInt(byte, 16));
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function hexToBytes(hex: string): number[] {
|
|
302
|
+
const compact = hex.replace(/\s/g, '');
|
|
303
|
+
if (!/^(?:[0-9a-fA-F]{2})*$/.test(compact)) throw new Error('Enter complete hexadecimal byte pairs.');
|
|
304
|
+
return Array.from(hexBytes(compact));
|
|
305
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
declare module 'monaco-editor/esm/vs/editor/standalone/browser/standaloneEditor' {
|
|
2
|
+
import type * as Monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
3
|
+
|
|
4
|
+
export const create: typeof Monaco.editor.create;
|
|
5
|
+
export const setModelLanguage: typeof Monaco.editor.setModelLanguage;
|
|
6
|
+
export const setTheme: typeof Monaco.editor.setTheme;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
declare module 'monaco-editor/esm/vs/editor/standalone/browser/standaloneLanguages' {
|
|
10
|
+
import type * as Monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
11
|
+
|
|
12
|
+
export const registerCompletionItemProvider:
|
|
13
|
+
typeof Monaco.languages.registerCompletionItemProvider;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
declare module 'monaco-editor/esm/vs/editor/common/services/editorBaseApi' {
|
|
17
|
+
import type * as Monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
18
|
+
|
|
19
|
+
export const KeyMod: typeof Monaco.KeyMod;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
declare module 'monaco-editor/esm/vs/editor/common/standalone/standaloneEnums' {
|
|
23
|
+
import type * as Monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
24
|
+
|
|
25
|
+
export const CompletionItemKind: typeof Monaco.languages.CompletionItemKind;
|
|
26
|
+
export const KeyCode: typeof Monaco.KeyCode;
|
|
27
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export type NewColumn = { name: string; type: string; primary: boolean; required: boolean; unique: boolean };
|
|
2
|
+
export const COLUMN_TYPES = ['INTEGER', 'TEXT', 'REAL', 'BLOB', 'NUMERIC', 'BOOLEAN', 'DATE', 'DATETIME'];
|
|
3
|
+
function identifier(name: string): string {
|
|
4
|
+
if (!name || name.length > 128 || /[\x00-\x1f\x7f]/.test(name) || /^(?:__romedb_|sqlite_|__turso_internal_)/i.test(name)) throw new Error('Use a non-reserved name with 1–128 characters');
|
|
5
|
+
return '"' + name.replaceAll('"', '""') + '"';
|
|
6
|
+
}
|
|
7
|
+
export type NewEdge = { source: string; target: string; cascade: boolean };
|
|
8
|
+
export type NewSpatialIndex = { table: string; field: string; region: boolean };
|
|
9
|
+
export function createObjectSql(name: string, kind: string, columns: NewColumn[], edge?: NewEdge, spatial?: NewSpatialIndex): string {
|
|
10
|
+
const table = identifier(name);
|
|
11
|
+
if (kind === 'collection') return `CREATE TABLE ${table};`;
|
|
12
|
+
if (kind === 'spatial') {
|
|
13
|
+
if (!spatial?.table) throw new Error('Choose a document collection');
|
|
14
|
+
const parts = spatial.field.trim().split('.');
|
|
15
|
+
if (!spatial.field.trim() || parts.length > 32 || parts.some(part => !part.trim())) throw new Error('Enter a field path such as location or address.location');
|
|
16
|
+
if (parts.length === 1 && parts[0].trim() === 'id') throw new Error('The record ID cannot hold geometry; choose another field');
|
|
17
|
+
const path = parts.map(part => identifier(part.trim())).join('.');
|
|
18
|
+
return `CREATE SEARCH INDEX ${table} ON ${identifier(spatial.table)}(${path}) USING SPATIAL${spatial.region ? " WITH (geometry = 'region')" : ''};`;
|
|
19
|
+
}
|
|
20
|
+
if (kind === 'edge') {
|
|
21
|
+
if (!edge?.source || !edge.target) throw new Error('Choose source and target collections');
|
|
22
|
+
return `CREATE EDGE TABLE ${table} FROM ${identifier(edge.source)} TO ${identifier(edge.target)} ON DELETE ${edge.cascade ? 'CASCADE' : 'RESTRICT'};`;
|
|
23
|
+
}
|
|
24
|
+
if (kind !== 'table' || columns.length < 1 || columns.length > 128) throw new Error('Choose 1–128 table columns');
|
|
25
|
+
const names = new Set<string>();
|
|
26
|
+
const primary = columns.filter(column => column.primary);
|
|
27
|
+
// A lone INTEGER primary key becomes SQLite's rowid alias, so inserts may omit it.
|
|
28
|
+
const rowid = primary.length === 1 && primary[0].type === 'INTEGER' ? primary[0] : undefined;
|
|
29
|
+
const definitions = columns.map(column => {
|
|
30
|
+
const quoted = identifier(column.name);
|
|
31
|
+
const key = column.name.toLowerCase();
|
|
32
|
+
if (names.has(key)) throw new Error('Column names must be distinct');
|
|
33
|
+
names.add(key);
|
|
34
|
+
if (!COLUMN_TYPES.includes(column.type)) throw new Error('Choose a supported column type');
|
|
35
|
+
if (column === rowid) return `${quoted} INTEGER PRIMARY KEY${column.unique ? ' UNIQUE' : ''}`;
|
|
36
|
+
return `${quoted} ${column.type}${column.required ? ' NOT NULL' : ''}${column.unique ? ' UNIQUE' : ''}`;
|
|
37
|
+
});
|
|
38
|
+
const keys = rowid ? [] : primary.map(column => identifier(column.name));
|
|
39
|
+
if (keys.length) definitions.push(`PRIMARY KEY (${keys.join(', ')})`);
|
|
40
|
+
return `CREATE TABLE ${table} (\n ${definitions.join(',\n ')}\n);`;
|
|
41
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createStore } from '@cossackframework/core';
|
|
2
|
+
import type { StudioSchema } from './lib/studio-types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Browser-memory catalog shared by every Monaco instance, so completion
|
|
6
|
+
* providers read the freshest schema after DDL without rebuilding editors.
|
|
7
|
+
*/
|
|
8
|
+
export const studioSchemaCatalog = createStore<StudioSchema | null>(null);
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// The seam between the database workspace and whatever holds the connections. Studio's own
|
|
2
|
+
// registry (`StudioConnections`) implements it over local files and URLs; another
|
|
3
|
+
// application, such as the Cloud dashboard, supplies its own for the request with
|
|
4
|
+
// `provideWorkspaceConnections`. Every function of schema, data, edits, queries, graph and
|
|
5
|
+
// spatial reaches a database only through this interface.
|
|
6
|
+
import type { Context } from 'hono';
|
|
7
|
+
import { encodeValue, type BatchResult, type Client, type ClientError, type Statement, type WorkLimits } from '@romedb/client';
|
|
8
|
+
|
|
9
|
+
/** A result as it crosses to the browser: values are portable (tagged) values. */
|
|
10
|
+
export type PortableBatch = {
|
|
11
|
+
requestId: BatchResult['requestId']; sequence: number;
|
|
12
|
+
results: { columns: string[]; rows: import('@romedb/client').PortableValue[][]; affected: string }[];
|
|
13
|
+
readVersion?: number;
|
|
14
|
+
};
|
|
15
|
+
/** Why a request did not give a result. `outcome` says whether a write may have been made. */
|
|
16
|
+
export type RequestFailure = { code: string; message: string; outcome: string; sequence?: number };
|
|
17
|
+
/**
|
|
18
|
+
* A reply to a read, a write or a recovery. `recoveryId` names a saved write whose outcome is
|
|
19
|
+
* not known yet; `acknowledgement` is the nonce that releases a saved write once the browser
|
|
20
|
+
* has its result.
|
|
21
|
+
*/
|
|
22
|
+
export type ExecuteReply = (PortableBatch | { error: RequestFailure }) & { recoveryId?: string; acknowledgement?: string };
|
|
23
|
+
|
|
24
|
+
export type WorkspaceDescriptor = {
|
|
25
|
+
connectionId: string; profileId: string; name: string; kind: 'file' | 'url'; endpoint: string; databaseId: string; sequence: number;
|
|
26
|
+
capabilities: Awaited<ReturnType<Client['info']>>['capabilities']; limits: Record<string, unknown>;
|
|
27
|
+
engineVersion?: string; journalMode?: string;
|
|
28
|
+
/** Version of the RomeDB SDK the host runs. It is the engine for database files. */
|
|
29
|
+
clientVersion?: string;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export interface WorkspaceConnections {
|
|
33
|
+
describe(actor: string, connectionId: string): Promise<WorkspaceDescriptor>;
|
|
34
|
+
/** One read, or one atomic write. `retainJournal` keeps a write's saved request until it is acknowledged. */
|
|
35
|
+
execute(actor: string, connectionId: string, operationId: string, statements: Statement[], mode: 'read' | 'write',
|
|
36
|
+
ifSequence?: number, workLimits?: WorkLimits, retainJournal?: boolean): Promise<ExecuteReply>;
|
|
37
|
+
/** Ask again for the result of a saved write. It never runs the write a second time. */
|
|
38
|
+
recover(actor: string, connectionId: string, recoveryId: string, operationId?: string, retainJournal?: boolean): Promise<ExecuteReply>;
|
|
39
|
+
acknowledge(actor: string, connectionId: string, recoveryId: string, nonce: string): Promise<void>;
|
|
40
|
+
/** Saved writes of this connection whose outcome is not known. */
|
|
41
|
+
recoveryIds(actor: string, connectionId: string): Promise<string[]>;
|
|
42
|
+
cancel(actor: string, operationId: string): void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const PROVIDED = 'studioWorkspaceConnections';
|
|
46
|
+
|
|
47
|
+
/** Supply the connections for this request. Call it before any workspace server function. */
|
|
48
|
+
export function provideWorkspaceConnections(context: Context, connections: WorkspaceConnections): void {
|
|
49
|
+
context.set(PROVIDED as never, connections as never);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The connections of this request: the provided ones, or Studio's own registry. */
|
|
53
|
+
export function workspaceConnections(context: Context): WorkspaceConnections {
|
|
54
|
+
const provided = context.get(PROVIDED as never) as Partial<WorkspaceConnections> | undefined;
|
|
55
|
+
// A request context can answer any key (tests do); accept only a real set of connections.
|
|
56
|
+
if (typeof provided?.execute === 'function') return provided as WorkspaceConnections;
|
|
57
|
+
const found = (context.env?.STUDIO as { connections?: WorkspaceConnections } | undefined)?.connections;
|
|
58
|
+
if (!found) throw new Error('Studio backend is unavailable');
|
|
59
|
+
return found;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A result as the browser receives it: values in their portable form. */
|
|
63
|
+
export function portable(batch: BatchResult) {
|
|
64
|
+
return { requestId: batch.requestId, sequence: batch.sequence, results: batch.results.map(result => ({ columns: result.columns, rows: result.rows.map(row => row.map(encodeValue)), affected: result.affected.toString() })), ...(batch.readVersion === undefined ? {} : { readVersion: batch.readVersion }) };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** What a failed request tells the page. An error the SDK did not raise has no known outcome once the request left. */
|
|
68
|
+
export function failure(error: unknown, dispatched = false) {
|
|
69
|
+
return clientFailure(error)
|
|
70
|
+
? { code: error.code, message: error.message, outcome: error.outcome, ...(error.sequence === undefined ? {} : { sequence: error.sequence }) }
|
|
71
|
+
: { code: 'STUDIO_REQUEST', message: 'Studio could not complete this database request', outcome: dispatched ? 'unknown' : 'not-sent' };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function clientFailure(error: unknown): error is ClientError {
|
|
75
|
+
if (!(error instanceof Error) || !('code' in error) || typeof error.code !== 'string' || !/^RDB_[A-Z0-9_]{1,80}$/.test(error.code) || !('outcome' in error) || typeof error.outcome !== 'string' || !['not-sent', 'read-failed', 'unknown', 'rolled-back'].includes(error.outcome)) return false;
|
|
76
|
+
return error.outcome !== 'rolled-back' || ('sequence' in error && Number.isSafeInteger(error.sequence) && Number(error.sequence) >= 0);
|
|
77
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import { decodeValue, type PortableValue, type Statement, type Value } from '@romedb/client';
|
|
3
|
+
import { workspaceConnections } from './backend';
|
|
4
|
+
import { isTextOperator } from '../lib/filters';
|
|
5
|
+
import { quoteIdentifier, sqlLiteral } from '../lib/sql-text';
|
|
6
|
+
import { kindValue } from '../lib/values';
|
|
7
|
+
import { PAGE_SIZES, type BrowseFilter, type BrowseSort, type GridResult, type GridRow, type ObjectModel, type StatementResult } from '../lib/studio-types';
|
|
8
|
+
|
|
9
|
+
export type BrowseRequest = { page: number; pageSize: number; filters: BrowseFilter[]; sort: BrowseSort[]; model: ObjectModel };
|
|
10
|
+
export type BrowseStatements = { count: Statement; rows: Statement; display: string };
|
|
11
|
+
|
|
12
|
+
const OPERATORS: Record<string, string> = { eq: '=', ne: '!=', gt: '>', gte: '>=', lt: '<', lte: '<=' };
|
|
13
|
+
|
|
14
|
+
/** Loads one page of a table, collection or view with its total row count. */
|
|
15
|
+
export async function browseGrid(context: Context, connectionId: string, table: string, request: BrowseRequest): Promise<GridResult> {
|
|
16
|
+
const actor = context.get('user') as { id?: string } | undefined;
|
|
17
|
+
if (!actor?.id) throw new Error('Studio session required');
|
|
18
|
+
const empty: GridResult = { columns: [], rows: [], affectedRows: 0, durationMs: 0, truncated: false, totalRows: 0, page: request?.page ?? 1, pageSize: request?.pageSize ?? 100, objectName: table, query: '', sequence: 0 };
|
|
19
|
+
const started = performance.now();
|
|
20
|
+
try {
|
|
21
|
+
const built = browseStatements(table, request);
|
|
22
|
+
const reply = await workspaceConnections(context).execute(actor.id, connectionId, crypto.randomUUID(), [built.count, built.rows], 'read');
|
|
23
|
+
if (!('results' in reply) || !reply.results) {
|
|
24
|
+
return { ...empty, query: built.display, error: 'error' in reply && reply.error ? `${reply.error.message}` : 'Invalid database response' };
|
|
25
|
+
}
|
|
26
|
+
const total = reply.results[0]?.rows[0]?.[0];
|
|
27
|
+
const page = statementResult(reply.results[1]?.columns ?? [], reply.results[1]?.rows ?? [], request.model === 'document');
|
|
28
|
+
return {
|
|
29
|
+
...empty,
|
|
30
|
+
columns: page.columns,
|
|
31
|
+
rows: page.rows,
|
|
32
|
+
totalRows: total?.type === 'Integer' ? Number(total.value) : page.rows.length,
|
|
33
|
+
query: built.display,
|
|
34
|
+
sequence: reply.sequence,
|
|
35
|
+
durationMs: performance.now() - started,
|
|
36
|
+
};
|
|
37
|
+
} catch (error) {
|
|
38
|
+
return { ...empty, error: error instanceof Error ? error.message.slice(0, 512) : 'Cannot browse this object' };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Builds the bound count/page statements and a readable equivalent for the query editor. */
|
|
43
|
+
export function browseStatements(table: string, request: BrowseRequest): BrowseStatements {
|
|
44
|
+
if (!request || !PAGE_SIZES.includes(request.pageSize)) throw new Error('Choose a supported page size');
|
|
45
|
+
if (!Number.isSafeInteger(request.page) || request.page < 1 || (request.page - 1) * request.pageSize > 10_000_000) throw new Error('Invalid browsing page');
|
|
46
|
+
if (!['relational', 'document', 'view'].includes(request.model)) throw new Error('Invalid object model');
|
|
47
|
+
const filters = request.filters ?? [];
|
|
48
|
+
const sort = request.sort ?? [];
|
|
49
|
+
if (!Array.isArray(filters) || filters.length > 8) throw new Error('Use at most eight filters');
|
|
50
|
+
if (!Array.isArray(sort) || sort.length > 4) throw new Error('Use at most four sort columns');
|
|
51
|
+
const literal = request.model !== 'document';
|
|
52
|
+
const params: Record<string, Value> = {};
|
|
53
|
+
const executed: string[] = [];
|
|
54
|
+
const shown: string[] = [];
|
|
55
|
+
const nested = !literal && [...filters.map(filter => filter.column), ...sort.map(item => item.column)].some(column => typeof column === 'string' && column.includes('.'));
|
|
56
|
+
filters.forEach((filter, index) => {
|
|
57
|
+
const field = fieldPath(filter.column, literal, 'studio_row');
|
|
58
|
+
const visible = nested ? field : fieldPath(filter.column, literal);
|
|
59
|
+
if (filter.operator === 'is-null' || filter.operator === 'is-not-null') {
|
|
60
|
+
const predicate = ` IS ${filter.operator === 'is-not-null' ? 'NOT ' : ''}NULL`;
|
|
61
|
+
executed.push(field + predicate);
|
|
62
|
+
shown.push(visible + predicate);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (!Object.hasOwn(OPERATORS, filter.operator) && !isTextOperator(filter.operator)) throw new Error('Choose a supported filter operator');
|
|
66
|
+
const parameter = `$filter${index}`;
|
|
67
|
+
if (isTextOperator(filter.operator)) {
|
|
68
|
+
if (typeof filter.value !== 'string' || filter.value.length > 4096) throw new Error('Text filters need a value of up to 4096 characters');
|
|
69
|
+
const escaped = filter.value.replaceAll('\\', '\\\\').replaceAll('%', '\\%').replaceAll('_', '\\_');
|
|
70
|
+
const pattern = `${filter.operator !== 'starts-with' ? '%' : ''}${escaped}${filter.operator !== 'ends-with' ? '%' : ''}`;
|
|
71
|
+
params[parameter] = pattern;
|
|
72
|
+
executed.push(`${field} LIKE ${parameter} ESCAPE '\\'`);
|
|
73
|
+
shown.push(`${visible} LIKE ${sqlLiteral({ type: 'String', value: pattern })} ESCAPE '\\'`);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const typed = filterValue(filter);
|
|
77
|
+
params[parameter] = decodeValue(typed);
|
|
78
|
+
executed.push(`${field} ${OPERATORS[filter.operator]} ${parameter}`);
|
|
79
|
+
shown.push(`${visible} ${OPERATORS[filter.operator]} ${sqlLiteral(typed)}`);
|
|
80
|
+
});
|
|
81
|
+
for (const item of sort) if (item.direction !== 'asc' && item.direction !== 'desc') throw new Error('Choose ascending or descending order');
|
|
82
|
+
const source = `FROM ${identifier(table)} AS studio_row`;
|
|
83
|
+
const visibleSource = nested ? source : `FROM ${identifier(table)}`;
|
|
84
|
+
const where = executed.length ? ` WHERE ${executed.join(' AND ')}` : '';
|
|
85
|
+
const visibleWhere = shown.length ? ` WHERE ${shown.join(' AND ')}` : '';
|
|
86
|
+
const order = sort.length ? ` ORDER BY ${sort.map(item => `${fieldPath(item.column, literal, 'studio_row')} ${item.direction.toUpperCase()}`).join(', ')}` : '';
|
|
87
|
+
const visibleOrder = sort.length ? ` ORDER BY ${sort.map(item => `${nested ? fieldPath(item.column, literal, 'studio_row') : fieldPath(item.column, literal)} ${item.direction.toUpperCase()}`).join(', ')}` : '';
|
|
88
|
+
const limit = ` LIMIT ${request.pageSize} OFFSET ${(request.page - 1) * request.pageSize}`;
|
|
89
|
+
return {
|
|
90
|
+
count: { sql: `SELECT count(*) AS total ${source}${where}`, params },
|
|
91
|
+
rows: { sql: `SELECT * ${source}${where}${order}${limit}`, params },
|
|
92
|
+
display: `SELECT * ${visibleSource}${visibleWhere}${visibleOrder}${limit}`,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function filterValue(filter: BrowseFilter): PortableValue {
|
|
97
|
+
if (filter.typed) {
|
|
98
|
+
decodeValue(filter.typed);
|
|
99
|
+
return filter.typed;
|
|
100
|
+
}
|
|
101
|
+
if (typeof filter.value !== 'string' || filter.value.length > 4096) throw new Error('Filters need a value of up to 4096 characters');
|
|
102
|
+
const kinds = { text: 'text', integer: 'integer', number: 'number', boolean: 'boolean', record: 'record', auto: 'text' } as const;
|
|
103
|
+
const type = filter.valueType ?? 'auto';
|
|
104
|
+
if (!Object.hasOwn(kinds, type)) throw new Error('Choose a supported filter value type');
|
|
105
|
+
return kindValue(kinds[type], filter.value);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Converts a RomeDB statement result into grid rows. `SELECT *` on a document
|
|
110
|
+
* collection returns one `document` column; its top-level fields become grid
|
|
111
|
+
* columns so collections browse like tables.
|
|
112
|
+
*/
|
|
113
|
+
export function statementResult(columns: string[], rows: PortableValue[][], documents = false): StatementResult {
|
|
114
|
+
const flatten = columns.length === 1 && rows.length > 0 && rows.every(row => row[0]?.type === 'Object') && (documents || columns[0] === 'document');
|
|
115
|
+
if (flatten) {
|
|
116
|
+
const names: string[] = [];
|
|
117
|
+
const seen = new Set<string>();
|
|
118
|
+
for (const row of rows) {
|
|
119
|
+
const value = row[0] as Extract<PortableValue, { type: 'Object' }>;
|
|
120
|
+
for (const key of Object.keys(value.value)) if (!seen.has(key)) { seen.add(key); names.push(key); }
|
|
121
|
+
}
|
|
122
|
+
names.sort((left, right) => left === 'id' ? -1 : right === 'id' ? 1 : 0);
|
|
123
|
+
return { columns: names, rows: rows.map(row => ({ ...(row[0] as Extract<PortableValue, { type: 'Object' }>).value })), affectedRows: 0, truncated: false };
|
|
124
|
+
}
|
|
125
|
+
const unique = columns.map((name, index) => columns.indexOf(name) === index ? name : `${name} (${index + 1})`);
|
|
126
|
+
return {
|
|
127
|
+
columns: unique,
|
|
128
|
+
rows: rows.map(row => Object.fromEntries(unique.map((name, index) => [name, row[index] ?? { type: 'Null' }])) as GridRow),
|
|
129
|
+
affectedRows: 0,
|
|
130
|
+
truncated: false,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function identifier(name: string): string {
|
|
135
|
+
if (typeof name !== 'string' || !name || name.length > 1024 || name.includes('\0') || /^(?:__romedb_|__turso_internal_|sqlite_)/i.test(name)) throw new Error('Choose a logical object or field name');
|
|
136
|
+
return quoteIdentifier(name);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function fieldPath(field: string, literal: boolean, alias?: string): string {
|
|
140
|
+
const path = (literal ? [field] : field.split('.')).map(identifier).join('.');
|
|
141
|
+
return alias ? `${alias}.${path}` : path;
|
|
142
|
+
}
|