|
1 | | -import type { SqlJsConfig, SqlJsStatic } from 'sql.js'; |
| 1 | +import type { SqlJsConfig, SqlJsStatic, InitSqlJsStatic } from 'sql.js'; |
2 | 2 | import { defaultFileAdapter, FileAdapter, getNodeRequire, isNodeRuntime } from './io'; |
3 | 3 |
|
4 | 4 | export interface SqliteStatementAdapter { |
@@ -30,12 +30,14 @@ export function configureSqlJs(config: SqlJsConfig): void { |
30 | 30 | sqlJsConfig = { ...(sqlJsConfig ?? {}), ...config }; |
31 | 31 | } |
32 | 32 |
|
33 | | -async function getSqlJs(): Promise<SqlJsStatic> { |
| 33 | +async function getSqlJsBrowser(): Promise<SqlJsStatic> { |
34 | 34 | if (!sqlJsPromise) { |
35 | | - sqlJsPromise = import('sql.js').then((module) => { |
36 | | - const initSqlJs = module.default || module; |
37 | | - return initSqlJs(sqlJsConfig ?? {}); |
38 | | - }); |
| 35 | + const isBrowser = typeof globalThis !== 'undefined' && (globalThis as any).window !== undefined; |
| 36 | + if (!isBrowser) throw new Error('Must be run in a browser'); |
| 37 | + const window = (globalThis as any).window; |
| 38 | + if (!('initSqlJs' in window)) throw new Error('Need to add sql-wasm.js script element to DOM'); |
| 39 | + const initSqlJs = window.initSqlJs as InitSqlJsStatic; |
| 40 | + sqlJsPromise = initSqlJs(sqlJsConfig ?? {}); |
39 | 41 | } |
40 | 42 | return sqlJsPromise; |
41 | 43 | } |
@@ -120,7 +122,7 @@ export async function openSqliteDatabase( |
120 | 122 | const data = await readBinaryFromInput(input); |
121 | 123 |
|
122 | 124 | if (!isNodeRuntime()) { |
123 | | - const SQL = await getSqlJs(); |
| 125 | + const SQL = await getSqlJsBrowser(); |
124 | 126 | const db = new SQL.Database(data); |
125 | 127 | return { db: createSqlJsAdapter(db) }; |
126 | 128 | } |
|
0 commit comments