@hulla/db-sqlite 0.3.3 → 0.4.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/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,12 +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.
22
- Expo can use the optional `expo-crypto` peer for secure UUID generation when
23
- Web Crypto is unavailable.
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.
24
25
  Readonly replicas require explicit source URL bindings. Offline mutations queue
25
26
  server calls with mandatory device-side conflict callbacks and optional optimistic
26
27
  feedback. Native Rust SQLite storage and SQLite managed HTTP hosting remain work.
package/dist/browser.d.ts CHANGED
@@ -1,4 +1,5 @@
1
+ import type { BrowserSQLiteConnection } from "./descriptor.ts";
1
2
  export { wasmSQLiteDriver } from "./driver.ts";
2
3
  export type { SQLiteWasmConnection, SQLiteDriver } from "./driver.ts";
3
4
  export type { BrowserSQLiteConnection as SQLiteConnection } from "./descriptor.ts";
4
- export declare const sqlite: import("./descriptor.ts").SQLiteFactory<import("./descriptor.ts").BrowserSQLiteConnection>;
5
+ export declare const sqlite: import("./descriptor.ts").SQLiteFactory<BrowserSQLiteConnection>;
package/dist/browser.js CHANGED
@@ -1,3 +1,8 @@
1
- import { portableSQLite } from "./portable.js";
1
+ import { createSQLiteAdapter } from "./portable.js";
2
2
  export { wasmSQLiteDriver } from "./driver.js";
3
- export const sqlite = portableSQLite();
3
+ export const sqlite = createSQLiteAdapter(settings => {
4
+ if (!settings || typeof settings !== "object" || Reflect.ownKeys(settings).some(key => !["open", "randomBytes", "transactionTimeoutMs", "startupRetry"].includes(key))
5
+ || settings.filename !== undefined || typeof settings.open !== "function")
6
+ throw new TypeError("Browser SQLite requires open: () => a dedicated SQLite driver");
7
+ return settings;
8
+ });
@@ -19,10 +19,11 @@ export type SQLiteConnection = BrowserSQLiteConnection | (SQLiteSettings & {
19
19
  readonly open?: never;
20
20
  });
21
21
  export type Connector<C extends SQLiteConnection = SQLiteConnection> = <S extends SchemaDefinition>(schema: S, settings: C, initialize: boolean) => Promise<ConnectedDatabase<S>>;
22
- 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>;
23
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>;
24
25
  export type SQLiteFactory<C extends SQLiteConnection = SQLiteConnection> = SQLiteConstructor<C> & {
25
26
  readonly initialize: SQLiteConstructor<C>;
26
27
  };
27
- 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>;
28
29
  export {};
@@ -1,6 +1,6 @@
1
1
  import { createDatabase, registerDatabaseFactory } from "@hulla/db/engine";
2
2
  import { DatabaseError } from "@hulla/db/internal/engine";
