@hulla/db-sqlite 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @hulla/db-sqlite
2
2
 
3
- SQLite application instances for Node, Bun, browsers and Expo.
3
+ SQLite application instances for Node, Bun, browsers, and Expo.
4
4
 
5
5
  ```ts
6
6
  import { defineSchema, defineTable, v } from '@hulla/db'
@@ -15,10 +15,13 @@ Schema imports are inert. `sqlite({...})` starts opening existing storage; opera
15
15
  wait automatically. `sqlite.initialize({...})` explicitly provisions fresh storage.
16
16
  Optional `ready()`, observable `state`/`subscribe()` and terminal `close()` expose the
17
17
  instance lifecycle. Register local functions through one barrel import callback or
18
- an application glob compiled by [`@hulla/db/build`](https://github.com/hulladev/db/blob/main/docs/build.md);
18
+ an application glob compiled by [`@hulla/db-cli/build`](https://github.com/hulladev/db/blob/main/docs/build.md);
19
19
  combine shared/app handlers using ordinary exports.
20
20
 
21
- The browser and Expo entrypoints accept `open`, which supplies a dedicated driver.
21
+ The browser entrypoint accepts `open`, which supplies a dedicated driver. Expo
22
+ apps import `sqlite` from `@hulla/db-sqlite/expo` and pass a filename. Run
23
+ `npx expo install expo-sqlite expo-crypto` to match the native dependencies to
24
+ the application's Expo SDK.
22
25
  Readonly replicas require explicit source URL bindings. Offline mutations queue
23
26
  server calls with mandatory device-side conflict callbacks and optional optimistic
24
27
  feedback. Native Rust SQLite storage and SQLite managed HTTP hosting remain work.
package/dist/browser.js CHANGED
@@ -1,9 +1,8 @@
1
- import { sqliteFactory } from "./descriptor.js";
2
- import { openSQLiteDatabase } from "./runtime.js";
1
+ import { createSQLiteAdapter } from "./portable.js";
3
2
  export { wasmSQLiteDriver } from "./driver.js";
4
- export const sqlite = sqliteFactory(async (schema, settings, initialize) => {
5
- if (!settings || typeof settings !== "object" || Reflect.ownKeys(settings).some(key => !["open", "randomBytes", "transactionTimeoutMs"].includes(key))
3
+ export const sqlite = createSQLiteAdapter(settings => {
4
+ if (!settings || typeof settings !== "object" || Reflect.ownKeys(settings).some(key => !["open", "randomBytes", "transactionTimeoutMs", "startupRetry"].includes(key))
6
5
  || settings.filename !== undefined || typeof settings.open !== "function")
7
6
  throw new TypeError("Browser SQLite requires open: () => a dedicated SQLite driver");
8
- return openSQLiteDatabase(schema, await settings.open(), settings, initialize);
7
+ return settings;
9
8
  });
@@ -1,11 +1,13 @@
1
1
  import type { Database, DatabaseEngine, SchemaDefinition, ConnectedDatabase, SourceConnection } from "@hulla/db";
2
2
  import { type DatabaseOptions } from "@hulla/db/engine";
3
3
  import type { FunctionSource } from "@hulla/db";
4
- import type { SourcesOf } from "@hulla/db/internal/engine";
4
+ import { type SourcesOf } from "@hulla/db/internal/engine";
5
5
  import type { SQLiteDriver } from "./driver.ts";
6
6
  interface SQLiteSettings {
7
7
  readonly randomBytes?: (length: number) => Uint8Array;
8
8
  readonly transactionTimeoutMs?: number;
9
+ /** Override which driver errors get one startup retry, or disable it. */
10
+ readonly startupRetry?: false | ((error: unknown) => boolean);
9
11
  }
10
12
  /** Each instance owns a fresh dedicated driver connection. */
11
13
  export type BrowserSQLiteConnection = SQLiteSettings & {
@@ -17,10 +19,11 @@ export type SQLiteConnection = BrowserSQLiteConnection | (SQLiteSettings & {
17
19
  readonly open?: never;
18
20
  });
19
21
  export type Connector<C extends SQLiteConnection = SQLiteConnection> = <S extends SchemaDefinition>(schema: S, settings: C, initialize: boolean) => Promise<ConnectedDatabase<S>>;
20
- export declare function sqliteDescriptor<C extends SQLiteConnection = SQLiteConnection>(connect: Connector<C>): DatabaseEngine<"sqlite", C>;
22
+ export declare function isSQLiteLockResult(code: unknown): boolean;
23
+ export declare function sqliteDescriptor<C extends SQLiteConnection = SQLiteConnection>(connect: Connector<C>, isDriverLockError?: (error: unknown) => boolean): DatabaseEngine<"sqlite", C>;
21
24
  export type SQLiteConstructor<C extends SQLiteConnection = SQLiteConnection> = <const S extends SchemaDefinition, const F extends FunctionSource | undefined = undefined, const R extends readonly SourceConnection<SourcesOf<S>>[] = readonly SourceConnection<SourcesOf<S>>[]>(options: DatabaseOptions<S, C, F, R>) => Database<S, F>;
22
25
  export type SQLiteFactory<C extends SQLiteConnection = SQLiteConnection> = SQLiteConstructor<C> & {
23
26
  readonly initialize: SQLiteConstructor<C>;
24
27
  };
25
- export declare function sqliteFactory<C extends SQLiteConnection = SQLiteConnection>(connect: Connector<C>): SQLiteFactory<C>;
28
+ export declare function sqliteFactory<C extends SQLiteConnection = SQLiteConnection>(connect: Connector<C>, isDriverLockError?: (error: unknown) => boolean): SQLiteFactory<C>;
26
29
  export {};
@@ -1,13 +1,41 @@
1
1
  import { createDatabase, registerDatabaseFactory } from "@hulla/db/engine";
2
- export function sqliteDescriptor(connect) {
2
+ import { DatabaseError } from "@hulla/db/internal/engine";
3
+ export function isSQLiteLockResult(code) {
4
+ if (typeof code !== "number" || !Number.isInteger(code) || code < 0 || code > 0x7fff_ffff)
5
+ return false;
6
+ const primary = code & 0xff;
7
+ return primary === 5 || primary === 6;
8
+ }
9
+ function isLockError(error) {
10
+ if (!(error instanceof Error))
11
+ return false;
12
+ const { code, errcode, errno, resultCode } = error;
13
+ if (typeof code === "string" && /^SQLITE_(?:BUSY|LOCKED)(?:_|$)/.test(code))
14
+ return true;
15
+ return isSQLiteLockResult(errcode ?? errno ?? resultCode);
16
+ }
17
+ export function sqliteDescriptor(connect, isDriverLockError) {
18
+ const open = (schema, settings, initialize) => {
19
+ const policy = settings?.startupRetry;
20
+ if (policy !== undefined && policy !== false && typeof policy !== "function")
21
+ throw new TypeError("SQLite startupRetry must be false or a function");
22
+ return connect(schema, settings, initialize);
23
+ };
3
24
  return Object.freeze({
4
25
  name: "sqlite", replicaStorage: true, serialTransactions: true,
5
- connect: (schema, settings) => connect(schema, settings, false),
6
- initialize: (schema, settings) => connect(schema, settings, true),
26
+ connect: (schema, settings) => open(schema, settings, false),
27
+ initialize: (schema, settings) => open(schema, settings, true),
28
+ retryStartup(error, settings) {
29
+ if (error instanceof DatabaseError || settings?.startupRetry === false)
30
+ return false;
31
+ return typeof settings?.startupRetry === "function"
32
+ ? settings.startupRetry(error) === true
33
+ : isLockError(error) || isDriverLockError?.(error) === true;
34
+ },
7
35
  });
8
36
  }
9
- export function sqliteFactory(connect) {
10
- const engine = sqliteDescriptor(connect);
37
+ export function sqliteFactory(connect, isDriverLockError) {
38
+ const engine = sqliteDescriptor(connect, isDriverLockError);
11
39
  const create = (options) => createDatabase(engine, options);
12
40
  const initialize = (options) => createDatabase(engine, options, true);
13
41
  registerDatabaseFactory(create, engine);
package/dist/driver.d.ts CHANGED
@@ -17,9 +17,3 @@ export interface SQLiteWasmConnection {
17
17
  }
18
18
  /** Wrap an official sqlite3.oo1.DB/OpfsDb in the thread which owns it (normally a worker). */
19
19
  export declare function wasmSQLiteDriver(connection: SQLiteWasmConnection): SQLiteDriver;
20
- export interface ExpoSQLiteConnection {
21
- getAllAsync<T>(sql: string, parameters: SQLiteValue[]): Promise<T[]>;
22
- closeAsync(): Promise<void>;
23
- }
24
- /** Wrap a dedicated expo-sqlite connection; the application owns opening/configuring its file. */
25
- export declare function expoSQLiteDriver(connection: ExpoSQLiteConnection): SQLiteDriver;
package/dist/driver.js CHANGED
@@ -9,10 +9,3 @@ export function wasmSQLiteDriver(connection) {
9
9
  close() { connection.close(); },
10
10
  };
11
11
  }
12
- /** Wrap a dedicated expo-sqlite connection; the application owns opening/configuring its file. */
13
- export function expoSQLiteDriver(connection) {
14
- return {
15
- execute: (sql, parameters = []) => connection.getAllAsync(sql, [...parameters]),
16
- close: () => connection.closeAsync(),
17
- };
18
- }
package/dist/engine.js CHANGED
@@ -14,7 +14,7 @@ export class SQLiteEngine {
14
14
  source = "";
15
15
  constructor(driver, schema, randomBytes = length => {
16
16
  if (!globalThis.crypto?.getRandomValues)
17
- throw new TypeError("Supply randomBytes using a cryptographically secure platform RNG (for example expo-crypto)");
17
+ throw new TypeError("Supply randomBytes using a cryptographically secure platform RNG");
18
18
  return globalThis.crypto.getRandomValues(new Uint8Array(length));
19
19
  }) {
20
20
  this.driver = driver;
package/dist/expo.d.ts CHANGED
@@ -1,4 +1,9 @@
1
- export { sqlite } from "./browser.ts";
2
- export { expoSQLiteDriver } from "./driver.ts";
3
- export type { ExpoSQLiteConnection, SQLiteDriver } from "./driver.ts";
4
- export type { BrowserSQLiteConnection as SQLiteConnection } from "./descriptor.ts";
1
+ import { type SQLiteDriver, type SQLiteFactory, type SQLiteValue } from "./portable.ts";
2
+ export type { SQLiteConnection, SQLiteDriver } from "./portable.ts";
3
+ export interface ExpoSQLiteConnection {
4
+ getAllAsync<T>(sql: string, parameters: SQLiteValue[]): Promise<T[]>;
5
+ closeAsync(): Promise<void>;
6
+ }
7
+ /** Transfer a dedicated native connection to the SQLite instance. */
8
+ export declare function expoSQLiteDriver(connection: ExpoSQLiteConnection): SQLiteDriver;
9
+ export declare const sqlite: SQLiteFactory;
package/dist/expo.js CHANGED
@@ -1,2 +1,52 @@
1
- export { sqlite } from "./browser.js";
2
- export { expoSQLiteDriver } from "./driver.js";
1
+ /// <reference path="./expo-modules.d.ts" />
2
+ import { createSQLiteAdapter, isSQLiteLockResult, } from "./portable.js";
3
+ /** Transfer a dedicated native connection to the SQLite instance. */
4
+ export function expoSQLiteDriver(connection) {
5
+ return {
6
+ execute: (sql, parameters = []) => connection.getAllAsync(sql, [...parameters]),
7
+ close: () => connection.closeAsync(),
8
+ };
9
+ }
10
+ async function secureRandomBytes() {
11
+ try {
12
+ const { getRandomValues } = await import("expo-crypto");
13
+ if (typeof getRandomValues !== "function")
14
+ throw new TypeError("expo-crypto requires getRandomValues");
15
+ return length => getRandomValues(new Uint8Array(length));
16
+ }
17
+ catch (cause) {
18
+ return () => {
19
+ throw new TypeError("Install expo-crypto for secure SQLite UUID generation, or supply randomBytes", { cause });
20
+ };
21
+ }
22
+ }
23
+ async function openDatabase(filename) {
24
+ const { openDatabaseAsync } = await import("expo-sqlite");
25
+ return expoSQLiteDriver(await openDatabaseAsync(filename, { useNewConnection: true }));
26
+ }
27
+ function isExpoLockError(error) {
28
+ // Expo reports the SQLite result code in the native error message.
29
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ERR_INTERNAL_SQLITE_ERROR")
30
+ return false;
31
+ const result = /\bError code (\d+)\b/.exec(error.message);
32
+ return result !== null && isSQLiteLockResult(Number(result[1]));
33
+ }
34
+ export const sqlite = createSQLiteAdapter(async (settings) => {
35
+ if (!settings || typeof settings !== "object" || Reflect.ownKeys(settings).some(key => !["filename", "open", "randomBytes", "transactionTimeoutMs", "startupRetry"].includes(key))
36
+ || (settings.filename === undefined) === (settings.open === undefined)) {
37
+ throw new TypeError("Expo SQLite requires exactly one of filename or open");
38
+ }
39
+ let open = settings.open;
40
+ const { filename } = settings;
41
+ if (filename !== undefined) {
42
+ if (typeof filename !== "string" || !filename || filename.includes("\0"))
43
+ throw new TypeError("SQLite filename must be a nonempty string");
44
+ open = () => openDatabase(filename);
45
+ }
46
+ if (typeof open !== "function")
47
+ throw new TypeError("SQLite open must create a dedicated connection");
48
+ const randomBytes = settings.randomBytes ?? (typeof globalThis.crypto?.getRandomValues === "function"
49
+ ? undefined
50
+ : await secureRandomBytes());
51
+ return { ...settings, open, ...(randomBytes === undefined ? {} : { randomBytes }) };
52
+ }, isExpoLockError);
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { sqliteFactory } from "./descriptor.js";
2
2
  export const sqlite = sqliteFactory(async (schema, settings, initialize) => {
3
- if (!settings || typeof settings !== "object" || Reflect.ownKeys(settings).some(key => !["filename", "open", "randomBytes", "transactionTimeoutMs"].includes(key))
3
+ if (!settings || typeof settings !== "object" || Reflect.ownKeys(settings).some(key => !["filename", "open", "randomBytes", "transactionTimeoutMs", "startupRetry"].includes(key))
4
4
  || (settings.filename === undefined) === (settings.open === undefined))
5
5
  throw new TypeError("SQLite requires exactly one of filename or open");
6
6
  let driver;
@@ -0,0 +1,8 @@
1
+ import { type BrowserSQLiteConnection, type SQLiteConnection, type SQLiteFactory } from "./descriptor.ts";
2
+ import { type SQLiteOptions } from "./runtime.ts";
3
+ export { isSQLiteLockResult } from "./descriptor.ts";
4
+ export type { SQLiteConnection, SQLiteFactory } from "./descriptor.ts";
5
+ export type { SQLiteDriver, SQLiteRecord, SQLiteValue } from "./driver.ts";
6
+ type DriverOptions = SQLiteOptions & Pick<BrowserSQLiteConnection, "open">;
7
+ /** Use a platform driver with the shared SQLite engine and instance lifecycle. */
8
+ export declare function createSQLiteAdapter<C extends SQLiteConnection>(resolve: (settings: C) => DriverOptions | PromiseLike<DriverOptions>, isDriverLockError?: (error: unknown) => boolean): SQLiteFactory<C>;
@@ -0,0 +1,10 @@
1
+ import { sqliteFactory } from "./descriptor.js";
2
+ import { openSQLiteDatabase } from "./runtime.js";
3
+ export { isSQLiteLockResult } from "./descriptor.js";
4
+ /** Use a platform driver with the shared SQLite engine and instance lifecycle. */
5
+ export function createSQLiteAdapter(resolve, isDriverLockError) {
6
+ return sqliteFactory(async (schema, settings, initialize) => {
7
+ const options = await resolve(settings);
8
+ return openSQLiteDatabase(schema, await options.open(), options, initialize);
9
+ }, isDriverLockError);
10
+ }
package/dist/runtime.d.ts CHANGED
@@ -2,7 +2,7 @@ import { type WriteDatabase } from "@hulla/db/internal/engine";
2
2
  import type { SchemaDefinition } from "@hulla/db";
3
3
  import type { SQLiteDriver } from "./driver.ts";
4
4
  export interface SQLiteOptions {
5
- /** Platform CSPRNG when Web Crypto is unavailable, e.g. expo-crypto.getRandomBytes. */
5
+ /** Platform CSPRNG when Web Crypto is unavailable. */
6
6
  readonly randomBytes?: (length: number) => Uint8Array;
7
7
  /** Callback deadline, excluding time in the connection queue. Defaults to 5000. */
8
8
  readonly transactionTimeoutMs?: number;
package/dist/runtime.js CHANGED
@@ -1,8 +1,9 @@
1
- import { registerClientStorage, registerStorageExecution, registerStorageChanges, transactionDatabase } from "@hulla/db/internal/engine";
1
+ import { failStorageStartup, registerClientStorage, registerStorageExecution, registerStorageChanges, transactionDatabase } from "@hulla/db/internal/engine";
2
2
  import { SQLiteEngine, sqliteFailure } from "./engine.js";
3
3
  import { sqliteClientStorage } from "./client-storage.js";
4
4
  /** Open schema-typed local storage. The driver belongs exclusively to the returned handle. */
5
5
  export async function openSQLiteDatabase(schema, driver, options = {}, initialize = false) {
6
+ const failOpen = (error) => failStorageStartup(error, () => driver.close());
6
7
  let engine;
7
8
  const timeoutMs = options.transactionTimeoutMs ?? 5000;
8
9
  try {
@@ -11,8 +12,7 @@ export async function openSQLiteDatabase(schema, driver, options = {}, initializ
11
12
  engine = new SQLiteEngine(driver, schema, options.randomBytes);
12
13
  }
13
14
  catch (error) {
14
- await driver.close();
15
- throw error;
15
+ return failOpen(error);
16
16
  }
17
17
  let closed = false, userTransaction = false, queued = 0;
18
18
  let tail = Promise.resolve();
@@ -62,8 +62,7 @@ export async function openSQLiteDatabase(schema, driver, options = {}, initializ
62
62
  storage = sqliteClientStorage(engine, schema, handler => enqueue(handler, true), notify);
63
63
  }
64
64
  catch (error) {
65
- await driver.close();
66
- throw error;
65
+ return failOpen(error);
67
66
  }
68
67
  try {
69
68
  if (initialize)
@@ -72,8 +71,7 @@ export async function openSQLiteDatabase(schema, driver, options = {}, initializ
72
71
  await engine.verify();
73
72
  }
74
73
  catch (error) {
75
- await driver.close();
76
- throw error;
74
+ return failOpen(error);
77
75
  }
78
76
  function guard(operation) {
79
77
  if (typeof operation.table === "string" && storage.isReplica(operation.table)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hulla/db-sqlite",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "type": "module",
5
5
  "description": "SQLite application instances and platform adapters for Hulla schemas",
6
6
  "exports": {
@@ -55,7 +55,9 @@
55
55
  "LICENSE"
56
56
  ],
57
57
  "peerDependencies": {
58
- "@hulla/db": "^0.3.2"
58
+ "@hulla/db": "^0.3.4",
59
+ "expo-crypto": "*",
60
+ "expo-sqlite": "*"
59
61
  },
60
62
  "engines": {
61
63
  "node": ">=22.18.0"
@@ -77,5 +79,13 @@
77
79
  "publishConfig": {
78
80
  "access": "public",
79
81
  "registry": "https://registry.npmjs.org/"
82
+ },
83
+ "peerDependenciesMeta": {
84
+ "expo-crypto": {
85
+ "optional": true
86
+ },
87
+ "expo-sqlite": {
88
+ "optional": true
89
+ }
80
90
  }
81
91
  }