@voltro/sql-turso 0.6.0 → 0.7.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/CHANGELOG.md CHANGED
@@ -39,6 +39,26 @@ _Changes staged for the next release accumulate here (rolled up from
39
39
 
40
40
  ---
41
41
 
42
+ ## [0.7.0] — 2026-07-20
43
+
44
+ ### ⚠ BREAKING
45
+
46
+ - **@voltro/runtime** — Row-level security: a `load` failure is now retried, and then surfaces as an **error** instead of an empty result. `setRowFilter({ load, predicate })` resolves `load` once per request; previously ANY failure was answered with a predicate matching zero rows. A downstream app reported the consequence correctly — for shared/team visibility `load` must read the store, so one transient DB blip denied every constrained table for that request and the whole UI rendered empty. Two distinct defects, fixed separately, because conflating them was the original mistake. **A transient failure should never reach the decision:** `load` had no retry at all, so a reaped connection was answered as if it were an authorization fact. It now runs under a bounded `retry` schedule — `DEFAULT_ROW_FILTER_RETRY`, three attempts backing off exponentially from 20ms, so ~60ms worst case — configurable per filter with your own `Schedule`, or `retry: false` for one attempt. **And refusal was expressed as an empty result, which is a lie:** "we could not determine your visibility" and "you may see nothing" are different facts, and only one of them is a fact. An empty list is byte-identical to legitimate emptiness, so the user reads "you have no tickets", the operator reads a healthy 200, and the outage is invisible to both — the most misleading outcome available. The module header used to defend this ("an empty result rather than a 500 on every page"); every constrained page IS broken, and saying so is the correct behavior. `onLoadError` now defaults to `'fail'`, raising the exported typed `RowFilterUnavailable`; `onLoadError: 'deny'` keeps the old degradation for apps that have looked at the screen and genuinely prefer an empty list to an error state, with the `onError` reporter still firing so the choice is not silent. The app asked for `onLoadError: 'fallthrough'` — fail OPEN to the handler's own check. Deliberately not implemented, and not planned. Serving unfiltered rows when the authorization filter is unavailable leaks data precisely when the system is under stress and nobody is reading dashboards, and it is only safe if every handler still carries the check that row filters exist to replace. Fail-closed is retained under both policies; a test asserts neither branch can ever yield an unfiltered read. **Migration.** `resolveRowFilterScope` gains an error channel — `Effect<RowFilterScope, RowFilterUnavailable>` instead of an infallible Effect — so direct callers (a custom entrypoint, a test harness) must handle it; TypeScript points at each one. Apps that want the previous behavior add `onLoadError: 'deny'`, but should decide that rather than default into it. Tests asserting "a broken load yields an empty result" now fail with `RowFilterUnavailable`, which is the fix working. Subscriptions changed shape too: a re-resolve that fails mid-delivery now REVOKES the subscription and emits a typed error frame — following the existing withdrawn-guard precedent — because an empty snapshot on a live subscription reads to a client as "every row you could see was just deleted". The same failure at subscribe time aborts the subscribe instead of opening a stream on a fabricated snapshot, and unwinds the matcher + dependent-table registration it had already made (previously leaked on any subscribe-time throw).
47
+ - **@voltro/testing, @voltro/runtime** — `@voltro/testing` now mirrors the runtime store's POLICY path, not only its DATA path. An adopting app found three places where the harness diverged, each of which made a class of rule untestable in-repo while leaving the suite green. **`invoke` runs Effect-mode handlers.** The framework's contract is "async OR Effect, your choice per handler", and every production runner honours it (`Effect.isEffect(result) ? … : …`). `invoke` only awaited the executor's return value, so an Effect-mode handler handed back its own un-run `EffectPrimitive`: nothing executed, nothing was written, and a test asserting on the "result" asserted on a description of work. The Effect now runs through `runProvidedEffect` — the same function the serve entrypoints use — so a handler failing with a typed error REJECTS WITH THAT ERROR rather than an opaque FiberFailure, and `EffectStore` + `SubjectService` are provided over the context the handler is actually given. Guards, the input decode, the transactional wrap, the deadlock replay, `afterCommit` and the plugin interceptor chain apply identically to both modes. **`makeTestContext({ relations: [spec] })`** registers `relations()` specs. `relations()` is pure — it returns a spec, it does not register one — and production registration is a boot step (`voltro dev` → `registerDiscoveredRelations`), so under the harness an eager load failed with "no relations registered" no matter what the test imported. The option REPLACES the process-global registry with exactly the specs given (the registry is a `Symbol.for` global; additive registration would throw `duplicate relation` on the second `makeTestContext` in a file and leak the first test's relations into the second). Omitting it touches the registry not at all. **The harness store applies row-level security.** After `setRowFilter(...)` a `makeTestContext` read of a constrained table returned the unfiltered set, so "user A cannot see user B's row" could not be asserted at all. `ctx.store` now resolves the filter for its subject and AND-merges it into every read — fluent builders and descriptor reads alike, not bypassed by `.unscoped()`, bypassed for a `system` subject. A new `rowFilter:` option passes a filter directly for tests that would rather not write to a process global. Resolution goes through the runtime's new `resolveRowFilterScopeFor` (`resolveRowFilterScope` is now that function applied to the registered filter), so the retry schedule, the system bypass and the `onLoadError` policy are the runtime's single definition rather than a second copy in the harness. **Breaking, and how to migrate** (`voltro update` prints this): delete any `Effect.isEffect(out) ? await Effect.runPromise(out) : out` shim around an `invoke` call — it is dead code that also destroyed your typed errors. `ProcedureExecutor<Input, Output>` gained an `Effect<Output, E>` arm and an optional third parameter `E` (default `never`); `invoke` now infers from the executor's whole return type instead of taking `Output` as its second type parameter, so an explicit `invoke<typeof d, Note>(…)` type-argument list must be dropped in favour of inference. Handlers themselves keep compiling — what changes is the type of a CALL.
48
+
49
+ ### Added
50
+
51
+ - **@voltro/plugin-auth** — `subjectFromUser(user, { metadata })` now carries arbitrary app metadata onto the Subject. Previously the helper set the metadata slot ONLY when `memberships` were supplied, so an app whose Subject must carry a provider credential — an Atlassian PAT captured at login and read back as `subject.metadata.jiraToken` by `@voltro/plugin-atlassian`'s `credentialsResolver`, say — could not adopt the helper at all: calling it silently dropped the credential, and building the Subject by hand was the only way to keep it. The framework shipped both halves of that gap itself. `metadata` MERGES with the memberships projection rather than replacing it. **Precedence when a `memberships` key appears in both:** the dedicated `memberships` option wins — it is the specific, typed input, and it is the one projected into the `{ tenantId, role }` shape `subjectMemberships()` and the switch-tenant menu read, so letting a free-form bag shadow it would break tenant switching in a way nothing type-checks. Without the option, a `memberships` key inside `metadata` passes through unchanged. A Subject built with neither option still has NO `metadata` key (not an empty object). The later stamps compose unchanged: the sign-in / sign-up / magic-link / passkey handlers spread the existing slot before adding `sessionId`, and the password strategy does the same for `provider`, so keys set through this option survive every login path — unless a caller names a key `sessionId` or `provider`, which those merges overwrite by design. **`handleSwitchTenant` now carries that metadata across a switch**, via a new optional `metadata` on `SwitchTenantInput` (the built-in `/switch-tenant` route passes the caller's `subject.metadata` for you). Without this the option above would have been a trap rather than a feature: a switch rebuilds the Subject from the user record, so an app parking a provider credential in the slot would lose it the first time a user changed tenant — staying authenticated while every call to the provider began failing, with no signal at the point that caused it. `memberships` is deliberately NOT carried: it is re-derived for the target tenant, and a carried copy would report a role the user does not hold there. Covered by a test that fails on the exact assertion when the carry is removed. `SwitchTenantInput` is now exported too — every sibling handler input (`SignInInput`, `MfaVerifyInput`, …) already was, and this one had simply been forgotten, so an app calling `handleSwitchTenant` directly could not name its argument type. Additive: the option is optional and callers that pass neither get byte-identical Subjects. `packages/plugin-auth/etc/plugin-auth.api.md` gains one line and changes none.
52
+ - **@voltro/database** — `timestampMs` and `timestampMsOrNull` — the timestamp wire mapping as STANDALONE field schemas, for hand-written `Schema.Struct` outputs. `Date` in the handler, epoch-ms `number` on the wire; `timestampMsOrNull` is the `.nullable()` column's variant, so a "never archived" row stays `null` instead of becoming `new Date(null)` (1970-01-01, which renders as a plausible date rather than as nothing). ```ts output: Schema.Struct({ id: Schema.String, addedAt: timestampMs, // Date in the handler, epoch ms on the wire archivedAt: timestampMsOrNull, seenAt: Schema.optional(timestampMs), }) ``` This closes the half of the problem `rowSchema(table)` left open. `rowSchema` only helps a handler returning a RAW FULL TABLE ROW, and real handlers overwhelmingly return a COMPUTED struct assembled across several tables — `{ id, name, slug, addedAt, jiraProjectKey }` — where there is no single table to derive from. That is exactly where the hand-written `Date → epoch` converters accumulate: the app that reported the original gap has ~228 of them, all in shaped outputs, and found zero clean applications for whole-row `rowSchema`. Single-sourced, not a parallel declaration: `columnSchema` now READS `timestampMs` for `timestamp()` / `date()` columns, so the derived-row and hand-written-struct paths are the same schema by identity and cannot drift into different wire representations. `rowSchema.test.ts` asserts that identity rather than asserting both merely produce a number. There is deliberately no `timestampMsOptional` — an absent field is `Schema.optional(timestampMs)`, which composes without a third export. Both exports live in the browser-safe `@voltro/database` main entry (pure `effect/Schema`, no driver, no `node:*`), which is what a descriptor's `output` needs. Additive: two new exports, no existing declaration changed. `packages/database/etc/database.api.md` gains two entries and changes none.
53
+
54
+ ### Fixed
55
+
56
+ - **@voltro/sql-turso** — Turso (local Rust engine): pooled connections now WAIT for a held lock instead of failing instantly with `database is locked`. The engine keeps SQLite's default of `PRAGMA busy_timeout = 0`, so any statement that met a lock held by another connection failed on the spot — and with the default pool of 4 connections on one file, two concurrent writers are enough to reach it. `makeConnection` now issues `busy_timeout` for every pooled connection, beside the mandatory MVCC and foreign-key pragmas. MVCC did not cover this and was the reason it was missed: `journal_mode=experimental_mvcc` resolves write-write conflicts BETWEEN transactions, while DDL and the schema lock stay exclusive, so the failure lands on statements the concurrency design appears to have handled. It also only reproduces under CPU contention — green on an idle machine, sporadic under load — which is the worst shape for a defect to have. It surfaced as a flaky `CREATE TABLE` in the MVCC keystone test during a full local gate run, where 78 packages build in parallel; a user would see it as an intermittent `database is locked` under production traffic with no obvious trigger. The default is 5000ms, matching better-sqlite3's own default — which is why the sibling `@voltro/sql-sqlite` never needed this: that driver sets the timeout for us, and the turso NAPI driver does not. Tunable via `busyTimeoutMs` on `makeTursoSqlLayer` / `TursoClientConfig`, beside `maxConnections`; `busyTimeoutMs: 0` explicitly restores the fail-immediately behavior (asserted by a test, so the default can never be implemented as a floor that silently ignores 0). It is deliberately NOT on the cross-dialect `ConnectionConfig` — that shape stays free of engine-specific knobs, the same reason the Turso auth token is env-sourced rather than threaded through it.
57
+ - **@voltro/cli** — `voltro update` now honors the project's actual package manager instead of defaulting to npm. It resolves the manager by walking from the app directory **up to the repo root**, preferring the corepack `packageManager` field over a lockfile (`pnpm-lock.yaml` / `yarn.lock` / `bun.lock` / `bun.lockb` / `package-lock.json`), and only falls back to npm when nothing declares one. Walking up fixes the workspace case: a scaffolded project keeps its lockfile at the monorepo root, so running `voltro update` from `apps/api` previously found no lockfile and ran `npm install` against a pnpm/yarn workspace — writing a stray lockfile and a nested `node_modules`. The resolved manager is also used for the latest-version registry lookup (`pnpm view` / `yarn` / `bun pm view`, with `npm view` as a last-resort fallback), so a private or scoped registry configured in `.npmrc` / `.yarnrc.yml` is honored. The yarn query dispatches on the installed yarn MAJOR version rather than probing berry syntax first: on yarn classic, `yarn npm info …` parses as `yarn run npm` and **executes a `npm` script from the project's package.json** if one exists — verified against yarn 1.22.22. Resolving a version number must never run user code, so classic gets `yarn info … --silent` and only berry (>=2) gets `yarn npm info`. All three managers are verified against real binaries in throwaway Docker containers — yarn classic 1.22.22, yarn berry 4.6.0, bun 1.3.14 — each asserting both that the query resolves a version and that it does not execute a same-named script. Re-run with `node scripts/smoke-package-managers.mjs`.
58
+ - **@voltro/cli** — Three fixes to `voltro update`, all reported by an app upgrading a pnpm workspace. **The bump is now LOCKSTEP across the whole workspace.** `voltro update` in `apps/api` bumped only that `package.json`, leaving the sibling web app and shared `packages/*` on the previous version — an api on 0.6.0 and a web client on 0.5.0 disagree about the generated rpcGroup types and the session cookie shape, and that disagreement surfaces as a runtime decode error, not a build error. When the app sits inside a workspace (`pnpm-workspace.yaml`, or a `workspaces` field in an ancestor `package.json`, found by the same bounded upward walk that resolves the package manager and stops at the first `.git`), every member `package.json` that declares `@voltro/*` is bumped to the target together, and the install runs **once at the workspace root** — running it inside `apps/api` corrupts a pnpm/yarn workspace's layout. Each file that will be bumped is listed in the plan output and in `--dry-run`. A standalone (non-workspace) project is unchanged: its own `package.json`, its own install, in place. The codemod re-exec now also looks for the installed `voltro` bin at the workspace root, since npm and yarn hoist it there. **A failed install now says that the codemods were skipped.** It previously printed only "install failed — package.json was bumped; fix the install and re-run", never mentioning codemods, so a user could boot on target-version code with source shaped for the old one and no signal as to why. The codemods for a jump ship *inside* the target version, which a failed install did not put on disk, so running them is impossible rather than merely undesirable — the fix is the message. It now states plainly that no codemods were applied, why, and prints the exact copy-pasteable recovery command with the concrete versions: `voltro update --codemods-only --from <from> --to <to>`. **`--help` / `-h` is answered before every guard.** `voltro update --help` on a dirty tree printed "working tree is not clean" — at precisely the moment the user was trying to discover `--dry-run` and `--codemods-only`. Help is documentation, not an operation, so it is now handled first, ahead of the `package.json` check, the `@voltro/*`-deps check and the clean-tree guard, and lists every flag (`--to`, `--from`, `--root`, `--dry-run`, `--force`, `--exact`, `--codemods-only`). `voltro doctor --help` had the same shape — it fell through to the preflight and reported on the tree instead — and gets the same treatment. `voltro help`'s `update` line now names `--from` and `--codemods-only` too.
59
+
60
+ ---
61
+
42
62
  ## [0.6.0] — 2026-07-19
