@observablehq/notebook-kit 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +7 -0
  3. package/dist/bin/build.d.ts +2 -0
  4. package/dist/bin/build.js +63 -0
  5. package/dist/bin/download.d.ts +2 -0
  6. package/dist/bin/download.js +49 -0
  7. package/dist/bin/notebooks.d.ts +2 -0
  8. package/dist/bin/notebooks.js +33 -0
  9. package/dist/bin/preview.d.ts +2 -0
  10. package/dist/bin/preview.js +48 -0
  11. package/dist/package.json +73 -0
  12. package/dist/src/index.d.ts +5 -0
  13. package/dist/src/index.js +5 -0
  14. package/dist/src/javascript/assignments.d.ts +2 -0
  15. package/dist/src/javascript/assignments.js +37 -0
  16. package/dist/src/javascript/assignments.test.d.ts +1 -0
  17. package/dist/src/javascript/assignments.test.js +33 -0
  18. package/dist/src/javascript/awaits.d.ts +2 -0
  19. package/dist/src/javascript/awaits.js +23 -0
  20. package/dist/src/javascript/awaits.test.d.ts +1 -0
  21. package/dist/src/javascript/awaits.test.js +22 -0
  22. package/dist/src/javascript/declarations.d.ts +2 -0
  23. package/dist/src/javascript/declarations.js +45 -0
  24. package/dist/src/javascript/files.d.ts +3 -0
  25. package/dist/src/javascript/files.js +18 -0
  26. package/dist/src/javascript/globals.d.ts +1 -0
  27. package/dist/src/javascript/globals.js +86 -0
  28. package/dist/src/javascript/imports/jsr.d.ts +2 -0
  29. package/dist/src/javascript/imports/jsr.js +6 -0
  30. package/dist/src/javascript/imports/npm.d.ts +2 -0
  31. package/dist/src/javascript/imports/npm.js +47 -0
  32. package/dist/src/javascript/imports/npm.test.d.ts +1 -0
  33. package/dist/src/javascript/imports/npm.test.js +32 -0
  34. package/dist/src/javascript/imports/observable.d.ts +8 -0
  35. package/dist/src/javascript/imports/observable.js +64 -0
  36. package/dist/src/javascript/imports/observable.test.d.ts +1 -0
  37. package/dist/src/javascript/imports/observable.test.js +13 -0
  38. package/dist/src/javascript/imports.d.ts +21 -0
  39. package/dist/src/javascript/imports.js +146 -0
  40. package/dist/src/javascript/observable.d.ts +2 -0
  41. package/dist/src/javascript/observable.js +72 -0
  42. package/dist/src/javascript/parse.d.ts +11 -0
  43. package/dist/src/javascript/parse.js +53 -0
  44. package/dist/src/javascript/references.d.ts +8 -0
  45. package/dist/src/javascript/references.js +129 -0
  46. package/dist/src/javascript/references.test.d.ts +1 -0
  47. package/dist/src/javascript/references.test.js +38 -0
  48. package/dist/src/javascript/sourcemap.d.ts +21 -0
  49. package/dist/src/javascript/sourcemap.js +143 -0
  50. package/dist/src/javascript/sourcemap.test.d.ts +1 -0
  51. package/dist/src/javascript/sourcemap.test.js +88 -0
  52. package/dist/src/javascript/strings.d.ts +8 -0
  53. package/dist/src/javascript/strings.js +42 -0
  54. package/dist/src/javascript/strings.test.d.ts +1 -0
  55. package/dist/src/javascript/strings.test.js +31 -0
  56. package/dist/src/javascript/syntaxError.d.ts +2 -0
  57. package/dist/src/javascript/syntaxError.js +5 -0
  58. package/dist/src/javascript/template.d.ts +3 -0
  59. package/dist/src/javascript/template.js +141 -0
  60. package/dist/src/javascript/template.test.d.ts +1 -0
  61. package/dist/src/javascript/template.test.js +32 -0
  62. package/dist/src/javascript/transpile.d.ts +25 -0
  63. package/dist/src/javascript/transpile.js +42 -0
  64. package/dist/src/javascript/transpile.test.d.ts +1 -0
  65. package/dist/src/javascript/transpile.test.js +29 -0
  66. package/dist/src/javascript/walk.d.ts +5 -0
  67. package/dist/src/javascript/walk.js +13 -0
  68. package/dist/src/lib/notebook.d.ts +35 -0
  69. package/dist/src/lib/notebook.js +19 -0
  70. package/dist/src/lib/notebook.test.d.ts +1 -0
  71. package/dist/src/lib/notebook.test.js +26 -0
  72. package/dist/src/lib/serialize.d.ts +5 -0
  73. package/dist/src/lib/serialize.js +97 -0
  74. package/dist/src/lib/serialize.test.d.ts +1 -0
  75. package/dist/src/lib/serialize.test.js +125 -0
  76. package/dist/src/lib/text.d.ts +1 -0
  77. package/dist/src/lib/text.js +3 -0
  78. package/dist/src/runtime/define.d.ts +28 -0
  79. package/dist/src/runtime/define.js +62 -0
  80. package/dist/src/runtime/display.d.ts +16 -0
  81. package/dist/src/runtime/display.js +60 -0
  82. package/dist/src/runtime/index.d.ts +11 -0
  83. package/dist/src/runtime/index.js +14 -0
  84. package/dist/src/runtime/inspect.d.ts +3 -0
  85. package/dist/src/runtime/inspect.js +43 -0
  86. package/dist/src/runtime/stdlib/assets.d.ts +4 -0
  87. package/dist/src/runtime/stdlib/assets.js +110 -0
  88. package/dist/src/runtime/stdlib/assets.test.d.ts +1 -0
  89. package/dist/src/runtime/stdlib/assets.test.js +78 -0
  90. package/dist/src/runtime/stdlib/dom/canvas.d.ts +1 -0
  91. package/dist/src/runtime/stdlib/dom/canvas.js +6 -0
  92. package/dist/src/runtime/stdlib/dom/context2d.d.ts +1 -0
  93. package/dist/src/runtime/stdlib/dom/context2d.js +9 -0
  94. package/dist/src/runtime/stdlib/dom/index.d.ts +5 -0
  95. package/dist/src/runtime/stdlib/dom/index.js +5 -0
  96. package/dist/src/runtime/stdlib/dom/svg.d.ts +1 -0
  97. package/dist/src/runtime/stdlib/dom/svg.js +7 -0
  98. package/dist/src/runtime/stdlib/dom/text.d.ts +1 -0
  99. package/dist/src/runtime/stdlib/dom/text.js +3 -0
  100. package/dist/src/runtime/stdlib/dom/uid.d.ts +8 -0
  101. package/dist/src/runtime/stdlib/dom/uid.js +25 -0
  102. package/dist/src/runtime/stdlib/dot.d.ts +2 -0
  103. package/dist/src/runtime/stdlib/dot.js +34 -0
  104. package/dist/src/runtime/stdlib/duckdb.d.ts +24 -0
  105. package/dist/src/runtime/stdlib/duckdb.js +379 -0
  106. package/dist/src/runtime/stdlib/fileAttachment.d.ts +71 -0
  107. package/dist/src/runtime/stdlib/fileAttachment.js +199 -0
  108. package/dist/src/runtime/stdlib/generators/index.d.ts +5 -0
  109. package/dist/src/runtime/stdlib/generators/index.js +5 -0
  110. package/dist/src/runtime/stdlib/generators/input.d.ts +1 -0
  111. package/dist/src/runtime/stdlib/generators/input.js +45 -0
  112. package/dist/src/runtime/stdlib/generators/now.d.ts +1 -0
  113. package/dist/src/runtime/stdlib/generators/now.js +5 -0
  114. package/dist/src/runtime/stdlib/generators/observe.d.ts +1 -0
  115. package/dist/src/runtime/stdlib/generators/observe.js +31 -0
  116. package/dist/src/runtime/stdlib/generators/queue.d.ts +1 -0
  117. package/dist/src/runtime/stdlib/generators/queue.js +27 -0
  118. package/dist/src/runtime/stdlib/generators/width.d.ts +1 -0
  119. package/dist/src/runtime/stdlib/generators/width.js +13 -0
  120. package/dist/src/runtime/stdlib/highlight.d.ts +2 -0
  121. package/dist/src/runtime/stdlib/highlight.js +76 -0
  122. package/dist/src/runtime/stdlib/index.d.ts +56 -0
  123. package/dist/src/runtime/stdlib/index.js +23 -0
  124. package/dist/src/runtime/stdlib/inputs.css +15 -0
  125. package/dist/src/runtime/stdlib/inputs.d.ts +2 -0
  126. package/dist/src/runtime/stdlib/inputs.js +2 -0
  127. package/dist/src/runtime/stdlib/leaflet.d.ts +1 -0
  128. package/dist/src/runtime/stdlib/leaflet.js +7 -0
  129. package/dist/src/runtime/stdlib/mapboxgl.d.ts +1 -0
  130. package/dist/src/runtime/stdlib/mapboxgl.js +5 -0
  131. package/dist/src/runtime/stdlib/md.d.ts +5 -0
  132. package/dist/src/runtime/stdlib/md.js +72 -0
  133. package/dist/src/runtime/stdlib/mermaid.d.ts +2 -0
  134. package/dist/src/runtime/stdlib/mermaid.js +11 -0
  135. package/dist/src/runtime/stdlib/mutable.d.ts +8 -0
  136. package/dist/src/runtime/stdlib/mutable.js +30 -0
  137. package/dist/src/runtime/stdlib/observer.d.ts +16 -0
  138. package/dist/src/runtime/stdlib/observer.js +42 -0
  139. package/dist/src/runtime/stdlib/recommendedLibraries.d.ts +25 -0
  140. package/dist/src/runtime/stdlib/recommendedLibraries.js +26 -0
  141. package/dist/src/runtime/stdlib/require.d.ts +4 -0
  142. package/dist/src/runtime/stdlib/require.js +40 -0
  143. package/dist/src/runtime/stdlib/sampleDatasets.d.ts +12 -0
  144. package/dist/src/runtime/stdlib/sampleDatasets.js +31 -0
  145. package/dist/src/runtime/stdlib/sql.d.ts +5 -0
  146. package/dist/src/runtime/stdlib/sql.js +5 -0
  147. package/dist/src/runtime/stdlib/template.d.ts +7 -0
  148. package/dist/src/runtime/stdlib/template.js +2 -0
  149. package/dist/src/runtime/stdlib/tex.d.ts +7 -0
  150. package/dist/src/runtime/stdlib/tex.js +18 -0
  151. package/dist/src/runtime/stdlib/vega-lite.d.ts +1 -0
  152. package/dist/src/runtime/stdlib/vega-lite.js +4 -0
  153. package/dist/src/styles/abstract-dark.css +14 -0
  154. package/dist/src/styles/abstract-light.css +14 -0
  155. package/dist/src/styles/global.css +266 -0
  156. package/dist/src/styles/highlight.css +47 -0
  157. package/dist/src/styles/index.css +14 -0
  158. package/dist/src/styles/inspector.css +89 -0
  159. package/dist/src/styles/plot.css +7 -0
  160. package/dist/src/styles/syntax-dark.css +12 -0
  161. package/dist/src/styles/syntax-light.css +12 -0
  162. package/dist/src/styles/theme-air.css +7 -0
  163. package/dist/src/styles/theme-coffee.css +7 -0
  164. package/dist/src/styles/theme-cotton.css +7 -0
  165. package/dist/src/styles/theme-deep-space.css +16 -0
  166. package/dist/src/styles/theme-glacier.css +7 -0
  167. package/dist/src/styles/theme-ink.css +7 -0
  168. package/dist/src/styles/theme-midnight.css +7 -0
  169. package/dist/src/styles/theme-near-midnight.css +7 -0
  170. package/dist/src/styles/theme-ocean-floor.css +7 -0
  171. package/dist/src/styles/theme-parchment.css +7 -0
  172. package/dist/src/styles/theme-slate.css +7 -0
  173. package/dist/src/styles/theme-stark.css +16 -0
  174. package/dist/src/styles/theme-sun-faded.css +7 -0
  175. package/dist/src/templates/default.html +31 -0
  176. package/dist/src/vite/config.d.ts +2 -0
  177. package/dist/src/vite/config.js +30 -0
  178. package/dist/src/vite/index.d.ts +2 -0
  179. package/dist/src/vite/index.js +2 -0
  180. package/dist/src/vite/observable.d.ts +12 -0
  181. package/dist/src/vite/observable.js +176 -0
  182. package/package.json +73 -0