3
- function isLockResult(code) {
3
+ export function isSQLiteLockResult(code) {
4
4
  if (typeof code !== "number" || !Number.isInteger(code) || code < 0 || code > 0x7fff_ffff)
5
5
  return false;
6
6
  const primary = code & 0xff;
@@ -12,15 +12,9 @@ function isLockError(error) {
12
12
  const { code, errcode, errno, resultCode } = error;
13
13
  if (typeof code === "string" && /^SQLITE_(?:BUSY|LOCKED)(?:_|$)/.test(code))
14
14
  return true;
15
- if (isLockResult(errcode ?? errno ?? resultCode))
16
- return true;
17
- // Expo reports SQLite's result code in the message of its native error.
18
- if (code !== "ERR_INTERNAL_SQLITE_ERROR")
19
- return false;
20
- const result = /\bError code (\d+)\b/.exec(error.message);
21
- return result !== null && isLockResult(Number(result[1]));
15
+ return isSQLiteLockResult(errcode ?? errno ?? resultCode);
22
16
  }
23
- export function sqliteDescriptor(connect) {
17
+ export function sqliteDescriptor(connect, isDriverLockError) {
24
18
  const open = (schema, settings, initialize) => {
25
19
  const policy = settings?.startupRetry;
26
20
  if (policy !== undefined && policy !== false && typeof policy !== "function")
@@ -34,12 +28,14 @@ export function sqliteDescriptor(connect) {
34
28
  retryStartup(error, settings) {
35
29
  if (error instanceof DatabaseError || settings?.startupRetry === false)
36
30
  return false;
37
- return typeof settings?.startupRetry === "function" ? settings.startupRetry(error) === true : isLockError(error);
31
+ return typeof settings?.startupRetry === "function"
32
+ ? settings.startupRetry(error) === true
33
+ : isLockError(error) || isDriverLockError?.(error) === true;
38
34
  },
39
35
  });
40
36
  }
41
- export function sqliteFactory(connect) {
42
- const engine = sqliteDescriptor(connect);
37
+ export function sqliteFactory(connect, isDriverLockError) {
38
+ const engine = sqliteDescriptor(connect, isDriverLockError);
43
39
  const create = (options) => createDatabase(engine, options);
44
40
  const initialize = (options) => createDatabase(engine, options, true);
45
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 { expoSQLiteDriver } from "./driver.ts";
2
- export type { ExpoSQLiteConnection, SQLiteDriver } from "./driver.ts";
3
- export type { BrowserSQLiteConnection as SQLiteConnection } from "./descriptor.ts";
4
- export declare const sqlite: import("./descriptor.ts").SQLiteFactory<import("./descriptor.ts").BrowserSQLiteConnection>;
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,7 +1,13 @@
1
- /// <reference path="./expo-crypto.d.ts" />
2
- import { portableSQLite } from "./portable.js";
3
- export { expoSQLiteDriver } from "./driver.js";
4
- export const sqlite = portableSQLite(async () => {
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() {
5
11
  try {
6
12
  const { getRandomValues } = await import("expo-crypto");
7
13
  if (typeof getRandomValues !== "function")
@@ -13,4 +19,34 @@ export const sqlite = portableSQLite(async () => {
13
19
  throw new TypeError("Install expo-crypto for secure SQLite UUID generation, or supply randomBytes", { cause });
14
20
  };
15
21
  }
16
- });
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);
@@ -1,2 +1,8 @@
1
- import { type BrowserSQLiteConnection } from "./descriptor.ts";
2
- export declare function portableSQLite(resolveRandomBytes?: () => Promise<NonNullable<BrowserSQLiteConnection["randomBytes"]>>): import("./descriptor.ts").SQLiteFactory<BrowserSQLiteConnection>;
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>;
package/dist/portable.js CHANGED
@@ -1,13 +1,10 @@
1
1
  import { sqliteFactory } from "./descriptor.js";
2
2
  import { openSQLiteDatabase } from "./runtime.js";
3
- export function portableSQLite(resolveRandomBytes) {
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) {
4
6
  return sqliteFactory(async (schema, settings, initialize) => {
5
- if (!settings || typeof settings !== "object" || Reflect.ownKeys(settings).some(key => !["open", "randomBytes", "transactionTimeoutMs", "startupRetry"].includes(key))
6
- || settings.filename !== undefined || typeof settings.open !== "function")
7
- throw new TypeError("Browser SQLite requires open: () => a dedicated SQLite driver");
8
- const options = resolveRandomBytes && settings.randomBytes === undefined && typeof globalThis.crypto?.getRandomValues !== "function"
9
- ? { ...settings, randomBytes: await resolveRandomBytes() }
10
- : settings;
11
- return openSQLiteDatabase(schema, await settings.open(), options, initialize);
12
- });
7
+ const options = await resolve(settings);
8
+ return openSQLiteDatabase(schema, await options.open(), options, initialize);
9
+ }, isDriverLockError);
13
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hulla/db-sqlite",
3
- "version": "0.3.3",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "SQLite application instances and platform adapters for Hulla schemas",
6
6
  "exports": {
@@ -55,13 +55,9 @@
55
55
  "LICENSE"
56
56
  ],
57
57
  "peerDependencies": {
58
- "@hulla/db": "^0.3.3",
59
- "expo-crypto": "*"
60
- },
61
- "peerDependenciesMeta": {
62
- "expo-crypto": {
63
- "optional": true
64
- }
58
+ "@hulla/db": "^0.4.0",
59
+ "expo-crypto": "*",
60
+ "expo-sqlite": "*"
65
61
  },
66
62
  "engines": {
67
63
  "node": ">=22.18.0"
@@ -83,5 +79,13 @@
83
79
  "publishConfig": {
84
80
  "access": "public",
85
81
  "registry": "https://registry.npmjs.org/"
82
+ },
83
+ "peerDependenciesMeta": {
84
+ "expo-crypto": {
85
+ "optional": true
86
+ },
87
+ "expo-sqlite": {
88
+ "optional": true
89
+ }
86
90
  }
87
91
  }