43
63
 
44
64
  ### ⚠ BREAKING
package/dist/index.d.ts CHANGED
@@ -119,6 +119,13 @@ export declare interface TursoClientConfig {
119
119
  * pool would split state).
120
120
  */
121
121
  readonly maxConnections?: number | undefined;
122
+ /**
123
+ * How long a statement waits for a held lock before failing with
124
+ * `database is locked`, in milliseconds. Default 5000; `0` restores the
125
+ * engine's fail-immediately behavior. See the pragma in `makeConnection` for
126
+ * why a non-zero default is mandatory with a pool.
127
+ */
128
+ readonly busyTimeoutMs?: number | undefined;
122
129
  readonly prepareCacheSize?: number | undefined;
123
130
  readonly prepareCacheTTL?: Duration.DurationInput | undefined;
124
131
  readonly spanAttributes?: Record<string, unknown> | undefined;
@@ -134,6 +141,8 @@ export declare interface TursoConnection {
134
141
  readonly readonly?: boolean;
135
142
  /** Connection-pool size (the MVCC write-concurrency knob). */
136
143
  readonly maxConnections?: number;
144
+ /** Lock-wait before `database is locked`, ms. Default 5000; `0` fails at once. */
145
+ readonly busyTimeoutMs?: number;
137
146
  }
