@pgxsinkit/pgwasm-repl 0.5.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/dist/index.js ADDED
@@ -0,0 +1,840 @@
1
+ import { defaultKeymap } from "@codemirror/commands";
2
+ import { PostgreSQL, keywordCompletionSource, schemaCompletionSource } from "@codemirror/lang-sql";
3
+ import { keymap } from "@codemirror/view";
4
+ import { githubDark, githubDarkInit, githubLight, githubLightInit } from "@uiw/codemirror-theme-github";
5
+ import CodeMirror from "@uiw/react-codemirror";
6
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
+ import { describe } from "psql-describe";
9
+ import { LanguageSupport } from "@codemirror/language";
10
+ //#region src/repl-table.tsx
11
+ var ROW_INCREMENT = 100;
12
+ var MAX_CELL_LENGTH = 200;
13
+ function cellClass(value) {
14
+ if (value === null) return "pgwasm-repl-null";
15
+ if (typeof value === "number") return "pgwasm-repl-number";
16
+ if (typeof value === "boolean") return "pgwasm-repl-boolean";
17
+ return "";
18
+ }
19
+ function cellValue(value) {
20
+ let text;
21
+ if (value === null) text = "null";
22
+ else if (value === void 0) text = "undefined";
23
+ else if (typeof value === "string") text = value;
24
+ else if (typeof value === "number" || typeof value === "bigint") text = value.toString();
25
+ else if (typeof value === "boolean") text = value ? "true" : "false";
26
+ else if (value instanceof Date) text = value.toISOString();
27
+ else if (Array.isArray(value)) text = `[${value.map(cellValue).join(", ")}]`;
28
+ else if (ArrayBuffer.isView(value)) text = `${value.byteLength} bytes`;
29
+ else if (typeof value === "object") text = JSON.stringify(value);
30
+ else if (typeof value === "symbol") text = value.toString();
31
+ else text = "[function]";
32
+ return text.length > MAX_CELL_LENGTH ? `${text.slice(0, MAX_CELL_LENGTH)}…` : text;
33
+ }
34
+ /** One result as a table, a hundred rows at a time. */
35
+ function ReplTable({ result }) {
36
+ const [maxRows, setMaxRows] = useState(ROW_INCREMENT);
37
+ const rows = result.rows.slice(0, maxRows);
38
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
39
+ className: "pgwasm-repl-table-scroll",
40
+ children: /* @__PURE__ */ jsxs("table", {
41
+ className: "pgwasm-repl-table",
42
+ children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: result.fields.map((field, index) => /* @__PURE__ */ jsx("th", { children: field.name }, `${index}:${field.name}`)) }) }), /* @__PURE__ */ jsx("tbody", { children: rows.map((row, rowIndex) => /* @__PURE__ */ jsx("tr", { children: row.map((value, columnIndex) => /* @__PURE__ */ jsx("td", {
43
+ className: cellClass(value),
44
+ children: cellValue(value)
45
+ }, columnIndex)) }, rowIndex)) })]
46
+ })
47
+ }), /* @__PURE__ */ jsxs("div", {
48
+ className: "pgwasm-repl-table-row-count",
49
+ children: [
50
+ result.rows.length > maxRows ? `${maxRows} of ` : "",
51
+ result.rows.length,
52
+ " rows",
53
+ " ",
54
+ result.rows.length > maxRows && /* @__PURE__ */ jsx("button", {
55
+ type: "button",
56
+ className: "pgwasm-repl-show-more",
57
+ onClick: () => setMaxRows((previous) => previous + ROW_INCREMENT),
58
+ children: "Show more"
59
+ })
60
+ ]
61
+ })] });
62
+ }
63
+ //#endregion
64
+ //#region src/repl-response.tsx
65
+ function ResultLine({ result }) {
66
+ return /* @__PURE__ */ jsxs("div", {
67
+ className: "pgwasm-repl-line",
68
+ children: [
69
+ result.title !== void 0 && /* @__PURE__ */ jsx("div", {
70
+ className: "pgwasm-repl-title",
71
+ children: result.title
72
+ }),
73
+ result.fields.length > 0 ? /* @__PURE__ */ jsx(ReplTable, { result }) : /* @__PURE__ */ jsx("div", {
74
+ className: "pgwasm-repl-null",
75
+ children: "null"
76
+ }),
77
+ result.footers !== void 0 && result.footers.length > 0 && /* @__PURE__ */ jsx("pre", {
78
+ className: "pgwasm-repl-footers",
79
+ children: result.footers.join("\n")
80
+ })
81
+ ]
82
+ });
83
+ }
84
+ /** One input and what came back for it. */
85
+ function ReplResponseView({ response, showTime }) {
86
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
87
+ /* @__PURE__ */ jsx("pre", {
88
+ className: "pgwasm-repl-line pgwasm-repl-query",
89
+ children: response.query
90
+ }),
91
+ response.text !== void 0 && /* @__PURE__ */ jsx("div", {
92
+ className: "pgwasm-repl-line pgwasm-repl-text",
93
+ children: response.text
94
+ }),
95
+ response.error !== void 0 ? /* @__PURE__ */ jsx("div", {
96
+ className: "pgwasm-repl-line pgwasm-repl-error",
97
+ children: response.error
98
+ }) : response.results?.map((result, index) => /* @__PURE__ */ jsx(ResultLine, { result }, index)),
99
+ /* @__PURE__ */ jsxs("div", {
100
+ className: "pgwasm-repl-divider",
101
+ children: [/* @__PURE__ */ jsx("hr", {}), showTime && /* @__PURE__ */ jsxs("div", {
102
+ className: "pgwasm-repl-time",
103
+ children: [response.time.toFixed(1), "ms"]
104
+ })]
105
+ })
106
+ ] });
107
+ }
108
+ //#endregion
109
+ //#region src/run-query.ts
110
+ var errorMessage = (error) => error instanceof Error ? error.message : String(error);
111
+ /** Rows asked for with `rowMode: "array"` are arrays; anything else is shown as one value. */
112
+ function asRows(result) {
113
+ return {
114
+ rows: result.rows.map((row) => Array.isArray(row) ? row : [row]),
115
+ fields: result.fields
116
+ };
117
+ }
118
+ /**
119
+ * Run what was typed: psql's `\d` family of commands through psql-describe, anything else as SQL (every
120
+ * statement of it, rows as arrays). A failure is a response with its message, never a throw.
121
+ */
122
+ async function runQuery(query, pg) {
123
+ if (query.trim().startsWith("\\")) return await runDescribe(query, pg);
124
+ const start = performance.now();
125
+ try {
126
+ return {
127
+ query,
128
+ results: (await pg.exec(query, { rowMode: "array" })).map(asRows),
129
+ time: performance.now() - start
130
+ };
131
+ } catch (error) {
132
+ return {
133
+ query,
134
+ error: errorMessage(error),
135
+ time: performance.now() - start
136
+ };
137
+ }
138
+ }
139
+ /** The text type's OID: psql-describe hands its tables over as text. */
140
+ var TEXT_OID = 25;
141
+ /** A table psql-describe produced (its cells row by row), as rows to show. */
142
+ function describedTable(item) {
143
+ const { title, headers, cells, footers, ncolumns } = item;
144
+ if (!Array.isArray(headers) || !Array.isArray(cells) || typeof ncolumns !== "number" || ncolumns < 1) return;
145
+ const rows = [];
146
+ for (let at = 0; at < cells.length; at += ncolumns) rows.push(cells.slice(at, at + ncolumns));
147
+ return {
148
+ rows,
149
+ fields: headers.map((name) => ({
150
+ name: String(name),
151
+ dataTypeID: TEXT_OID
152
+ })),
153
+ ...typeof title === "string" ? { title } : {},
154
+ ...Array.isArray(footers) ? { footers: footers.map(String) } : {}
155
+ };
156
+ }
157
+ /**
158
+ * Run a psql describe command (`\d`, `\dt`, `\df+ pattern`, …): each table psql-describe produces is a
159
+ * result, with its caption and footers; its messages are the response's text.
160
+ */
161
+ async function runDescribe(query, pg) {
162
+ const start = performance.now();
163
+ const items = [];
164
+ try {
165
+ const { promise } = describe(query, "postgres", async (sql) => {
166
+ const [result] = await pg.exec(sql, { rowMode: "array" });
167
+ const rows = asRows(result ?? {
168
+ rows: [],
169
+ fields: []
170
+ });
171
+ return {
172
+ rows: rows.rows,
173
+ fields: rows.fields,
174
+ rowCount: rows.rows.length
175
+ };
176
+ }, (item) => {
177
+ items.push(item);
178
+ });
179
+ await promise;
180
+ } catch (error) {
181
+ return {
182
+ query,
183
+ error: errorMessage(error),
184
+ time: performance.now() - start
185
+ };
186
+ }
187
+ const time = performance.now() - start;
188
+ const texts = items.filter((item) => typeof item === "string");
189
+ const error = texts.find((text) => text.startsWith("ERROR:"));
190
+ if (error !== void 0) return {
191
+ query,
192
+ error,
193
+ time
194
+ };
195
+ const results = items.flatMap((item) => {
196
+ const table = typeof item === "string" ? void 0 : describedTable(item);
197
+ return table === void 0 ? [] : [table];
198
+ });
199
+ if (texts.length === 0 && results.length === 0) return {
200
+ query,
201
+ error: "No output",
202
+ time
203
+ };
204
+ return {
205
+ query,
206
+ ...texts.length > 0 ? { text: texts.join("\n") } : {},
207
+ ...results.length > 0 ? { results } : {},
208
+ time
209
+ };
210
+ }
211
+ /** Every table's columns, by `schema.table`, for autocompletion. */
212
+ async function getSchema(pg) {
213
+ const result = await pg.query(`SELECT table_schema || '.' || table_name, column_name::text
214
+ FROM information_schema.columns
215
+ ORDER BY table_schema, table_name, ordinal_position`, [], { rowMode: "array" });
216
+ const schema = {};
217
+ for (const [table, column] of asRows(result).rows) if (typeof table === "string" && typeof column === "string") (schema[table] ??= []).push(column);
218
+ return schema;
219
+ }
220
+ //#endregion
221
+ //#region src/sql-support.ts
222
+ /** psql's describe commands, offered after a backslash. */
223
+ var describeCompletions = [
224
+ {
225
+ label: "\\d",
226
+ type: "function",
227
+ displayLabel: "\\d[S+] [ pattern ]",
228
+ detail: "PSQL Describe"
229
+ },
230
+ {
231
+ label: "\\da",
232
+ type: "function",
233
+ displayLabel: "\\da[S] [ pattern ]",
234
+ detail: "Lists aggregate functions"
235
+ },
236
+ {
237
+ label: "\\dA",
238
+ type: "function",
239
+ displayLabel: "\\dA[+] [ pattern ]",
240
+ detail: "Lists access methods"
241
+ },
242
+ {
243
+ label: "\\dAc",
244
+ type: "function",
245
+ displayLabel: "\\dAc[+] [access-method-pattern [input-type-pattern]]",
246
+ detail: "Lists operator classes"
247
+ },
248
+ {
249
+ label: "\\dAf",
250
+ type: "function",
251
+ displayLabel: "\\dAf[+] [access-method-pattern [input-type-pattern]]",
252
+ detail: "Lists operator families"
253
+ },
254
+ {
255
+ label: "\\dAo",
256
+ type: "function",
257
+ displayLabel: "\\dAo[+] [access-method-pattern [operator-family-pattern]]",
258
+ detail: "Lists operators associated with operator families"
259
+ },
260
+ {
261
+ label: "\\dAp",
262
+ type: "function",
263
+ displayLabel: "\\dAp[+] [access-method-pattern [operator-family-pattern]]",
264
+ detail: "Lists support functions associated with operator families"
265
+ },
266
+ {
267
+ label: "\\db",
268
+ type: "function",
269
+ displayLabel: "\\db[+] [ pattern ]",
270
+ detail: "Lists tablespaces"
271
+ },
272
+ {
273
+ label: "\\dc",
274
+ type: "function",
275
+ displayLabel: "\\dc[S+] [ pattern ]",
276
+ detail: "Lists conversions between character-set encodings"
277
+ },
278
+ {
279
+ label: "\\dconfig",
280
+ type: "function",
281
+ displayLabel: "\\dconfig[+] [ pattern ]",
282
+ detail: "Lists server configuration parameters and their values"
283
+ },
284
+ {
285
+ label: "\\dC",
286
+ type: "function",
287
+ displayLabel: "\\dC[+] [ pattern ]",
288
+ detail: "Lists type casts"
289
+ },
290
+ {
291
+ label: "\\dd",
292
+ type: "function",
293
+ displayLabel: "\\dd[S] [ pattern ]",
294
+ detail: "Shows the descriptions of objects of type constraint, operator class, operator family, rule, and trigger"
295
+ },
296
+ {
297
+ label: "\\dD",
298
+ type: "function",
299
+ displayLabel: "\\dD[S+] [ pattern ]",
300
+ detail: "Lists domains"
301
+ },
302
+ {
303
+ label: "\\ddp",
304
+ type: "function",
305
+ displayLabel: "\\ddp [ pattern ]",
306
+ detail: "Lists default access privilege settings"
307
+ },
308
+ {
309
+ label: "\\dE",
310
+ type: "function",
311
+ displayLabel: "\\dE[S+] [ pattern ]",
312
+ detail: "Lists foreign tables"
313
+ },
314
+ {
315
+ label: "\\di",
316
+ type: "function",
317
+ displayLabel: "\\di[S+] [ pattern ]",
318
+ detail: "Lists indexes"
319
+ },
320
+ {
321
+ label: "\\dm",
322
+ type: "function",
323
+ displayLabel: "\\dm[S+] [ pattern ]",
324
+ detail: "Lists materialized views"
325
+ },
326
+ {
327
+ label: "\\ds",
328
+ type: "function",
329
+ displayLabel: "\\ds[S+] [ pattern ]",
330
+ detail: "Lists sequences"
331
+ },
332
+ {
333
+ label: "\\dt",
334
+ type: "function",
335
+ displayLabel: "\\dt[S+] [ pattern ]",
336
+ detail: "Lists tables"
337
+ },
338
+ {
339
+ label: "\\dv",
340
+ type: "function",
341
+ displayLabel: "\\dv[S+] [ pattern ]",
342
+ detail: "Lists views"
343
+ },
344
+ {
345
+ label: "\\des",
346
+ type: "function",
347
+ displayLabel: "\\des[+] [ pattern ]",
348
+ detail: "Lists foreign servers"
349
+ },
350
+ {
351
+ label: "\\det",
352
+ type: "function",
353
+ displayLabel: "\\det[+] [ pattern ]",
354
+ detail: "Lists foreign tables"
355
+ },
356
+ {
357
+ label: "\\deu",
358
+ type: "function",
359
+ displayLabel: "\\deu[+] [ pattern ]",
360
+ detail: "Lists user mappings"
361
+ },
362
+ {
363
+ label: "\\dew",
364
+ type: "function",
365
+ displayLabel: "\\dew[+] [ pattern ]",
366
+ detail: "Lists foreign-data wrappers"
367
+ },
368
+ {
369
+ label: "\\df",
370
+ type: "function",
371
+ displayLabel: "\\df[anptwS+] [ pattern [ arg_pattern ... ] ]",
372
+ detail: "Lists functions"
373
+ },
374
+ {
375
+ label: "\\dF",
376
+ type: "function",
377
+ displayLabel: "\\dF[+] [ pattern ]",
378
+ detail: "Lists text search configurations"
379
+ },
380
+ {
381
+ label: "\\dFd",
382
+ type: "function",
383
+ displayLabel: "\\dFd[+] [ pattern ]",
384
+ detail: "Lists text search dictionaries"
385
+ },
386
+ {
387
+ label: "\\dFp",
388
+ type: "function",
389
+ displayLabel: "\\dFp[+] [ pattern ]",
390
+ detail: "Lists text search parsers"
391
+ },
392
+ {
393
+ label: "\\dFt",
394
+ type: "function",
395
+ displayLabel: "\\dFt[+] [ pattern ]",
396
+ detail: "Lists text search templates"
397
+ },
398
+ {
399
+ label: "\\dg",
400
+ type: "function",
401
+ displayLabel: "\\dg[S+] [ pattern ]",
402
+ detail: "Lists database roles"
403
+ },
404
+ {
405
+ label: "\\dl",
406
+ type: "function",
407
+ displayLabel: "\\dl[+] ",
408
+ detail: "List large objects"
409
+ },
410
+ {
411
+ label: "\\dL",
412
+ type: "function",
413
+ displayLabel: "\\dL[S+] [ pattern ]",
414
+ detail: "Lists procedural languages"
415
+ },
416
+ {
417
+ label: "\\dn",
418
+ type: "function",
419
+ displayLabel: "\\dn[S+] [ pattern ]",
420
+ detail: "Lists schemas"
421
+ },
422
+ {
423
+ label: "\\do",
424
+ type: "function",
425
+ displayLabel: "\\do[S+] [ pattern [ arg_pattern [ arg_pattern ] ] ]",
426
+ detail: "Lists operators with their operand and result types"
427
+ },
428
+ {
429
+ label: "\\dO",
430
+ type: "function",
431
+ displayLabel: "\\dO[S+] [ pattern ]",
432
+ detail: "Lists collations"
433
+ },
434
+ {
435
+ label: "\\dp",
436
+ type: "function",
437
+ displayLabel: "\\dp[S] [ pattern ]",
438
+ detail: "Lists tables, views and sequences with their associated access privileges"
439
+ },
440
+ {
441
+ label: "\\dP",
442
+ type: "function",
443
+ displayLabel: "\\dP[itn+] [ pattern ]",
444
+ detail: "Lists partitioned relations"
445
+ },
446
+ {
447
+ label: "\\drds",
448
+ type: "function",
449
+ displayLabel: "\\drds [ role-pattern [ database-pattern ] ]",
450
+ detail: "Lists defined configuration settings"
451
+ },
452
+ {
453
+ label: "\\drg",
454
+ type: "function",
455
+ displayLabel: "\\drg[S] [ pattern ]",
456
+ detail: "Lists information about each granted role membership"
457
+ },
458
+ {
459
+ label: "\\dRp",
460
+ type: "function",
461
+ displayLabel: "\\dRp[+] [ pattern ]",
462
+ detail: "Lists replication publications"
463
+ },
464
+ {
465
+ label: "\\dRs",
466
+ type: "function",
467
+ displayLabel: "\\dRs[+] [ pattern ]",
468
+ detail: "Lists replication subscriptions"
469
+ },
470
+ {
471
+ label: "\\dT",
472
+ type: "function",
473
+ displayLabel: "\\dT[S+] [ pattern ]",
474
+ detail: "Lists data types"
475
+ },
476
+ {
477
+ label: "\\du",
478
+ type: "function",
479
+ displayLabel: "\\du[S+] [ pattern ]",
480
+ detail: "Lists database roles"
481
+ },
482
+ {
483
+ label: "\\dx",
484
+ type: "function",
485
+ displayLabel: "\\dx[+] [ pattern ]",
486
+ detail: "Lists installed extensions"
487
+ },
488
+ {
489
+ label: "\\dX",
490
+ type: "function",
491
+ displayLabel: "\\dX [ pattern ]",
492
+ detail: "Lists extended statistics"
493
+ },
494
+ {
495
+ label: "\\dy",
496
+ type: "function",
497
+ displayLabel: "\\dy[+] [ pattern ]",
498
+ detail: "Lists event triggers"
499
+ }
500
+ ];
501
+ function describeCompletionSource(context) {
502
+ const word = context.matchBefore(/\\\w*/);
503
+ if (!word || word.from === word.to) return null;
504
+ return {
505
+ from: word.from,
506
+ options: describeCompletions
507
+ };
508
+ }
509
+ /**
510
+ * `sql()` from `@codemirror/lang-sql`, with one more completion source: psql's `\d` family of commands.
511
+ */
512
+ function sqlSupport(config = {}) {
513
+ const dialect = config.dialect ?? PostgreSQL;
514
+ return new LanguageSupport(dialect.language, [
515
+ config.schema ? dialect.language.data.of({ autocomplete: schemaCompletionSource(config) }) : [],
516
+ dialect.language.data.of({ autocomplete: keywordCompletionSource(dialect, config.upperCaseKeywords === true) }),
517
+ dialect.language.data.of({ autocomplete: describeCompletionSource })
518
+ ]);
519
+ }
520
+ //#endregion
521
+ //#region src/styles.ts
522
+ /**
523
+ * The REPL's stylesheet. It ships as a string, not a `.css` import (which only some bundlers can load):
524
+ * the component renders it as a React-hoisted `<style>`, which React inserts into the document once,
525
+ * however many REPLs are mounted. Every class is prefixed `pgwasm-repl-`. `--pgwasm-repl-font-size`
526
+ * sets the size; the colours and borders follow the editor's theme.
527
+ */
528
+ var REPL_STYLESHEET_ID = "pgwasm-repl";
529
+ var REPL_STYLES = `
530
+ .pgwasm-repl-root {
531
+ --pgwasm-repl-fg: var(--pgwasm-repl-foreground-color);
532
+ --pgwasm-repl-bg: var(--pgwasm-repl-background-color);
533
+ --pgwasm-repl-size: var(--pgwasm-repl-font-size, 12px);
534
+ display: flex;
535
+ flex-direction: column;
536
+ height: 100%;
537
+ width: 100%;
538
+ font-size: var(--pgwasm-repl-size);
539
+ color: var(--pgwasm-repl-fg);
540
+ background-color: var(--pgwasm-repl-bg);
541
+ }
542
+ .pgwasm-repl-loading-msg {
543
+ opacity: 0.5;
544
+ }
545
+ .pgwasm-repl-root table {
546
+ font-size: var(--pgwasm-repl-size);
547
+ }
548
+ .pgwasm-repl-root-border {
549
+ border: var(--pgwasm-repl-border);
550
+ }
551
+ .pgwasm-repl-output {
552
+ flex: 1;
553
+ overflow-y: auto;
554
+ padding: 0.5em 0 0.5em 0.5em;
555
+ border-bottom: var(--pgwasm-repl-border);
556
+ }
557
+ .pgwasm-repl-root hr {
558
+ margin: 0.5em 0;
559
+ border: none;
560
+ border-top: var(--pgwasm-repl-border);
561
+ }
562
+ .pgwasm-repl-input {
563
+ display: flex;
564
+ min-height: 60px;
565
+ max-height: 50%;
566
+ width: 100%;
567
+ }
568
+ .pgwasm-repl-input .cm-editor.cm-focused {
569
+ outline: none;
570
+ }
571
+ .pgwasm-repl-input-loading {
572
+ pointer-events: none;
573
+ }
574
+ .pgwasm-repl-table-scroll {
575
+ overflow-x: auto;
576
+ }
577
+ .pgwasm-repl-table {
578
+ border-collapse: collapse;
579
+ }
580
+ .pgwasm-repl-line {
581
+ margin: 0 0 0 1em;
582
+ position: relative;
583
+ }
584
+ .pgwasm-repl-line::before {
585
+ display: block;
586
+ width: 0.7em;
587
+ text-align: center;
588
+ content: "\\276E";
589
+ margin-right: 0.5em;
590
+ color: var(--pgwasm-repl-border-color);
591
+ position: absolute;
592
+ left: -1em;
593
+ }
594
+ .pgwasm-repl-line + .pgwasm-repl-line {
595
+ margin-top: 0.25em;
596
+ }
597
+ .pgwasm-repl-query {
598
+ margin: 0 0 0.25em 1em;
599
+ }
600
+ .pgwasm-repl-query::before {
601
+ content: "\\276F";
602
+ }
603
+ .pgwasm-repl-table th {
604
+ text-align: center;
605
+ font-weight: 600;
606
+ }
607
+ .pgwasm-repl-table td {
608
+ text-align: left;
609
+ max-width: 400px;
610
+ overflow: hidden;
611
+ text-overflow: ellipsis;
612
+ }
613
+ .pgwasm-repl-table .pgwasm-repl-number {
614
+ text-align: right;
615
+ font-variant-numeric: tabular-nums;
616
+ }
617
+ .pgwasm-repl-table .pgwasm-repl-boolean {
618
+ text-align: center;
619
+ }
620
+ .pgwasm-repl-table th,
621
+ .pgwasm-repl-table td {
622
+ padding: 0 0.2em;
623
+ border: var(--pgwasm-repl-border);
624
+ }
625
+ .pgwasm-repl-divider {
626
+ font-size: 9px;
627
+ display: flex;
628
+ align-items: center;
629
+ color: var(--pgwasm-repl-border-color);
630
+ padding-right: 0.5em;
631
+ }
632
+ .pgwasm-repl-divider hr {
633
+ margin: 0;
634
+ flex-grow: 1;
635
+ }
636
+ .pgwasm-repl-time {
637
+ margin: 0 0.5em;
638
+ }
639
+ .pgwasm-repl-null {
640
+ color: var(--pgwasm-repl-border-color);
641
+ }
642
+ .pgwasm-repl-error {
643
+ color: #c33;
644
+ }
645
+ .pgwasm-repl-error::before {
646
+ content: "!";
647
+ color: #c33;
648
+ font-weight: bold;
649
+ }
650
+ .pgwasm-repl-title {
651
+ font-weight: 600;
652
+ }
653
+ .pgwasm-repl-footers {
654
+ margin: 0.25em 0 0;
655
+ }
656
+ .pgwasm-repl-show-more {
657
+ border: none;
658
+ background: none;
659
+ padding: 0;
660
+ font: inherit;
661
+ color: inherit;
662
+ text-decoration: underline;
663
+ cursor: pointer;
664
+ }
665
+ `;
666
+ //#endregion
667
+ //#region src/repl.tsx
668
+ var baseKeymap = defaultKeymap.filter((binding) => binding.key !== "Enter");
669
+ var defaultLightThemeInit = githubLightInit;
670
+ var defaultLightTheme = githubLight;
671
+ var defaultDarkThemeInit = githubDarkInit;
672
+ var defaultDarkTheme = githubDark;
673
+ var prefersDark = () => globalThis.matchMedia?.("(prefers-color-scheme: dark)").matches === true;
674
+ /** An interactive SQL prompt on a database: psql's `\d` commands, autocompletion, input history. */
675
+ function Repl({ pg, border = false, lightTheme = defaultLightTheme, darkTheme = defaultDarkTheme, theme = "auto", showTime = false, disableUpdateSchema = false }) {
676
+ const [value, setValue] = useState("");
677
+ const [valueBeforeHistory, setValueBeforeHistory] = useState("");
678
+ const [historyPosition, setHistoryPosition] = useState(-1);
679
+ const [readyPg, setReadyPg] = useState(void 0);
680
+ const loading = readyPg !== pg;
681
+ const [output, setOutput] = useState([]);
682
+ const outputRef = useRef(null);
683
+ const [schema, setSchema] = useState({});
684
+ const editorRef = useRef(null);
685
+ const [systemDark, setSystemDark] = useState(prefersDark);
686
+ const themeToUse = theme === "dark" || theme === "auto" && systemDark ? darkTheme : lightTheme;
687
+ const [styles, setStyles] = useState({});
688
+ const refreshSchema = useCallback(() => {
689
+ getSchema(pg).then(setSchema, () => void 0);
690
+ }, [pg]);
691
+ const extractStyles = useCallback(() => {
692
+ const editor = editorRef.current?.editor?.querySelector(".cm-editor");
693
+ const gutters = editor?.querySelector(".cm-gutters");
694
+ if (!editor || !gutters) return;
695
+ const editorStyle = globalThis.getComputedStyle(editor);
696
+ const gutterStyle = globalThis.getComputedStyle(gutters);
697
+ const foreground = editorStyle.color;
698
+ const borderWidth = Number.parseInt(gutterStyle.borderRightWidth, 10) || 0;
699
+ const borderColor = borderWidth ? gutterStyle.borderRightColor : foreground.replace("rgb", "rgba").replace(")", ", 0.15)");
700
+ setStyles({
701
+ "--pgwasm-repl-foreground-color": foreground,
702
+ "--pgwasm-repl-background-color": editorStyle.backgroundColor,
703
+ "--pgwasm-repl-border": borderWidth ? gutterStyle.borderRight : `1px solid ${borderColor}`,
704
+ "--pgwasm-repl-gutter-border": gutterStyle.borderRight,
705
+ "--pgwasm-repl-border-color": borderColor
706
+ });
707
+ }, []);
708
+ useEffect(() => {
709
+ let ignore = false;
710
+ (pg.waitReady ?? Promise.resolve()).then(() => {
711
+ if (!ignore) setReadyPg(pg);
712
+ }, () => void 0);
713
+ return () => {
714
+ ignore = true;
715
+ };
716
+ }, [pg]);
717
+ useEffect(() => {
718
+ if (theme !== "auto") return;
719
+ const query = globalThis.matchMedia?.("(prefers-color-scheme: dark)");
720
+ if (query === void 0) return;
721
+ const listener = (event) => setSystemDark(event.matches);
722
+ query.addEventListener("change", listener);
723
+ return () => query.removeEventListener("change", listener);
724
+ }, [theme]);
725
+ useEffect(() => {
726
+ const timer = setTimeout(extractStyles, 0);
727
+ return () => clearTimeout(timer);
728
+ }, [themeToUse, extractStyles]);
729
+ useEffect(() => {
730
+ const element = outputRef.current;
731
+ if (element) element.scrollTop = element.scrollHeight;
732
+ }, [output]);
733
+ const onChange = useCallback((next) => {
734
+ extractStyles();
735
+ setValue(next);
736
+ if (historyPosition === -1) setValueBeforeHistory(next);
737
+ }, [extractStyles, historyPosition]);
738
+ const extensions = useMemo(() => {
739
+ const moveHistory = (step) => {
740
+ const next = Math.max(-1, Math.min(output.length - 1, historyPosition + step));
741
+ if (next !== historyPosition) {
742
+ setHistoryPosition(next);
743
+ setValue(next === -1 ? valueBeforeHistory : output[output.length - next - 1]?.query ?? "");
744
+ }
745
+ return true;
746
+ };
747
+ return [keymap.of([
748
+ {
749
+ key: "Enter",
750
+ preventDefault: true,
751
+ run: () => {
752
+ if (value.trim() === "") return false;
753
+ runQuery(value, pg).then((response) => {
754
+ setOutput((previous) => [...previous, response]);
755
+ if (!disableUpdateSchema) refreshSchema();
756
+ });
757
+ setHistoryPosition(-1);
758
+ setValueBeforeHistory("");
759
+ setValue("");
760
+ return true;
761
+ }
762
+ },
763
+ {
764
+ key: "ArrowUp",
765
+ run: (view) => {
766
+ const state = view.state;
767
+ if (state.doc.lineAt(state.selection.main.head).number !== 1) return false;
768
+ return moveHistory(1);
769
+ }
770
+ },
771
+ {
772
+ key: "ArrowDown",
773
+ run: (view) => {
774
+ const state = view.state;
775
+ if (state.doc.lineAt(state.selection.main.head).number !== state.doc.lines) return false;
776
+ return moveHistory(-1);
777
+ }
778
+ },
779
+ ...baseKeymap
780
+ ]), sqlSupport({
781
+ dialect: PostgreSQL,
782
+ schema,
783
+ tables: [{
784
+ label: "d",
785
+ displayLabel: "\\d"
786
+ }],
787
+ defaultSchema: "public"
788
+ })];
789
+ }, [
790
+ pg,
791
+ schema,
792
+ value,
793
+ valueBeforeHistory,
794
+ historyPosition,
795
+ output,
796
+ disableUpdateSchema,
797
+ refreshSchema
798
+ ]);
799
+ return /* @__PURE__ */ jsxs("div", {
800
+ className: border ? "pgwasm-repl-root pgwasm-repl-root-border" : "pgwasm-repl-root",
801
+ style: styles,
802
+ children: [
803
+ /* @__PURE__ */ jsx("style", {
804
+ href: REPL_STYLESHEET_ID,
805
+ precedence: "default",
806
+ children: REPL_STYLES
807
+ }),
808
+ /* @__PURE__ */ jsxs("div", {
809
+ className: "pgwasm-repl-output",
810
+ ref: outputRef,
811
+ children: [loading && /* @__PURE__ */ jsx("div", {
812
+ className: "pgwasm-repl-loading-msg",
813
+ children: "Loading..."
814
+ }), output.map((response, index) => /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(ReplResponseView, {
815
+ response,
816
+ showTime
817
+ }) }, index))]
818
+ }),
819
+ /* @__PURE__ */ jsx(CodeMirror, {
820
+ ref: editorRef,
821
+ className: loading ? "pgwasm-repl-input pgwasm-repl-input-loading" : "pgwasm-repl-input",
822
+ width: "100%",
823
+ value,
824
+ basicSetup: { defaultKeymap: false },
825
+ extensions,
826
+ theme: themeToUse,
827
+ onChange,
828
+ editable: !loading,
829
+ onCreateEditor: () => {
830
+ extractStyles();
831
+ refreshSchema();
832
+ }
833
+ })
834
+ ]
835
+ });
836
+ }
837
+ //#endregion
838
+ export { Repl, defaultDarkTheme, defaultDarkThemeInit, defaultLightTheme, defaultLightThemeInit };
839
+
840
+ //# sourceMappingURL=index.js.map