@@ -0,0 +1,379 @@
1
+ import * as duckdb from "npm:@duckdb/duckdb-wasm";
2
+ // Adapted from https://observablehq.com/@cmudig/duckdb-client
3
+ // Copyright 2021 CMU Data Interaction Group
4
+ //
5
+ // Redistribution and use in source and binary forms, with or without
6
+ // modification, are permitted provided that the following conditions are met:
7
+ //
8
+ // 1. Redistributions of source code must retain the above copyright notice,
9
+ // this list of conditions and the following disclaimer.
10
+ //
11
+ // 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ // this list of conditions and the following disclaimer in the documentation
13
+ // and/or other materials provided with the distribution.
14
+ //
15
+ // 3. Neither the name of the copyright holder nor the names of its contributors
16
+ // may be used to endorse or promote products derived from this software
17
+ // without specific prior written permission.
18
+ //
19
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23
+ // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24
+ // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
+ // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
+ // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
+ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
+ // POSSIBILITY OF SUCH DAMAGE.
30
+ const bundles = {
31
+ mvp: {
32
+ mainModule: "https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm/dist/duckdb-mvp.wasm",
33
+ mainWorker: "https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm/dist/duckdb-browser-mvp.worker.js"
34
+ },
35
+ eh: {
36
+ mainModule: "https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm/dist/duckdb-eh.wasm",
37
+ mainWorker: "https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm/dist/duckdb-browser-eh.worker.js"
38
+ }
39
+ };
40
+ const bundle = duckdb.selectBundle(bundles);
41
+ const logger = new duckdb.ConsoleLogger(duckdb.LogLevel.WARNING);
42
+ // let db;
43
+ // let inserts = [];
44
+ // const sources = new Map();
45
+ // export function registerTable(name, source) {
46
+ // if (source == null) {
47
+ // sources.delete(name);
48
+ // db = DuckDBClient.of(); // drop existing tables and views before re-inserting
49
+ // inserts = Array.from(sources, (i) => db.then((db) => insertSource(db._db, ...i)));
50
+ // } else {
51
+ // sources.set(name, source);
52
+ // db ??= DuckDBClient.of(); // lazy instantiation
53
+ // inserts.push(db.then((db) => insertSource(db._db, name, source)));
54
+ // }
55
+ // }
56
+ // export async function sql(strings, ...args) {
57
+ // return (await getDefaultClient()).query(strings.join("?"), args);
58
+ // }
59
+ // export async function getDefaultClient() {
60
+ // await Promise.all(inserts);
61
+ // return await (db ??= DuckDBClient.of());
62
+ // }
63
+ export class DuckDBClient {
64
+ constructor(db) {
65
+ Object.defineProperties(this, {
66
+ _db: { value: db }
67
+ });
68
+ }
69
+ async queryStream(query, params) {
70
+ const connection = await this._db.connect();
71
+ let reader, batch;
72
+ try {
73
+ if (params?.length > 0) {
74
+ const statement = await connection.prepare(query);
75
+ reader = await statement.send(...params);
76
+ }
77
+ else {
78
+ reader = await connection.send(query);
79
+ }
80
+ batch = await reader.next();
81
+ if (batch.done)
82
+ throw new Error("missing first batch");
83
+ }
84
+ catch (error) {
85
+ await connection.close();
86
+ throw error;
87
+ }
88
+ return {
89
+ schema: batch.value.schema,
90
+ async *readRows() {
91
+ try {
92
+ while (!batch.done) {
93
+ yield batch.value.toArray();
94
+ batch = await reader.next();
95
+ }
96
+ }
97
+ finally {
98
+ await connection.close();
99
+ }
100
+ }
101
+ };
102
+ }
103
+ async query(query, params) {
104
+ const connection = await this._db.connect();
105
+ let table;
106
+ try {
107
+ if (params?.length > 0) {
108
+ const statement = await connection.prepare(query);
109
+ table = await statement.query(...params);
110
+ }
111
+ else {
112
+ table = await connection.query(query);
113
+ }
114
+ }
115
+ finally {
116
+ await connection.close();
117
+ }
118
+ return table;
119
+ }
120
+ async queryRow(query, params) {
121
+ const result = await this.queryStream(query, params);
122
+ const reader = result.readRows();
123
+ try {
124
+ const { done, value } = await reader.next();
125
+ return done || !value.length ? null : value[0];
126
+ }
127
+ finally {
128
+ await reader.return();
129
+ }
130
+ }
131
+ async sql(strings, ...args) {
132
+ return await this.query(strings.join("?"), args);
133
+ }
134
+ queryTag(strings, ...params) {
135
+ return [strings.join("?"), params];
136
+ }
137
+ escape(name) {
138
+ return `"${name}"`;
139
+ }
140
+ async describeTables() {
141
+ return Array.from(await this.query("SHOW TABLES"), ({ name }) => ({ name }));
142
+ }
143
+ async describeColumns(options = {}) {
144
+ return Array.from(await this.query(`DESCRIBE ${this.escape(options.table)}`), ({ column_name, column_type, null: nullable }) => ({
145
+ name: column_name,
146
+ type: getDuckDBType(column_type),
147
+ nullable: nullable !== "NO",
148
+ databaseType: column_type
149
+ }));
150
+ }
151
+ static async of(sources = {}, config = {}) {
152
+ const db = await createDuckDB();
153
+ if (config.query?.castTimestampToDate === undefined) {
154
+ config = { ...config, query: { ...config.query, castTimestampToDate: true } };
155
+ }
156
+ if (config.query?.castBigIntToDouble === undefined) {
157
+ config = { ...config, query: { ...config.query, castBigIntToDouble: true } };
158
+ }
159
+ await db.open(config);
160
+ // await registerExtensions(db, config.extensions);
161
+ await Promise.all(Object.entries(sources).map(([name, source]) => insertSource(db, name, source)));
162
+ return new DuckDBClient(db);
163
+ }
164
+ static sql() {
165
+ return this.of.apply(this, arguments).then((db) => db.sql.bind(db));
166
+ }
167
+ }
168
+ Object.defineProperty(DuckDBClient.prototype, "dialect", { value: "duckdb" });
169
+ // async function registerExtensions(db, extensions) {
170
+ // const {mainModule} = await bundle;
171
+ // const platform = Object.keys(bundles).find(
172
+ // (platform) => mainModule === bundles[platform].mainModule
173
+ // );
174
+ // const con = await db.connect();
175
+ // try {
176
+ // await Promise.all(
177
+ // Object.entries(DUCKDB_MANIFEST.extensions).map(([name, {load, [platform]: ref}]) =>
178
+ // con
179
+ // .query(`INSTALL "${name}" FROM '${import.meta.resolve(ref)}'`)
180
+ // .then(
181
+ // () =>
182
+ // (extensions === undefined ? load : extensions.includes(name)) &&
183
+ // con.query(`LOAD "${name}"`)
184
+ // )
185
+ // )
186
+ // );
187
+ // } finally {
188
+ // await con.close();
189
+ // }
190
+ // }
191
+ async function insertSource(database, name, source) {
192
+ source = await source;
193
+ if (isFileAttachment(source))
194
+ return insertFile(database, name, source);
195
+ if (isArrowTable(source))
196
+ return insertArrowTable(database, name, source);
197
+ if (Array.isArray(source))
198
+ return insertArray(database, name, source);
199
+ if (isArqueroTable(source))
200
+ return insertArqueroTable(database, name, source);
201
+ if (typeof source === "string")
202
+ return insertUrl(database, name, source);
203
+ if (source && typeof source === "object") {
204
+ if ("data" in source) {
205
+ // data + options
206
+ const { data, ...options } = source;
207
+ if (isArrowTable(data))
208
+ return insertArrowTable(database, name, data, options);
209
+ return insertArray(database, name, data, options);
210
+ }
211
+ if ("file" in source) {
212
+ // file + options
213
+ const { file, ...options } = source;
214
+ return insertFile(database, name, file, options);
215
+ }
216
+ }
217
+ throw new Error(`invalid source: ${source}`);
218
+ }
219
+ async function insertUrl(database, name, url) {
220
+ const connection = await database.connect();
221
+ try {
222
+ await connection.query(`CREATE VIEW '${name}' AS FROM '${url}'`);
223
+ }
224
+ finally {
225
+ await connection.close();
226
+ }
227
+ }
228
+ async function insertFile(database, name, file, options) {
229
+ const url = await file.url();
230
+ if (url.startsWith("blob:")) {
231
+ const buffer = await file.arrayBuffer();
232
+ await database.registerFileBuffer(file.name, new Uint8Array(buffer));
233
+ }
234
+ else {
235
+ await database.registerFileURL(file.name, new URL(url, location).href, 4); // duckdb.DuckDBDataProtocol.HTTP
236
+ }
237
+ const connection = await database.connect();
238
+ try {
239
+ switch (file.mimeType) {
240
+ case "text/csv":
241
+ case "text/tab-separated-values": {
242
+ return await connection
243
+ .insertCSVFromPath(file.name, {
244
+ name,
245
+ schema: "main",
246
+ ...options
247
+ })
248
+ .catch(async (error) => {
249
+ // If initial attempt to insert CSV resulted in a conversion
250
+ // error, try again, this time treating all columns as strings.
251
+ if (error.toString().includes("Could not convert")) {
252
+ return await insertUntypedCSV(connection, file, name);
253
+ }
254
+ throw error;
255
+ });
256
+ }
257
+ case "application/json":
258
+ return await connection.insertJSONFromPath(file.name, {
259
+ name,
260
+ schema: "main",
261
+ ...options
262
+ });
263
+ default:
264
+ if (/\.arrow$/i.test(file.name)) {
265
+ const buffer = new Uint8Array(await file.arrayBuffer());
266
+ return await connection.insertArrowFromIPCStream(buffer, {
267
+ name,
268
+ schema: "main",
269
+ ...options
270
+ });
271
+ }
272
+ if (/\.parquet$/i.test(file.name)) {
273
+ const table = file.size < 50e6 ? "TABLE" : "VIEW"; // for small files, materialize the table
274
+ return await connection.query(`CREATE ${table} '${name}' AS SELECT * FROM parquet_scan('${file.name}')`);
275
+ }
276
+ if (/\.(db|ddb|duckdb)$/i.test(file.name)) {
277
+ return await connection.query(`ATTACH '${file.name}' AS ${name} (READ_ONLY)`);
278
+ }
279
+ throw new Error(`unknown file type: ${file.mimeType}`);
280
+ }
281
+ }
282
+ finally {
283
+ await connection.close();
284
+ }
285
+ }
286
+ async function insertUntypedCSV(connection, file, name) {
287
+ const statement = await connection.prepare(`CREATE TABLE '${name}' AS SELECT * FROM read_csv_auto(?, ALL_VARCHAR=TRUE)`);
288
+ return await statement.send(file.name);
289
+ }
290
+ async function insertArrowTable(database, name, table, options) {
291
+ const connection = await database.connect();
292
+ try {
293
+ await connection.insertArrowTable(table, {
294
+ name,
295
+ schema: "main",
296
+ ...options
297
+ });
298
+ }
299
+ finally {
300
+ await connection.close();
301
+ }
302
+ }
303
+ async function insertArqueroTable(database, name, source) {
304
+ // TODO When we have stdlib versioning and can upgrade Arquero to version 5,
305
+ // we can then call source.toArrow() directly, with insertArrowTable()
306
+ const arrow = await import("npm:apache-arrow");
307
+ const table = arrow.tableFromIPC(source.toArrowBuffer());
308
+ return await insertArrowTable(database, name, table);
309
+ }
310
+ async function insertArray(database, name, array, options) {
311
+ const arrow = await import("npm:apache-arrow");
312
+ const table = arrow.tableFromJSON(array);
313
+ return await insertArrowTable(database, name, table, options);
314
+ }
315
+ async function createDuckDB() {
316
+ const { mainWorker, mainModule } = await bundle;
317
+ const worker = await duckdb.createWorker(mainWorker);
318
+ const db = new duckdb.AsyncDuckDB(logger, worker);
319
+ await db.instantiate(mainModule);
320
+ return db;
321
+ }
322
+ // https://duckdb.org/docs/sql/data_types/overview
323
+ function getDuckDBType(type) {
324
+ switch (type) {
325
+ case "BIGINT":
326
+ case "HUGEINT":
327
+ case "UBIGINT":
328
+ return "bigint";
329
+ case "DOUBLE":
330
+ case "REAL":
331
+ case "FLOAT":
332
+ return "number";
333
+ case "INTEGER":
334
+ case "SMALLINT":
335
+ case "TINYINT":
336
+ case "USMALLINT":
337
+ case "UINTEGER":
338
+ case "UTINYINT":
339
+ return "integer";
340
+ case "BOOLEAN":
341
+ return "boolean";
342
+ case "DATE":
343
+ case "TIMESTAMP":
344
+ case "TIMESTAMP WITH TIME ZONE":
345
+ return "date";
346
+ case "VARCHAR":
347
+ case "UUID":
348
+ return "string";
349
+ // case "BLOB":
350
+ // case "INTERVAL":
351
+ // case "TIME":
352
+ default:
353
+ if (/^DECIMAL\(/.test(type))
354
+ return "integer";
355
+ return "other";
356
+ }
357
+ }
358
+ // Returns true if the given value is an Observable FileAttachment.
359
+ function isFileAttachment(value) {
360
+ return (value &&
361
+ typeof value.name === "string" &&
362
+ typeof value.url === "function" &&
363
+ typeof value.arrayBuffer === "function");
364
+ }
365
+ // Arquero tables have a `toArrowBuffer` function
366
+ function isArqueroTable(value) {
367
+ return value && typeof value.toArrowBuffer === "function";
368
+ }
369
+ // Returns true if the value is an Apache Arrow table. This uses a “duck” test
370
+ // (instead of strict instanceof) because we want it to work with a range of
371
+ // Apache Arrow versions at least 7.0.0 or above.
372
+ // https://arrow.apache.org/docs/7.0/js/classes/Arrow_dom.Table.html
373
+ function isArrowTable(value) {
374
+ return (value &&
375
+ typeof value.getChild === "function" &&
376
+ typeof value.toArray === "function" &&
377
+ value.schema &&
378
+ Array.isArray(value.schema.fields));
379
+ }
@@ -0,0 +1,71 @@
1
+ export type DsvOptions = {
2
+ delimiter?: string;
3
+ array?: boolean;
4
+ typed?: boolean;
5
+ };
6
+ export type DsvResult = any[] & {
7
+ columns: string[];
8
+ };
9
+ export interface FileAttachment {
10
+ name: string;
11
+ mimeType: string;
12
+ href: string;
13
+ lastModified: number | undefined;
14
+ size: number | undefined;
15
+ url(): Promise<string>;
16
+ blob(): Promise<Blob>;
17
+ arrayBuffer(): Promise<ArrayBuffer>;
18
+ text(encoding?: string): Promise<string>;
19
+ json(): Promise<any>;
20
+ stream(): Promise<ReadableStream<Uint8Array<ArrayBufferLike>>>;
21
+ dsv(options?: DsvOptions): Promise<DsvResult>;
22
+ csv(options?: Exclude<DsvOptions, "delimiter">): Promise<DsvResult>;
23
+ tsv(options?: Exclude<DsvOptions, "delimiter">): Promise<DsvResult>;
24
+ image(props?: Partial<HTMLImageElement>): Promise<HTMLImageElement>;
25
+ arrow(): Promise<any>;
26
+ arquero(options?: any): Promise<any>;
27
+ parquet(): Promise<any>;
28
+ xml(mimeType?: DOMParserSupportedType): Promise<Document>;
29
+ html(): Promise<Document>;
30
+ }
31
+ export declare function FileAttachment(name: string, base?: string): FileAttachment;
32
+ export declare namespace FileAttachment {
33
+ var prototype: FileAttachmentImpl;
34
+ }
35
+ export declare abstract class AbstractFile implements FileAttachment {
36
+ name: string;
37
+ mimeType: string;
38
+ lastModified: number | undefined;
39
+ size: number | undefined;
40
+ abstract href: string;
41
+ constructor(name: string, mimeType?: string, lastModified?: number, size?: number);
42
+ url(): Promise<string>;
43
+ blob(): Promise<Blob>;
44
+ arrayBuffer(): Promise<ArrayBuffer>;
45
+ text(encoding?: string): Promise<string>;
46
+ json(): Promise<any>;
47
+ stream(): Promise<ReadableStream<Uint8Array<ArrayBufferLike>>>;
48
+ dsv({ delimiter, array, typed }?: {
49
+ delimiter?: string | undefined;
50
+ array?: boolean | undefined;
51
+ typed?: boolean | undefined;
52
+ }): Promise<DsvResult>;
53
+ csv(options: Exclude<DsvOptions, "delimiter">): Promise<DsvResult>;
54
+ tsv(options: Exclude<DsvOptions, "delimiter">): Promise<DsvResult>;
55
+ image(props?: Partial<HTMLImageElement>): Promise<HTMLImageElement>;
56
+ arrow(): Promise<any>;
57
+ arquero(options?: any): Promise<any>;
58
+ parquet(): Promise<any>;
59
+ xml(mimeType?: DOMParserSupportedType): Promise<Document>;
60
+ html(): Promise<Document>;
61
+ }
62
+ declare class FileAttachmentImpl extends AbstractFile {
63
+ href: string;
64
+ constructor(href: string, name: string, mimeType?: string, lastModified?: number, size?: number);
65
+ }
66
+ type FileResolver = (name: string) => {
67
+ url: string;
68
+ mimeType?: string;
69
+ } | string | null;
70
+ export declare function fileAttachments(resolve: FileResolver): (name: string) => FileAttachment;
71
+ export {};
@@ -0,0 +1,199 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ const files = new Map();
3
+ export function FileAttachment(name, base = document.baseURI) {
4
+ if (new.target !== undefined)
5
+ throw new TypeError("FileAttachment is not a constructor");
6
+ const href = new URL(name, base).href;
7
+ let file = files.get(href);
8
+ if (!file) {
9
+ file = new FileAttachmentImpl(href, name.split("/").pop());
10
+ files.set(href, file);
11
+ }
12
+ return file;
13
+ }
14
+ async function remote_fetch(file) {
15
+ const response = await fetch(file.href);
16
+ if (!response.ok)
17
+ throw new Error(`Unable to load file: ${file.name}`);
18
+ return response;
19
+ }
20
+ export class AbstractFile {
21
+ constructor(name, mimeType = guessMimeType(name), lastModified, size) {
22
+ Object.defineProperty(this, "name", {
23
+ enumerable: true,
24
+ configurable: true,
25
+ writable: true,
26
+ value: void 0
27
+ });
28
+ Object.defineProperty(this, "mimeType", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: void 0
33
+ });
34
+ Object.defineProperty(this, "lastModified", {
35
+ enumerable: true,
36
+ configurable: true,
37
+ writable: true,
38
+ value: void 0
39
+ });
40
+ Object.defineProperty(this, "size", {
41
+ enumerable: true,
42
+ configurable: true,
43
+ writable: true,
44
+ value: void 0
45
+ });
46
+ Object.defineProperties(this, {
47
+ name: { value: `${name}`, enumerable: true },
48
+ mimeType: { value: `${mimeType}`, enumerable: true },
49
+ lastModified: { value: lastModified === undefined ? undefined : +lastModified, enumerable: true }, // prettier-ignore
50
+ size: { value: size === undefined ? undefined : +size, enumerable: true }
51
+ });
52
+ }
53
+ async url() {
54
+ return this.href;
55
+ }
56
+ async blob() {
57
+ return (await remote_fetch(this)).blob();
58
+ }
59
+ async arrayBuffer() {
60
+ return (await remote_fetch(this)).arrayBuffer();
61
+ }
62
+ async text(encoding) {
63
+ return encoding === undefined
64
+ ? (await remote_fetch(this)).text()
65
+ : new TextDecoder(encoding).decode(await this.arrayBuffer());
66
+ }
67
+ async json() {
68
+ return (await remote_fetch(this)).json();
69
+ }
70
+ async stream() {
71
+ return (await remote_fetch(this)).body;
72
+ }
73
+ async dsv({ delimiter = ",", array = false, typed = false } = {}) {
74
+ const [text, d3] = await Promise.all([this.text(), import("npm:d3-dsv")]);
75
+ const format = d3.dsvFormat(delimiter);
76
+ const parse = array ? format.parseRows : format.parse;
77
+ return parse(text, typed && d3.autoType);
78
+ }
79
+ async csv(options) {
80
+ return this.dsv({ ...options, delimiter: "," });
81
+ }
82
+ async tsv(options) {
83
+ return this.dsv({ ...options, delimiter: "\t" });
84
+ }
85
+ async image(props) {
86
+ const url = await this.url();
87
+ return new Promise((resolve, reject) => {
88
+ const i = new Image();
89
+ if (new URL(url, document.baseURI).origin !== location.origin)
90
+ i.crossOrigin = "anonymous";
91
+ Object.assign(i, props);
92
+ i.onload = () => resolve(i);
93
+ i.onerror = () => reject(new Error(`Unable to load file: ${this.name}`));
94
+ i.src = url;
95
+ });
96
+ }
97
+ async arrow() {
98
+ const [Arrow, response] = await Promise.all([import("npm:apache-arrow"), remote_fetch(this)]);
99
+ return Arrow.tableFromIPC(response);
100
+ }
101
+ async arquero(options) {
102
+ let request;
103
+ let from;
104
+ switch (this.mimeType) {
105
+ case "application/json":
106
+ request = this.text();
107
+ from = "fromJSON";
108
+ break;
109
+ // @ts-expect-error fall through
110
+ case "text/tab-separated-values":
111
+ if (options?.delimiter === undefined)
112
+ options = { ...options, delimiter: "\t" };
113
+ // fall through
114
+ case "text/csv":
115
+ request = this.text();
116
+ from = "fromCSV";
117
+ break;
118
+ default:
119
+ if (/\.arrow$/i.test(this.name)) {
120
+ request = this.arrow();
121
+ from = "fromArrow";
122
+ }
123
+ else if (/\.parquet$/i.test(this.name)) {
124
+ request = this.parquet();
125
+ from = "fromArrow";
126
+ }
127
+ else {
128
+ throw new Error(`unable to determine Arquero loader: ${this.name}`);
129
+ }
130
+ break;
131
+ }
132
+ const [aq, body] = await Promise.all([import("npm:arquero"), request]);
133
+ return aq[from](body, options);
134
+ }
135
+ async parquet() {
136
+ const [Arrow, Parquet, buffer] = await Promise.all([import("npm:apache-arrow"), import("npm:parquet-wasm").then(async (Parquet) => (await Parquet.default("https://cdn.jsdelivr.net/npm/parquet-wasm/esm/parquet_wasm_bg.wasm"), Parquet)), this.arrayBuffer()]); // prettier-ignore
137
+ return Arrow.tableFromIPC(Parquet.readParquet(new Uint8Array(buffer)).intoIPCStream());
138
+ }
139
+ async xml(mimeType = "application/xml") {
140
+ return new DOMParser().parseFromString(await this.text(), mimeType);
141
+ }
142
+ async html() {
143
+ return this.xml("text/html");
144
+ }
145
+ }
146
+ // TODO Replace this with static analysis of files.
147
+ function guessMimeType(name) {
148
+ const i = name.lastIndexOf(".");
149
+ const j = name.lastIndexOf("/");
150
+ const extension = i > 0 && (j < 0 || i > j) ? name.slice(i).toLowerCase() : "";
151
+ switch (extension) {
152
+ case ".csv":
153
+ return "text/csv";
154
+ case ".tsv":
155
+ return "text/tab-separated-values";
156
+ case ".json":
157
+ return "application/json";
158
+ case ".html":
159
+ return "text/html";
160
+ case ".xml":
161
+ return "application/xml";
162
+ case ".png":
163
+ return "image/png";
164
+ case ".jpg":
165
+ return "image/jpg";
166
+ case ".js":
167
+ return "text/javascript";
168
+ default:
169
+ return "application/octet-stream";
170
+ }
171
+ }
172
+ class FileAttachmentImpl extends AbstractFile {
173
+ constructor(href, name, mimeType, lastModified, size) {
174
+ super(name, mimeType, lastModified, size);
175
+ Object.defineProperty(this, "href", {
176
+ enumerable: true,
177
+ configurable: true,
178
+ writable: true,
179
+ value: void 0
180
+ });
181
+ Object.defineProperty(this, "href", { value: href });
182
+ }
183
+ }
184
+ Object.defineProperty(FileAttachmentImpl, "name", { value: "FileAttachment" }); // prevent mangling
185
+ FileAttachment.prototype = FileAttachmentImpl.prototype; // instanceof
186
+ export function fileAttachments(resolve) {
187
+ function FileAttachment(name) {
188
+ const result = resolve((name += ""));
189
+ if (result == null)
190
+ throw new Error(`File not found: ${name}`);
191
+ if (typeof result === "object" && "url" in result) {
192
+ const { url, mimeType } = result;
193
+ return new FileAttachmentImpl(url, name, mimeType);
194
+ }
195
+ return new FileAttachmentImpl(result, name);
196
+ }
197
+ FileAttachment.prototype = FileAttachmentImpl.prototype; // instanceof
198
+ return FileAttachment;
199
+ }
@@ -0,0 +1,5 @@
1
+ export { input } from "./input.js";
2
+ export { now } from "./now.js";
3
+ export { observe } from "./observe.js";
4
+ export { queue } from "./queue.js";
5
+ export { width } from "./width.js";
@@ -0,0 +1,5 @@
1
+ export { input } from "./input.js";
2
+ export { now } from "./now.js";
3
+ export { observe } from "./observe.js";
4
+ export { queue } from "./queue.js";
5
+ export { width } from "./width.js";
@@ -0,0 +1 @@
1
+ export declare function input(element: Element): AsyncGenerator<string | number | boolean | string[] | Date | File | FileList | null, void, unknown>;