138
147
 
139
148
  export declare const tursoDialect: SqlDialect;
package/dist/index.js CHANGED
@@ -9,28 +9,28 @@ import { connect as te } from "@tursodatabase/database";
9
9
  import { createLogger as g } from "@voltro/logger";
10
10
  import { createClient as _ } from "@libsql/client";
11
11
  //#region src/sqlClient.ts
12
- var v = g({ scope: "voltro:turso" }), y = "db.system.name", ne = /no transaction is active|no active transaction|cannot rollback|cannot commit/i, b = s.unsafeMake(!1), x = (e) => o.locally(e, b, !0), S = Symbol.for("@voltro/sql-turso/TursoClient"), C = i.GenericTag("@voltro/sql-turso/TursoClient"), w = (e) => (t) => {
12
+ var v = g({ scope: "voltro:turso" }), y = "db.system.name", b = /no transaction is active|no active transaction|cannot rollback|cannot commit/i, x = s.unsafeMake(!1), S = (e) => o.locally(e, x, !0), C = Symbol.for("@voltro/sql-turso/TursoClient"), w = i.GenericTag("@voltro/sql-turso/TursoClient"), T = (e) => (t) => {
13
13
  let n = t?.message;
14
14
  return new m({
15
15
  cause: t,
16
16
  message: typeof n == "string" ? `${e}: ${n}` : e
17
17
  });
18
- }, re = /file is locked|locking error|failed locking file/i, T = (e) => (t) => {
18
+ }, ne = /file is locked|locking error|failed locking file/i, E = (e) => (t) => {
19
19
  let n = String(t?.message ?? t);
20
- return re.test(n) ? new m({
20
+ return ne.test(n) ? new m({
21
21
  cause: t,
22
22
  message: `@voltro/sql-turso: database file '${e}' is locked by another process. Turso is single-process (it takes an exclusive file lock) — you cannot run multiple instances / replicas against one file. For a multi-replica deployment use DB_DIALECT=postgres (or mysql / mariadb / mssql).`
23
23
  }) : new m({
24
24
  cause: t,
25
25
  message: `Failed to open Turso database: ${n}`
26
26
  });
27
- }, E = (e) => o.gen(function* () {
27
+ }, D = (e) => o.gen(function* () {
28
28
  let r = yield* o.scope, c = yield* o.tryPromise({
29
29
  try: () => te(e.filename, {
30
30
  readonly: e.readonly ?? !1,
31
31
  experimental: ["attach"]
32
32
  }),
33
- catch: T(e.filename)
33
+ catch: E(e.filename)
34
34
  });
35
35
  yield* u.addFinalizer(r, o.promise(async () => {
36
36
  try {
@@ -38,50 +38,55 @@ var v = g({ scope: "voltro:turso" }), y = "db.system.name", ne = /no transaction
38
38
  } catch {}
39
39
  })), yield* o.tryPromise({
40
40
  try: () => c.pragma("journal_mode=experimental_mvcc", void 0),
41
- catch: w("Failed to enable Turso MVCC (journal_mode=experimental_mvcc)")
41
+ catch: T("Failed to enable Turso MVCC (journal_mode=experimental_mvcc)")
42
42
  }), yield* o.tryPromise({
43
43
  try: () => c.pragma("foreign_keys=ON", void 0),
44
- catch: w("Failed to enable foreign-key enforcement (foreign_keys=ON)")
44
+ catch: T("Failed to enable foreign-key enforcement (foreign_keys=ON)")
45
45
  });
46
- let l = (e) => c.prepare(e), f = yield* t.make({
46
+ let l = e.busyTimeoutMs ?? 5e3;
47
+ yield* o.tryPromise({
48
+ try: () => c.pragma(`busy_timeout=${l}`, void 0),
49
+ catch: T(`Failed to set lock-wait timeout (busy_timeout=${l})`)
50
+ });
51
+ let f = (e) => c.prepare(e), h = yield* t.make({
47
52
  capacity: e.prepareCacheSize ?? 200,
48
53
  timeToLive: e.prepareCacheTTL ?? a.minutes(10),
49
54
  lookup: (e) => o.try({
50
- try: () => l(e),
51
- catch: w("Failed to prepare statement")
55
+ try: () => f(e),
56
+ catch: T("Failed to prepare statement")
52
57
  })
53
- }), h = (e, t, n) => o.withFiberRuntime((r) => (i.get(r.currentContext, p.SafeIntegers) && e.safeIntegers(!0), e.reader ? o.tryPromise({
58
+ }), g = (e, t, n) => o.withFiberRuntime((r) => (i.get(r.currentContext, p.SafeIntegers) && e.safeIntegers(!0), e.reader ? o.tryPromise({
54
59
  try: () => e.all(...t),
55
- catch: w("Failed to execute statement")
60
+ catch: T("Failed to execute statement")
56
61
  }) : o.tryPromise({
57
62
  try: async () => {
58
63
  let r = await e.run(...t);
59
64
  return n ? r : [];
60
65
  },
61
- catch: w("Failed to execute statement")
62
- }))), g = (e, t, n = !1) => o.flatMap(f.get(e), (e) => h(e, t, n)), _ = (e, t) => o.acquireUseRelease(f.get(e), (e) => o.tryPromise({
66
+ catch: T("Failed to execute statement")
67
+ }))), _ = (e, t, n = !1) => o.flatMap(h.get(e), (e) => g(e, t, n)), v = (e, t) => o.acquireUseRelease(h.get(e), (e) => o.tryPromise({
63
68
  try: async () => e.reader ? (e.raw(!0), await e.all(...t)) : (await e.run(...t), []),
64
- catch: w("Failed to execute statement")
69
+ catch: T("Failed to execute statement")
65
70
  }), (e) => o.sync(() => {
66
71
  e.reader && e.raw(!1);
67
72
  }));
68
73
  return ee({
69
74
  execute(e, t, n) {
70
- return n ? o.map(g(e, t), n) : g(e, t);
75
+ return n ? o.map(_(e, t), n) : _(e, t);
71
76
  },
72
77
  executeRaw(e, t) {
73
- return g(e, t, !0);
78
+ return _(e, t, !0);
74
79
  },
75
80
  executeValues(e, t) {
76
- return _(e, t);
81
+ return v(e, t);
77
82
  },
78
83
  executeUnprepared(e, t, n) {
79
- let r = o.flatMap(s.get(b), (n) => {
84
+ let r = o.flatMap(s.get(x), (n) => {
80
85
  let r = n && e === "BEGIN" ? "BEGIN CONCURRENT" : e;
81
86
  return o.acquireUseRelease(o.try({
82
- try: () => l(r),
83
- catch: w("Failed to prepare statement")
84
- }), (e) => h(e, t ?? [], !1).pipe(o.catchIf((e) => ne.test(String(e?.message ?? "")), () => o.succeed([]))), (e) => o.sync(() => {
87
+ try: () => f(r),
88
+ catch: T("Failed to prepare statement")
89
+ }), (e) => g(e, t ?? [], !1).pipe(o.catchIf((e) => b.test(String(e?.message ?? "")), () => o.succeed([]))), (e) => o.sync(() => {
85
90
  try {
86
91
  e.close();
87
92
  } catch {}
@@ -91,8 +96,8 @@ var v = g({ scope: "voltro:turso" }), y = "db.system.name", ne = /no transaction
91
96
  },
92
97
  executeStream(e, t, r) {
93
98
  let i = d.acquireRelease(o.try({
94
- try: () => l(e),
95
- catch: w("Failed to prepare statement")
99
+ try: () => f(e),
100
+ catch: T("Failed to prepare statement")
96
101
  }), (e) => o.sync(() => {
97
102
  try {
98
103
  e.close();
@@ -104,11 +109,11 @@ var v = g({ scope: "voltro:turso" }), y = "db.system.name", ne = /no transaction
104
109
  return r ? d.mapChunks(i, (e) => n.unsafeFromArray(r(n.toReadonlyArray(e)))) : i;
105
110
  }
106
111
  });
107
- }), D = (e) => o.gen(function* () {
112
+ }), O = (e) => o.gen(function* () {
108
113
  let t = h.makeCompilerSqlite(e.transformQueryNames), n = e.transformResultNames ? h.defaultTransforms(e.transformResultNames).array : void 0, r = e.filename === ":memory:" || e.filename === "" || e.filename.startsWith("file::memory:"), i = e.maxConnections ?? 4;
109
114
  r && i > 1 && v.warn(`:memory: Turso DB is per-connection — clamping pool size ${i} → 1`);
110
115
  let a = r ? 1 : Math.max(1, i), o = yield* l.make({
111
- acquire: E(e),
116
+ acquire: D(e),
112
117
  size: a
113
118
  }), s = l.get(o), c = l.get(o), u = yield* p.make({
114
119
  acquirer: s,
@@ -119,77 +124,77 @@ var v = g({ scope: "voltro:turso" }), y = "db.system.name", ne = /no transaction
119
124
  transformRows: n
120
125
  });
121
126
  return Object.assign(u, {
122
- [S]: S,
127
+ [C]: C,
123
128
  config: e
124
129
  });
125
- }), ie = (e) => c.scopedContext(r.unwrap(e).pipe(o.flatMap(D), o.map((e) => i.make(C, e).pipe(i.add(p.SqlClient, e))))).pipe(c.provide(f.layer)), ae = g({ scope: "voltro:turso:libsql" }), oe = "db.system.name", O = Symbol.for("@voltro/sql-turso/LibsqlClient"), k = i.GenericTag("@voltro/sql-turso/LibsqlClient"), A = (e) => (t) => {
130
+ }), re = (e) => c.scopedContext(r.unwrap(e).pipe(o.flatMap(O), o.map((e) => i.make(w, e).pipe(i.add(p.SqlClient, e))))).pipe(c.provide(f.layer)), ie = g({ scope: "voltro:turso:libsql" }), ae = "db.system.name", k = Symbol.for("@voltro/sql-turso/LibsqlClient"), A = i.GenericTag("@voltro/sql-turso/LibsqlClient"), j = (e) => (t) => {
126
131
  let n = t?.message;
127
132
  return new m({
128
133
  cause: t,
129
134
  message: typeof n == "string" ? `${e}: ${n}` : e
130
135
  });
131
- }, se = (e, t) => {
136
+ }, oe = (e, t) => {
132
137
  let n = {};
133
138
  for (let r of t) n[r] = e[r];
134
139
  return n;
135
- }, j = (e) => e.rows.map((t) => se(t, e.columns)), M = (e) => e.rows.map((t) => e.columns.map((e, n) => t[n])), N = (e) => e, P = (e) => /^\s*BEGIN\b/i.test(e), F = (e) => /^\s*(COMMIT|END)\b/i.test(e), I = (e) => /^\s*ROLLBACK\b/i.test(e), L = (e) => ({
140
+ }, M = (e) => e.rows.map((t) => oe(t, e.columns)), N = (e) => e.rows.map((t) => e.columns.map((e, n) => t[n])), P = (e) => e, F = (e) => /^\s*BEGIN\b/i.test(e), I = (e) => /^\s*(COMMIT|END)\b/i.test(e), L = (e) => /^\s*ROLLBACK\b/i.test(e), R = (e) => ({
136
141
  execute(t, n, r) {
137
142
  let i = o.map(o.tryPromise({
138
143
  try: () => e(t, n),
139
- catch: A("Failed to execute statement")
140
- }), j);
144
+ catch: j("Failed to execute statement")
145
+ }), M);
141
146
  return r ? o.map(i, r) : i;
142
147
  },
143
148
  executeRaw(t, n) {
144
149
  return o.map(o.tryPromise({
145
150
  try: () => e(t, n),
146
- catch: A("Failed to execute statement")
147
- }), j);
151
+ catch: j("Failed to execute statement")
152
+ }), M);
148
153
  },
149
154
  executeValues(t, n) {
150
155
  return o.map(o.tryPromise({
151
156
  try: () => e(t, n),
152
- catch: A("Failed to execute statement")
153
- }), M);
157
+ catch: j("Failed to execute statement")
158
+ }), N);
154
159
  },
155
160
  executeUnprepared(t, n, r) {
156
161
  let i = o.map(o.tryPromise({
157
162
  try: () => e(t, n),
158
- catch: A("Failed to execute statement")
159
- }), j);
163
+ catch: j("Failed to execute statement")
164
+ }), M);
160
165
  return r ? o.map(i, r) : i;
161
166
  },
162
167
  executeStream(t, r, i) {
163
168
  let a = d.fromIterableEffect(o.map(o.tryPromise({
164
169
  try: () => e(t, r),
165
- catch: A("Failed to stream statement")
166
- }), j));
170
+ catch: j("Failed to stream statement")
171
+ }), M));
167
172
  return i ? d.mapChunks(a, (e) => n.unsafeFromArray(i(n.toReadonlyArray(e)))) : a;
168
173
  }
169
- }), R = (e) => L((t, n) => n.length === 0 ? e.execute(t) : e.execute({
174
+ }), z = (e) => R((t, n) => n.length === 0 ? e.execute(t) : e.execute({
170
175
  sql: t,
171
- args: N(n)
172
- })), z = (e) => o.gen(function* () {
176
+ args: P(n)
177
+ })), B = (e) => o.gen(function* () {
173
178
  let t = yield* o.scope, n = yield* o.tryPromise({
174
179
  try: () => e.transaction("write"),
175
- catch: A("Failed to begin transaction")
180
+ catch: j("Failed to begin transaction")
176
181
  });
177
182
  return yield* u.addFinalizer(t, o.sync(() => {
178
183
  try {
179
184
  n.close();
180
185
  } catch {}
181
- })), L((e, t) => P(e) ? Promise.resolve(B) : F(e) ? n.commit().then(() => B) : I(e) ? n.rollback().then(() => B) : t.length === 0 ? n.execute(e) : n.execute({
186
+ })), R((e, t) => F(e) ? Promise.resolve(V) : I(e) ? n.commit().then(() => V) : L(e) ? n.rollback().then(() => V) : t.length === 0 ? n.execute(e) : n.execute({
182
187
  sql: e,
183
- args: N(t)
188
+ args: P(t)
184
189
  }));
185
- }), B = {
190
+ }), V = {
186
191
  columns: [],
187
192
  columnTypes: [],
188
193
  rows: [],
189
194
  rowsAffected: 0,
190
195
  lastInsertRowid: void 0,
191
196
  toJSON: () => ({})
192
- }, V = (e) => e.url.startsWith("file:") && e.syncUrl !== void 0, H = (e) => o.gen(function* () {
197
+ }, H = (e) => e.url.startsWith("file:") && e.syncUrl !== void 0, U = (e) => o.gen(function* () {
193
198
  let t = h.makeCompilerSqlite(e.transformQueryNames), n = e.transformResultNames ? h.defaultTransforms(e.transformResultNames).array : void 0, r = {
194
199
  url: e.url,
195
200
  ...e.authToken === void 0 ? {} : { authToken: e.authToken },
@@ -197,11 +202,11 @@ var v = g({ scope: "voltro:turso" }), y = "db.system.name", ne = /no transaction
197
202
  ...e.syncInterval === void 0 ? {} : { syncInterval: a.toSeconds(a.decode(e.syncInterval)) },
198
203
  ...e.readYourWrites === void 0 ? {} : { readYourWrites: e.readYourWrites },
199
204
  ...e.encryptionKey === void 0 ? {} : { encryptionKey: e.encryptionKey }
200
- }, i = V(e);
201
- ae.info(`libsql client: ${i ? "embedded replica" : "remote"} (url scheme=${e.url.split(":")[0]}${e.syncUrl ? ", sync enabled" : ""})`);
205
+ }, i = H(e);
206
+ ie.info(`libsql client: ${i ? "embedded replica" : "remote"} (url scheme=${e.url.split(":")[0]}${e.syncUrl ? ", sync enabled" : ""})`);
202
207
  let s = yield* o.acquireRelease(o.try({
203
208
  try: () => _(r),
204
- catch: A("Failed to create libsql client")
209
+ catch: j("Failed to create libsql client")
205
210
  }), (e) => o.sync(() => {
206
211
  try {
207
212
  e.close();
@@ -209,31 +214,31 @@ var v = g({ scope: "voltro:turso" }), y = "db.system.name", ne = /no transaction
209
214
  }));
210
215
  i && (yield* o.tryPromise({
211
216
  try: () => s.sync(),
212
- catch: A("Failed initial embedded-replica sync")
217
+ catch: j("Failed initial embedded-replica sync")
213
218
  }));
214
- let c = o.succeed(R(s)), l = z(s), u = yield* p.make({
219
+ let c = o.succeed(z(s)), l = B(s), u = yield* p.make({
215
220
  acquirer: c,
216
221
  compiler: t,
217
222
  transactionAcquirer: l,
218
223
  beginTransaction: "BEGIN",
219
- spanAttributes: [...e.spanAttributes ? Object.entries(e.spanAttributes) : [], [oe, "turso"]],
224
+ spanAttributes: [...e.spanAttributes ? Object.entries(e.spanAttributes) : [], [ae, "turso"]],
220
225
  transformRows: n
221
226
  });
222
227
  return Object.assign(u, {
223
- [O]: O,
228
+ [k]: k,
224
229
  config: e
225
230
  });
226
- }), U = (e) => c.scopedContext(r.unwrap(e).pipe(o.flatMap(H), o.map((e) => i.make(k, e).pipe(i.add(p.SqlClient, e))))).pipe(c.provide(f.layer)), W = /^(libsql|wss?|https?):/i, G = () => process.env.DB_AUTH_TOKEN ?? process.env.TURSO_AUTH_TOKEN, ce = () => process.env.DB_SYNC_URL ?? process.env.TURSO_SYNC_URL, le = () => {
231
+ }), W = (e) => c.scopedContext(r.unwrap(e).pipe(o.flatMap(U), o.map((e) => i.make(A, e).pipe(i.add(p.SqlClient, e))))).pipe(c.provide(f.layer)), G = /^(libsql|wss?|https?):/i, K = () => process.env.DB_AUTH_TOKEN ?? process.env.TURSO_AUTH_TOKEN, se = () => process.env.DB_SYNC_URL ?? process.env.TURSO_SYNC_URL, ce = () => {
227
232
  let e = process.env.DB_SYNC_INTERVAL ?? process.env.TURSO_SYNC_INTERVAL;
228
233
  if (e === void 0 || e.trim() === "") return;
229
234
  let t = Number(e);
230
235
  if (!Number.isFinite(t) || t <= 0) throw Error(`@voltro/sql-turso: invalid DB_SYNC_INTERVAL '${e}' — expected a positive number of seconds.`);
231
236
  return t;
232
- }, ue = () => process.env.DB_ENCRYPTION_KEY ?? process.env.TURSO_ENCRYPTION_KEY, de = () => {
237
+ }, le = () => process.env.DB_ENCRYPTION_KEY ?? process.env.TURSO_ENCRYPTION_KEY, ue = () => {
233
238
  let e = process.env.DB_READ_YOUR_WRITES;
234
239
  if (e !== void 0) return e !== "false" && e !== "0";
235
- }, K = (e, t, n) => {
236
- let r = le(), i = de(), a = ue();
240
+ }, q = (e, t, n) => {
241
+ let r = ce(), i = ue(), a = le();
237
242
  return {
238
243
  kind: "remote",
239
244
  url: e,
@@ -243,13 +248,13 @@ var v = g({ scope: "voltro:turso" }), y = "db.system.name", ne = /no transaction
243
248
  ...i === void 0 ? {} : { readYourWrites: i },
244
249
  ...a === void 0 ? {} : { encryptionKey: a }
245
250
  };
246
- }, q = (e) => {
247
- let t = e.maxConnections, n = t === void 0 ? {} : { maxConnections: t }, r = ce();
251
+ }, J = (e) => {
252
+ let t = e.maxConnections, n = t === void 0 ? {} : { maxConnections: t }, r = se();
248
253
  if (e.url) {
249
- if (W.test(e.url)) {
250
- let t = G();
254
+ if (G.test(e.url)) {
255
+ let t = K();
251
256
  if (t === void 0) throw Error(`@voltro/sql-turso: remote Turso url '${e.url}' needs an auth token. Set DB_AUTH_TOKEN (or TURSO_AUTH_TOKEN) to the token from 'turso db tokens create <db>'.`);
252
- return K(e.url, t, r);
257
+ return q(e.url, t, r);
253
258
  }
254
259
  if (e.url === ":memory:") return {
255
260
  kind: "local",
@@ -258,9 +263,9 @@ var v = g({ scope: "voltro:turso" }), y = "db.system.name", ne = /no transaction
258
263
  };
259
264
  if (e.url.startsWith("file:")) {
260
265
  if (r !== void 0) {
261
- let t = G();
266
+ let t = K();
262
267
  if (t === void 0) throw Error(`@voltro/sql-turso: embedded replica (file '${e.url}' + DB_SYNC_URL='${r}') needs an auth token for the remote primary. Set DB_AUTH_TOKEN (or TURSO_AUTH_TOKEN).`);
263
- return K(e.url, t, r);
268
+ return q(e.url, t, r);
264
269
  }
265
270
  return {
266
271
  kind: "local",
@@ -276,33 +281,34 @@ var v = g({ scope: "voltro:turso" }), y = "db.system.name", ne = /no transaction
276
281
  ...n
277
282
  };
278
283
  throw Error("@voltro/sql-turso: no url/filename supplied. Set DB_URL=file:./db.turso (local), DB_URL=libsql://<db>.turso.io + DB_AUTH_TOKEN (remote), or DB_DATABASE=path/to/db.turso.");
279
- }, J = (e) => ie({
284
+ }, Y = (e) => re({
280
285
  filename: r.succeed(e.filename),
281
286
  ...e.readonly === void 0 ? {} : { readonly: r.succeed(e.readonly) },
282
- ...e.maxConnections === void 0 ? {} : { maxConnections: r.succeed(e.maxConnections) }
283
- }), Y = (e) => U({
287
+ ...e.maxConnections === void 0 ? {} : { maxConnections: r.succeed(e.maxConnections) },
288
+ ...e.busyTimeoutMs === void 0 ? {} : { busyTimeoutMs: r.succeed(e.busyTimeoutMs) }
289
+ }), X = (e) => W({
284
290
  url: r.succeed(e.url),
285
291
  ...e.authToken === void 0 ? {} : { authToken: r.succeed(e.authToken) },
286
292
  ...e.syncUrl === void 0 ? {} : { syncUrl: r.succeed(e.syncUrl) },
287
293
  ...e.syncIntervalSeconds === void 0 ? {} : { syncInterval: r.succeed(`${e.syncIntervalSeconds} seconds`) },
288
294
  ...e.readYourWrites === void 0 ? {} : { readYourWrites: r.succeed(e.readYourWrites) },
289
295
  ...e.encryptionKey === void 0 ? {} : { encryptionKey: r.succeed(e.encryptionKey) }
290
- }), X = (e) => {
291
- let t = q(e);
292
- return t.kind === "remote" ? Y(t) : J(t);
293
- }, fe = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, pe = /* @__PURE__ */ new Set([
296
+ }), Z = (e) => {
297
+ let t = J(e);
298
+ return t.kind === "remote" ? X(t) : Y(t);
299
+ }, de = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, fe = /* @__PURE__ */ new Set([
294
300
  "SQLITE_BUSY",
295
301
  "SQLITE_LOCKED",
296
302
  "5",
297
303
  "6"
298
- ]), Z = (e, t) => {
304
+ ]), pe = (e, t) => {
299
305
  let n = e, r = "";
300
306
  for (let e = 0; e < 6 && typeof n == "object" && n; e++) {
301
307
  let e = t(n);
302
308
  e !== void 0 && (r += ` ${e}`), n = n.cause;
303
309
  }
304
310
  return r;
305
- }, me = (e) => Z(e, (e) => typeof e.message == "string" ? e.message : void 0), he = (e) => {
311
+ }, me = (e) => pe(e, (e) => typeof e.message == "string" ? e.message : void 0), he = (e) => {
306
312
  let t = e;
307
313
  for (let e = 0; e < 6 && typeof t == "object" && t; e++) {
308
314
  let e = t.code;
@@ -311,20 +317,20 @@ var v = g({ scope: "voltro:turso" }), y = "db.system.name", ne = /no transaction
311
317
  t = t.cause;
312
318
  }
313
319
  }, Q = (e) => {
314
- if (fe.test(me(e))) return !0;
320
+ if (de.test(me(e))) return !0;
315
321
  let t = he(e);
316
- return t !== void 0 && pe.has(t);
322
+ return t !== void 0 && fe.has(t);
317
323
  }, $ = (e) => Q(e) ? "retry" : "noRetry", ge = {
318
324
  id: "turso",
319
- makeSqlLayer: (e) => X(e),
325
+ makeSqlLayer: (e) => Z(e),
320
326
  makeStore: (t) => e({
321
327
  ...t,
322
328
  isRetryable: Q,
323
329
  systemName: "turso",
324
- wrapTransaction: x
330
+ wrapTransaction: S
325
331
  }),
326
332
  compileContains: (e, t, n) => n`${e} LIKE ${`%${t.replace(/[\\%_]/g, (e) => `\\${e}`)}%`} ESCAPE '\\'`,
327
333
  retryFilter: $
328
334
  };
329
335
  //#endregion
330
- export { k as LibsqlClient, C as TursoClient, q as connectionFromConfig, Q as isTursoRetryableFailure, Y as makeLibsqlSqlLayer, J as makeTursoSqlLayer, X as makeTursoSqlLayerFromConfig, ge as tursoDialect, $ as tursoRetryFilter };
336
+ export { A as LibsqlClient, w as TursoClient, J as connectionFromConfig, Q as isTursoRetryableFailure, X as makeLibsqlSqlLayer, Y as makeTursoSqlLayer, Z as makeTursoSqlLayerFromConfig, ge as tursoDialect, $ as tursoRetryFilter };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/sql-turso",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Turso dialect adapter for Voltro's cross-dialect DataStore — local Rust SQLite with MVCC BEGIN CONCURRENT, or remote Turso Cloud (libsql://) with embedded-replica sync.",
5
5
  "keywords": [
6
6
  "voltro",
@@ -36,9 +36,9 @@
36
36
  "@effect/sql": "^0.51.1",
37
37
  "@libsql/client": "^0.17.4",
38
38
  "@tursodatabase/database": "^0.6.1",
39
- "@voltro/database": "0.6.0",
40
- "@voltro/logger": "0.6.0",
41
- "@voltro/sql-sqlite": "0.6.0"
39
+ "@voltro/database": "0.7.0",
40
+ "@voltro/logger": "0.7.0",
41
+ "@voltro/sql-sqlite": "0.7.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "effect": "^3.21.4"