clanka 0.8.4 → 0.8.6

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 (36) hide show
  1. package/dist/AgentSkills.test.js +1 -0
  2. package/dist/AgentSkills.test.js.map +1 -1
  3. package/dist/AgentTools.d.ts.map +1 -1
  4. package/dist/AgentTools.js +2 -1
  5. package/dist/AgentTools.js.map +1 -1
  6. package/dist/Compaction.test.js +1 -0
  7. package/dist/Compaction.test.js.map +1 -1
  8. package/dist/CompactionTransport.test.js +1 -1
  9. package/dist/CompactionTransport.test.js.map +1 -1
  10. package/dist/bin/{Effect-BmOuzEIp.mjs → Effect-rADALOOD.mjs} +477 -267
  11. package/dist/bin/Effect-rADALOOD.mjs.map +1 -0
  12. package/dist/bin/{McpClient-CLpFJSre.mjs → McpClient-NazR2OwL.mjs} +219 -63
  13. package/dist/bin/McpClient-NazR2OwL.mjs.map +1 -0
  14. package/dist/bin/{OutputFormatter-C_gdNUl1.mjs → OutputFormatter-BVHbgF2b.mjs} +8 -8
  15. package/dist/bin/OutputFormatter-BVHbgF2b.mjs.map +1 -0
  16. package/dist/bin/{Schema-C7W9nQug.mjs → Schema-C7NXAOWA.mjs} +642 -88
  17. package/dist/bin/Schema-C7NXAOWA.mjs.map +1 -0
  18. package/dist/bin/{SemanticSearch-cqSnq90g.mjs → SemanticSearch-4Jes3jCl.mjs} +135 -90
  19. package/dist/bin/SemanticSearch-4Jes3jCl.mjs.map +1 -0
  20. package/dist/bin/{Stream-BI6Fx9yq.mjs → Stream-CSLA1_GD.mjs} +69 -48
  21. package/dist/bin/Stream-CSLA1_GD.mjs.map +1 -0
  22. package/dist/bin/cli.mjs +2865 -5333
  23. package/dist/bin/cli.mjs.map +1 -1
  24. package/dist/bin/{turndown.cjs-usmCKZ4b.mjs → turndown.cjs-DK29wZw3.mjs} +2 -2
  25. package/dist/bin/{turndown.cjs-usmCKZ4b.mjs.map → turndown.cjs-DK29wZw3.mjs.map} +1 -1
  26. package/package.json +15 -15
  27. package/src/AgentSkills.test.ts +1 -0
  28. package/src/AgentTools.ts +2 -1
  29. package/src/Compaction.test.ts +1 -0
  30. package/src/CompactionTransport.test.ts +1 -1
  31. package/dist/bin/Effect-BmOuzEIp.mjs.map +0 -1
  32. package/dist/bin/McpClient-CLpFJSre.mjs.map +0 -1
  33. package/dist/bin/OutputFormatter-C_gdNUl1.mjs.map +0 -1
  34. package/dist/bin/Schema-C7W9nQug.mjs.map +0 -1
  35. package/dist/bin/SemanticSearch-cqSnq90g.mjs.map +0 -1
  36. package/dist/bin/Stream-BI6Fx9yq.mjs.map +0 -1
@@ -1,17 +1,17 @@
1
- import { $ as isEffect, $a as match, $o as hasProperty, $t as uninterruptibleMask, As as pipe, B as fnUntraced, Ba as flatten, Bi as isArrayNonEmpty, Br as succeed$2, C as catch_, Ca as Reference, D as delay, Da as get$1, Di as void_$2, Do as withFiber$1, Dr as doneUnsafe, Ds as identity, E as contextWith, Ei as updateContext, Er as done, Es as flow, Et as provideService, F as filterOrFail, Fr as failCause, Go as symbol, Gt as tap, H as forEach, Ha as fromNullishOr, Hr as ClockRef, I as flatMap, It as scope, Ja as isNone, Jo as hash, Jr as contextWith$1, K as forkScoped, Ki as map$2, Kt as tapCause, La as filter, Li as flatMapNullishOr, Ln as filterInterruptors, Lt as scoped, M as fail, Ma as make$9, Mr as makeUnsafe$2, Mt as runFork, Ni as empty, Ns as pipeArguments, Nt as runForkWith, O as die, Oa as getOption, Pa as merge, Pr as fail$1, Qa as map$1, Qo as symbol$1, Qr as exitHasInterrupts, Ri as fromIterable, Rr as isFailure, S as catchTags, Ss as constUndefined, St as orElseSucceed, T as context, Ta as add, Ts as dual, Tt as provideContext, U as forever, Uo as byReferenceUnsafe, Ut as suspend, Vn as hasInterruptsOnly, Vr as void_$3, Vt as succeed, Wo as equals, Wt as sync, X as ignore, Xa as isSome, Xi as sort, Xt as try_, Y as gen, Yt as tryPromise, Z as interrupt, Zr as endSpan, _o as Prototype, _r as close, _t as onExit, a as andThen, at as makeSpanScoped, ba as toMillis, bo as PipeInspectableProto, c as as, da as infinity, eo as none, er as effect, et as logDebug, fn as Class$1, ft as matchCauseEager, ga as minutes, gi as makeSpanUnsafe, gt as onError, h as catchDefect, ha as millis, hr as addFinalizer, i as all, ja as getUnsafe, ka as getOrUndefined, ki as ParentSpan, kn as NoSuchElementError, ko as assignProperty, kr as into, kt as request$1, ln as withSpan, lr as provide$1, lt as mapError, m as catchCause, ma as isZero, mr as Scope, n as acquireUseRelease, nn as useSpan, nr as effectDiscard, o as annotateCurrentSpan, on as withFiber, os as isNotNull, ot as map, pa as isFinite, po as make$10, pt as matchCauseEffect, ri as fiberInterrupt, rn as void_$1, ro as some, rt as logInfo, s as annotateLogs, si as fiberJoin, sn as withLogSpan, so as Number$1, t as acquireRelease, tr as effectContext, u as asVoid, ua as fromInputUnsafe, ui as forkUnsafe, ur as provideMerge, v as catchIf, vi as onExit$1, vt as onExitPrimitive, wa as Service, wr as TracerTimingEnabled, x as catchTag, xi as succeed$1, xr as provide, xt as orDie, y as catchNoSuchElement, ya as seconds, yr as make$8, z as fn, zr as isSuccess, zt as serviceOption } from "./Effect-BmOuzEIp.mjs";
2
- import { $ as tap$1, B as provideService$1, Ft as join$1, H as runCollect, It as runIn, Pt as interruptAs, T as fromQueue, U as runDrain, bt as offerUnsafe, c as die$1, ct as make$12, g as flatMap$1, gt as make$11, ht as failCauseUnsafe, lt as makeUnsafe$3, tt as unwrap, v as fromArray, y as fromArrayEffect } from "./Stream-BI6Fx9yq.mjs";
3
- import { A as OptionFromNullOr, Cn as transform, D as NullOr, Dt as mutable, F as String$1, Ft as toType, I as Struct$2, In as formatIsoDate, It as withConstructorDefault, J as Union$2, Jn as TaggedError$1, O as Number$2, Ot as optional, Rn as now, S as Natural, St as isSchema, Wn as Clock, Z as brand, _n as transform$1, bn as dateTimeUtcFromInput, c as DateTimeUtcFromDate, d as Defect, i as BooleanFromBit, k as Option, kt as optionalKey, l as DateTimeUtcFromMillis, n as ArraySchema, nt as decodeTo, o as Class$2, ot as encodeEffect, r as Boolean, rt as decodeUnknownEffect, s as DateTimeUtc, u as DateTimeUtcFromString, ut as instanceOf, xn as map$3, yn as transformOptional, z as TaggedError, zn as removeTime, zt as evolve } from "./Schema-C7W9nQug.mjs";
4
- import { C as set, D as toPredicate, E as has, S as remove, T as compose, _ as empty$1, a as makeGrouped, b as isEmpty, c as SemanticSearch, d as map$4, f as make$14, g as FileSystem, h as Path, i as batchN, l as maybeRemoveFile, m as Console, n as EmbeddingModel, o as setDelay, p as ChildProcessSpawner, r as EmbeddingRequest, s as withSpan$1, t as Dimensions, u as maybeUpdateFile, v as forEach$1, w as size, x as make$13, y as get$2 } from "./cli.mjs";
1
+ import { $a as getOrUndefined, $n as fromReasons, An as spaced, Ar as Scope, At as request$1, B as fn, Ba as minutes, Br as TracerTimingEnabled, Bt as serviceOption, C as catchTags, Cn as size, Co as match, Ct as orElseSucceed, D as contextWith, Di as forkUnsafe, Do as some, Ds as symbol$1, Dt as provideService, E as context, Er as provideMerge, Et as provideContext, Fr as make$7, Fs as isNotNull, Gi as void_$2, Gr as into, Gt as sync, Hr as done, Ht as succeed, I as filterOrFail, Ia as isFinite, Ja as Service, Jr as makeUnsafe$2, Ka as zero, Kn as combine, Kt as tap, L as flatMap, La as isZero, Li as onExitUnsafe, Lo as make$10, Lr as provide, Lt as scope, Mt as retry, N as fail, Na as fromInputUnsafe, Ni as makeSpanUnsafe, Nr as close, Nt as runFork, O as delay, Os as hasProperty, P as failCause$1, Pa as infinity, Pt as runForkWith, Q as interrupt, Qa as getOption, Qr as failCause, Rt as scoped, S as catchTag, Sn as set, So as map$1, St as orDie, Tr as provide$1, U as forEach$1, Ua as seconds, Ur as doneUnsafe, V as fnUntraced, Vn as NoSuchElementError, Vo as Prototype, W as forever, Wa as toMillis, Wi as updateContext, Wo as PipeInspectableProto, Wt as suspend, X as gen, Xi as has, Xn as filterInterruptors, Xt as tryPromise, Ya as add, Yi as compose, Z as ignore, Za as get$1, Zi as toPredicate, Zr as fail$1, Zs as constUndefined, Zt as try_, _n as forEach, _r as effectContext, _s as equals, _t as onError, a as andThen, aa as flatMapNullishOr, ac as pipe, ai as ClockRef, ar as isFailReason, b as catchNoSuchElement, bi as fiberInterrupt, bn as make$8, bo as isSome, c as as, ca as isArrayNonEmpty, cc as pipeArguments, cn as withLogSpan, cr as makeDieReason, di as contextWith$1, ec as dual, en as uninterruptibleMask, es as withFiber$1, et as isEffect, fo as fromNullishOr, g as catchDefect, gn as empty$1, gr as effect, gs as byReferenceUnsafe, hi as exitHasInterrupts, i as all, ii as void_$3, in as void_$1, io as merge, it as logInfo, jo as Number$1, jr as addFinalizer, k as die, m as catchCause, ma as map$2, mi as endSpan, mn as Class$1, mt as matchCauseEffect, n as acquireUseRelease, nc as identity, ni as isSuccess, no as make$9, ns as assignProperty, o as annotateCurrentSpan, oa as fromIterable, ot as makeSpanScoped, pr as reasonAnnotations, pt as matchCauseEager, q as forkScoped, qa as Reference, qi as ParentSpan, qt as tapCause, ri as succeed$2, rn as useSpan, s as annotateLogs, sn as withFiber, so as filter, st as map, t as acquireRelease, ta as empty, tc as flow, ti as isFailure, to as getUnsafe, tr as hasInterruptsOnly, tt as logDebug, u as asVoid, un as withSpan, uo as flatten, ut as mapError, va as sort, vn as get$2, vo as isNone, vr as effectDiscard, vs as symbol, vt as onExit, w as catch_, wi as fiberJoin, wo as none, xn as remove, xs as hash, y as catchIf, yn as isEmpty, yt as onExitPrimitive, za as millis, zi as succeed$1 } from "./Effect-rADALOOD.mjs";
2
+ import { $ as tap$1, B as provideService$1, Ft as interruptAs, H as runCollect, It as join$1, Lt as runIn, T as fromQueue, U as runDrain, bt as offerUnsafe, c as die$1, ct as make$12, g as flatMap$1, gt as make$11, ht as failCauseUnsafe, lt as makeUnsafe$3, tt as unwrap, v as fromArray, y as fromArrayEffect } from "./Stream-CSLA1_GD.mjs";
3
+ import { A as Option, At as optionalKey, B as TaggedError, Bn as now, C as Natural, Cn as map$3, I as String$1, Kn as Clock, L as Struct$2, Lt as toType, O as NullOr, Ot as mutable, Q as brand, Rn as formatIsoDate, Rt as withConstructorDefault, Sn as dateTimeUtcFromInput, Tn as transform, Vn as removeTime, Vt as evolve, Y as Union$2, Zn as TaggedError$1, c as DateTimeUtcFromDate, d as Defect, dt as instanceOf, i as BooleanFromBit, it as decodeUnknownEffect, j as OptionFromNullOr, k as Number$2, kt as optional, l as DateTimeUtcFromMillis, n as ArraySchema, o as Class$2, qn as monotonicTimeNanos, r as Boolean, rt as decodeTo, s as DateTimeUtc, st as encodeEffect, u as DateTimeUtcFromString, wt as isSchema, xn as transformOptional, yn as transform$1 } from "./Schema-C7NXAOWA.mjs";
4
+ import { a as makeGrouped, c as SemanticSearch, d as map$4, f as make$13, g as FileSystem, h as Path, i as batchN, l as maybeRemoveFile, m as Console, n as EmbeddingModel, o as setDelay, p as ChildProcessSpawner, r as EmbeddingRequest, s as withSpan$1, t as Dimensions, u as maybeUpdateFile } from "./cli.mjs";
5
5
  import { createHash } from "node:crypto";
6
6
  import { DatabaseSync, backup } from "node:sqlite";
7
7
  import TreeSitter from "tree-sitter";
8
8
  import TreeSitterJavaScript from "tree-sitter-javascript";
9
9
  import TreeSitterTypeScript from "tree-sitter-typescript";
10
10
  import { getLoadablePath } from "sqlite-vec";
11
- //#region node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/reactivity/Reactivity.js
11
+ //#region node_modules/.pnpm/effect@4.0.4/node_modules/effect/dist/reactivity/Reactivity.js
12
12
  const TypeId$6 = "~effect/reactivity/Reactivity";
13
13
  const Reactivity = Service("effect/reactivity/Reactivity");
14
- const make$7 = sync(() => {
14
+ const make$6 = sync(() => {
15
15
  const handlers = new Map();
16
16
  const invalidateUnsafe = (keys) => {
17
17
  keysToHashes(keys, (hash) => {
@@ -100,7 +100,7 @@ const make$7 = sync(() => {
100
100
  });
101
101
  });
102
102
  var PendingInvalidation = class extends Service()("effect/reactivity/Reactivity/PendingInvalidation") {};
103
- const layer$5 = effect(Reactivity)(make$7);
103
+ const layer$5 = effect(Reactivity)(make$6);
104
104
  function stringOrHash(u) {
105
105
  switch (typeof u) {
106
106
  case "string":
@@ -122,7 +122,7 @@ const keysToHashes = (keys, f) => {
122
122
  }
123
123
  };
124
124
  //#endregion
125
- //#region node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/sql/SqlError.js
125
+ //#region node_modules/.pnpm/effect@4.0.4/node_modules/effect/dist/sql/SqlError.js
126
126
  const TypeId$5 = "~effect/sql/SqlError";
127
127
  const ReasonTypeId = "~effect/sql/SqlError/Reason";
128
128
  const ReasonFields = {
@@ -296,7 +296,7 @@ var ResultLengthMismatch = class extends TaggedError("effect/sql/ResultLengthMis
296
296
  }
297
297
  };
298
298
  //#endregion
299
- //#region node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/sql/Statement.js
299
+ //#region node_modules/.pnpm/effect@4.0.4/node_modules/effect/dist/sql/Statement.js
300
300
  const FragmentTypeId = "~effect/sql/Statement/Fragment";
301
301
  const fragment = (segments) => ({
302
302
  [FragmentTypeId]: FragmentTypeId,
@@ -352,7 +352,7 @@ const recordUpdateHelperSingle = (value, omit) => Object.assign(Object.create(Re
352
352
  omit,
353
353
  returningIdentifier: void 0
354
354
  });
355
- const make$6 = (acquirer, compiler, spanAttributes, transformRows, borrower) => {
355
+ const make$5 = (acquirer, compiler, spanAttributes, transformRows, borrower) => {
356
356
  const cache = transformRows === void 0 ? constructorCache.noTransforms : constructorCache.transforms;
357
357
  if (cache.has(acquirer)) return cache.get(acquirer);
358
358
  const self = Object.assign(function sql(strings, ...args) {
@@ -652,8 +652,27 @@ const defaultTransforms = (transformer, nested = true) => {
652
652
  array
653
653
  };
654
654
  };
655
- const ATTR_DB_OPERATION_NAME = "db.operation.name";
655
+ const spanTarget = (spanAttributes) => {
656
+ const namespace = spanAttribute(spanAttributes, "db.namespace");
657
+ if (isNonEmptyString(namespace)) return namespace;
658
+ const address = spanAttribute(spanAttributes, "server.address");
659
+ if (isNonEmptyString(address)) {
660
+ const port = spanAttribute(spanAttributes, "server.port");
661
+ return port === void 0 ? address : `${address}:${port}`;
662
+ }
663
+ };
664
+ const spanName = (spanAttributes) => {
665
+ const target = spanTarget(spanAttributes);
666
+ if (target !== void 0) return target;
667
+ const system = spanAttribute(spanAttributes, "db.system.name");
668
+ return isNonEmptyString(system) ? system : "sql.execute";
669
+ };
656
670
  const ATTR_DB_QUERY_TEXT = "db.query.text";
671
+ const ATTR_SQL_METHOD = "effect.sql.method";
672
+ const spanAttribute = (spanAttributes, key) => {
673
+ for (let i = spanAttributes.length - 1; i >= 0; i--) if (spanAttributes[i][0] === key) return spanAttributes[i][1];
674
+ };
675
+ const isNonEmptyString = (u) => typeof u === "string" && u.length > 0;
657
676
  const makeUnsafe$1 = (segments, acquirer, compiler, spanAttributes, transformRows, borrower) => {
658
677
  const self = Object.create(StatementProto);
659
678
  self.segments = segments;
@@ -667,13 +686,13 @@ const makeUnsafe$1 = (segments, acquirer, compiler, spanAttributes, transformRow
667
686
  const StatementProto = {
668
687
  [FragmentTypeId]: FragmentTypeId,
669
688
  withConnection(operation, f, withoutTransform = false) {
670
- return useSpan("sql.execute", { kind: "client" }, (span) => this.withConnectionSpan(operation, f, withoutTransform, span));
689
+ return useSpan(spanName(this.spanAttributes), { kind: "client" }, (span) => this.withConnectionSpan(operation, f, withoutTransform, span));
671
690
  },
672
691
  withConnectionSpan(operation, f, withoutTransform, span) {
673
692
  return withStatement(this, span, (statement, fiber) => {
674
693
  const [sql, params] = statement.compile(withoutTransform);
675
694
  for (const [key, value] of this.spanAttributes) span.attribute(key, value);
676
- span.attribute(ATTR_DB_OPERATION_NAME, operation);
695
+ span.attribute(ATTR_SQL_METHOD, operation);
677
696
  span.attribute(ATTR_DB_QUERY_TEXT, sql);
678
697
  const execute = this.borrower === void 0 ? scoped(flatMap(this.acquirer, (_) => f(_, sql, params))) : this.borrower((connection) => f(connection, sql, params));
679
698
  return fiber.cache.tracerEnabled && fiber.getRef(SpanPropagationEnabled) ? provideService(execute, ParentSpan, span) : execute;
@@ -687,10 +706,10 @@ const StatementProto = {
687
706
  },
688
707
  get stream() {
689
708
  const self = this;
690
- return unwrap(flatMap(makeSpanScoped("sql.execute", { kind: "client" }), (span) => withStatement(self, span, (statement, fiber) => {
709
+ return unwrap(flatMap(makeSpanScoped(spanName(self.spanAttributes), { kind: "client" }), (span) => withStatement(self, span, (statement, fiber) => {
691
710
  const [sql, params] = statement.compile();
692
711
  for (const [key, value] of self.spanAttributes) span.attribute(key, value);
693
- span.attribute(ATTR_DB_OPERATION_NAME, "executeStream");
712
+ span.attribute(ATTR_SQL_METHOD, "executeStream");
694
713
  span.attribute(ATTR_DB_QUERY_TEXT, sql);
695
714
  const acquire = map(self.acquirer, (_) => _.executeStream(sql, params, self.transformRows));
696
715
  return fiber.cache.tracerEnabled && fiber.getRef(SpanPropagationEnabled) ? succeed(provideService$1(unwrap(acquire), ParentSpan, span)) : acquire;
@@ -709,7 +728,7 @@ const StatementProto = {
709
728
  ...Prototype({
710
729
  label: "Statement",
711
730
  evaluate(fiber) {
712
- const span = makeSpanUnsafe(fiber, "sql.execute", { kind: "client" });
731
+ const span = makeSpanUnsafe(fiber, spanName(this.spanAttributes), { kind: "client" });
713
732
  const clock = fiber.getRef(Clock);
714
733
  const timingEnabled = fiber.getRef(TracerTimingEnabled);
715
734
  return onExit(this.withConnectionSpan("execute", (connection, sql, params) => connection.execute(sql, params, this.transformRows), false, span), (exit) => endSpan(span, exit, clock, timingEnabled));
@@ -731,7 +750,7 @@ const StatementProto = {
731
750
  const withStatement = (self, span, f) => withFiber((fiber) => {
732
751
  const transform = fiber.getRef(CurrentTransformer);
733
752
  if (transform === void 0) return f(self, fiber);
734
- return flatMap(transform(self, make$6(self.acquirer, self.compiler, self.spanAttributes, self.transformRows, self.borrower), fiber, span), (statement) => f(statement, fiber));
753
+ return flatMap(transform(self, make$5(self.acquirer, self.compiler, self.spanAttributes, self.transformRows, self.borrower), fiber, span), (statement) => f(statement, fiber));
735
754
  });
736
755
  const isSegment = (u) => {
737
756
  if (!hasProperty(u, "_tag")) return false;
@@ -786,12 +805,12 @@ function in_() {
786
805
  }
787
806
  const neverFragment = fragment([literal("1=0")]);
788
807
  //#endregion
789
- //#region node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/sql/SqlClient.js
808
+ //#region node_modules/.pnpm/effect@4.0.4/node_modules/effect/dist/sql/SqlClient.js
790
809
  const TypeId$4 = "~effect/sql/SqlClient";
791
810
  const SqlClient = Service("effect/sql/SqlClient");
792
811
  let clientIdCounter = 0;
793
812
  let transactionSemaphoreIdCounter = 0;
794
- const make$5 = fnUntraced(function* (options) {
813
+ const make$4 = fnUntraced(function* (options) {
795
814
  const transactionService = options.transactionService ?? TransactionConnection(clientIdCounter++);
796
815
  const getConnection = flatMap(serviceOption(transactionService), match({
797
816
  onNone: () => options.acquirer,
@@ -808,7 +827,7 @@ const make$5 = fnUntraced(function* (options) {
808
827
  const withTransaction = makeWithTransaction({
809
828
  transactionService,
810
829
  spanAttributes: options.spanAttributes,
811
- acquireConnection: flatMap(make$8(), (scope) => provide(transactionAcquirer, scope).pipe(onError((cause) => close(scope, failCause(cause))), map((conn) => [scope, conn]))),
830
+ acquireConnection: flatMap(make$7(), (scope) => provide(transactionAcquirer, scope).pipe(onError((cause) => close(scope, failCause(cause))), map((conn) => [scope, conn]))),
812
831
  begin: (conn) => control(conn, beginTransaction),
813
832
  savepoint: (conn, id) => control(conn, savepoint(`effect_sql_${id}`)),
814
833
  releaseSavepoint: releaseSavepoint ? (conn, id) => control(conn, releaseSavepoint(`effect_sql_${id}`)) : void 0,
@@ -822,7 +841,7 @@ const make$5 = fnUntraced(function* (options) {
822
841
  onNone: () => options.borrower(f),
823
842
  onSome: ([conn]) => f(conn)
824
843
  }));
825
- const client = Object.assign(make$6(getConnection, options.compiler, options.spanAttributes, options.transformRows, borrower), {
844
+ const client = Object.assign(make$5(getConnection, options.compiler, options.spanAttributes, options.transformRows, borrower), {
826
845
  [TypeId$4]: TypeId$4,
827
846
  safe: void 0,
828
847
  withTransaction,
@@ -830,7 +849,7 @@ const make$5 = fnUntraced(function* (options) {
830
849
  reserve: transactionAcquirer,
831
850
  withoutTransforms() {
832
851
  if (options.transformRows === void 0) return this;
833
- const statement = make$6(getConnection, options.compiler.withoutTransform, options.spanAttributes, void 0, borrower);
852
+ const statement = make$5(getConnection, options.compiler.withoutTransform, options.spanAttributes, void 0, borrower);
834
853
  const client = Object.assign(statement, {
835
854
  ...this,
836
855
  ...statement
@@ -867,9 +886,10 @@ const makeSqliteAcquirers = (options) => {
867
886
  }
868
887
  });
869
888
  });
889
+ const lease = uninterruptibleMask((restore) => flatMap(scope, (scope) => restore(semaphore.take(1)).pipe(andThen(addFinalizer(scope, semaphore.release(1))), andThen(available))));
870
890
  return {
871
- acquirer: semaphore.withPermits(1)(available),
872
- transactionAcquirer: uninterruptibleMask((restore) => flatMap(scope, (scope) => restore(semaphore.take(1)).pipe(andThen(addFinalizer(scope, semaphore.release(1))), andThen(available)))),
891
+ acquirer: lease,
892
+ transactionAcquirer: lease,
873
893
  onCommitFailure: (conn) => tapCause(rollback(conn), (cause) => sync(() => poison(cause)))
874
894
  };
875
895
  };
@@ -878,9 +898,10 @@ const isNoTransactionError = (error) => {
878
898
  const message = typeof cause === "string" ? cause : hasProperty(cause, "message") && typeof cause.message === "string" ? cause.message : "";
879
899
  return /no transaction is active/i.test(message);
880
900
  };
901
+ const failuresToDefects = (cause) => fromReasons(cause.reasons.map((reason) => isFailReason(reason) ? makeDieReason(reason.error).annotate(reasonAnnotations(reason)) : reason));
881
902
  const makeWithTransaction = (options) => {
882
903
  const transactionSemaphore = Service(`effect/sql/SqlClient/TransactionSemaphore/${transactionSemaphoreIdCounter++}`);
883
- return (effect) => uninterruptibleMask((restore) => useSpan("sql.transaction", { kind: "client" }, (span) => withFiber((fiber) => {
904
+ return (effect) => uninterruptibleMask((restore) => useSpan("sql.transaction", { kind: "internal" }, (span) => withFiber((fiber) => {
884
905
  for (const [key, value] of options.spanAttributes) span.attribute(key, value);
885
906
  const services = fiber.context;
886
907
  const clock = fiber.getRef(Clock);
@@ -891,16 +912,18 @@ const makeWithTransaction = (options) => {
891
912
  let effect;
892
913
  if (isSuccess(exit)) {
893
914
  if (id === 0) {
894
- span.event("db.transaction.commit", clock.currentTimeNanosUnsafe());
915
+ span.event("effect.sql.transaction.commit", clock.currentTimeNanosUnsafe());
895
916
  const onCommitFailure = options.onCommitFailure;
896
- effect = orDie(options.commit(conn));
897
- if (onCommitFailure) effect = onError(effect, () => orDie(onCommitFailure(conn)));
917
+ effect = onCommitFailure ? catchCause(options.commit(conn), (commitCause) => matchCauseEffect(onCommitFailure(conn), {
918
+ onFailure: (cleanupCause) => failCause$1(failuresToDefects(combine(commitCause, cleanupCause))),
919
+ onSuccess: () => failCause$1(commitCause)
920
+ })) : options.commit(conn);
898
921
  } else {
899
- span.event("db.transaction.savepoint", clock.currentTimeNanosUnsafe());
922
+ span.event("effect.sql.transaction.savepoint", clock.currentTimeNanosUnsafe());
900
923
  effect = void_$1;
901
924
  }
902
925
  } else {
903
- span.event("db.transaction.rollback", clock.currentTimeNanosUnsafe());
926
+ span.event("effect.sql.transaction.rollback", clock.currentTimeNanosUnsafe());
904
927
  effect = orDie(id > 0 ? options.rollbackSavepoint(conn, id) : options.rollback(conn));
905
928
  }
906
929
  if (id > 0 && options.releaseSavepoint) effect = andThen(effect, orDie(options.releaseSavepoint(conn, id)));
@@ -912,20 +935,16 @@ const makeWithTransaction = (options) => {
912
935
  const TransactionConnection = (clientId) => Service(`effect/sql/SqlClient/TransactionConnection/${clientId}`);
913
936
  const SafeIntegers = Reference("effect/sql/SqlClient/SafeIntegers", { defaultValue: () => false });
914
937
  //#endregion
915
- //#region node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/Cache.js
938
+ //#region node_modules/.pnpm/effect@4.0.4/node_modules/effect/dist/Cache.js
916
939
  const TypeId$3 = "~effect/Cache";
917
940
  const makeWith = (lookup, options) => contextWith$1((context) => {
918
941
  const self = Object.create(Proto$1);
919
942
  self.lookup = (key) => updateContext(lookup(key), (input) => merge(context, input));
920
- self.map = make$13();
943
+ self.map = make$8();
921
944
  self.capacity = options.capacity;
922
945
  self.timeToLive = options.timeToLive ? (exit, key) => fromInputUnsafe(options.timeToLive(exit, key)) : defaultTimeToLive;
923
946
  return succeed$1(self);
924
947
  });
925
- const make$4 = (options) => makeWith(options.lookup, {
926
- ...options,
927
- timeToLive: options.timeToLive !== void 0 ? () => options.timeToLive : defaultTimeToLive
928
- });
929
948
  const Proto$1 = {
930
949
  ...PipeInspectableProto,
931
950
  [TypeId$3]: TypeId$3,
@@ -944,49 +963,57 @@ const get = dual(2, (self, key) => withFiber$1((fiber) => {
944
963
  remove(self.map, key);
945
964
  if (!hasExpired(oentry.value, fiber)) {
946
965
  set(self.map, key, oentry.value);
947
- return oentry.value.await();
966
+ return oentry.value.await(fiber);
948
967
  }
949
968
  }
950
969
  const entry = new EntryImpl(fiber, self.lookup(key));
970
+ entry.onInterrupt = () => removeEntry(self, key, entry);
951
971
  let skipCache = false;
952
972
  entry.fiber.addObserver((exit) => {
973
+ entry.onInterrupt = void 0;
953
974
  if (exitHasInterrupts(exit)) {
954
- const current = get$2(self.map, key);
955
- if (isSome(current) && current.value === entry) remove(self.map, key);
975
+ removeEntry(self, key, entry);
956
976
  return;
957
977
  }
958
978
  const ttl = self.timeToLive(exit, key);
959
979
  if (isZero(ttl)) {
960
980
  skipCache = true;
961
- const current = get$2(self.map, key);
962
- if (isSome(current) && current.value === entry) remove(self.map, key);
981
+ removeEntry(self, key, entry);
963
982
  } else if (isFinite(ttl)) entry.expiresAt = fiber.getRef(ClockRef).currentTimeMillisUnsafe() + toMillis(ttl);
964
983
  });
965
984
  const exit = entry.fiber.pollUnsafe();
966
985
  if (!skipCache && (exit === void 0 || !exitHasInterrupts(exit))) set(self.map, key, entry);
967
986
  if (Number.isFinite(self.capacity)) checkCapacity(self);
968
- return entry.await();
987
+ return entry.await(fiber);
969
988
  }));
970
989
  var EntryImpl = class {
971
990
  expiresAt;
972
991
  awaiters;
973
992
  fiber;
993
+ onInterrupt;
974
994
  constructor(parent, valueEffect) {
975
995
  this.fiber = forkUnsafe(parent, valueEffect, true, true);
976
996
  this.awaiters = 0;
977
997
  this.expiresAt = void 0;
978
998
  }
979
- await() {
999
+ await(fiber) {
1000
+ if (fiber === void 0) return withFiber$1((fiber) => this.await(fiber));
980
1001
  const exit = this.fiber.pollUnsafe();
981
1002
  if (exit) return exit;
982
1003
  this.awaiters++;
983
- return onExit$1(fiberJoin(this.fiber), () => {
1004
+ onExitUnsafe(fiber, () => {
984
1005
  this.awaiters--;
985
1006
  if (this.awaiters > 0 || this.fiber.pollUnsafe()) return void_$2;
1007
+ this.onInterrupt?.();
986
1008
  return fiberInterrupt(this.fiber);
987
1009
  });
1010
+ return fiberJoin(this.fiber);
988
1011
  }
989
1012
  };
1013
+ const removeEntry = (self, key, entry) => {
1014
+ const current = get$2(self.map, key);
1015
+ if (isSome(current) && current.value === entry) remove(self.map, key);
1016
+ };
990
1017
  const hasExpired = (entry, fiber) => {
991
1018
  if (entry.expiresAt === void 0) return false;
992
1019
  return fiber.getRef(ClockRef).currentTimeMillisUnsafe() >= entry.expiresAt;
@@ -1001,7 +1028,7 @@ const checkCapacity = (self) => {
1001
1028
  }
1002
1029
  };
1003
1030
  //#endregion
1004
- //#region node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/schema/VariantSchema.js
1031
+ //#region node_modules/.pnpm/effect@4.0.4/node_modules/effect/dist/schema/VariantSchema.js
1005
1032
  const TypeId$2 = "~effect/schema/VariantSchema";
1006
1033
  const cacheSymbol = Symbol.for(`${TypeId$2}/cache`);
1007
1034
  const defaultCacheSymbol = Symbol.for(`${TypeId$2}/defaultCache`);
@@ -1106,7 +1133,7 @@ const Union$1 = (members, defaultVariant, variants) => {
1106
1133
  return VariantUnion;
1107
1134
  };
1108
1135
  //#endregion
1109
- //#region node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/schema/Model.js
1136
+ //#region node_modules/.pnpm/effect@4.0.4/node_modules/effect/dist/schema/Model.js
1110
1137
  const { Class, Field, FieldExcept, FieldOnly, Struct, Union, extract, fieldEvolve } = make$3({
1111
1138
  variants: [
1112
1139
  "select",
@@ -1180,7 +1207,7 @@ const DateTimeUpdateFromNumber = Field({
1180
1207
  json: DateTimeUtcFromMillis
1181
1208
  });
1182
1209
  //#endregion
1183
- //#region node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/sql/SqlResolver.js
1210
+ //#region node_modules/.pnpm/effect@4.0.4/node_modules/effect/dist/sql/SqlResolver.js
1184
1211
  const SqlRequestProto = {
1185
1212
  ...Class$1.prototype,
1186
1213
  [symbol](that) {
@@ -1237,7 +1264,7 @@ const findById = (options) => {
1237
1264
  request.value.completeUnsafe(succeed$2(result));
1238
1265
  }
1239
1266
  if (isEmpty(idMap)) return;
1240
- forEach$1(idMap, (request) => {
1267
+ forEach(idMap, (request) => {
1241
1268
  request.completeUnsafe(constNoSuchElement);
1242
1269
  });
1243
1270
  })
@@ -1311,14 +1338,14 @@ function transactionKey(entry) {
1311
1338
  return byReferenceUnsafe(conn);
1312
1339
  }
1313
1340
  //#endregion
1314
- //#region node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/sql/SqlSchema.js
1341
+ //#region node_modules/.pnpm/effect@4.0.4/node_modules/effect/dist/sql/SqlSchema.js
1315
1342
  const findAll = (options) => {
1316
1343
  const encodeRequest = encodeEffect(options.Request);
1317
1344
  const decode = decodeUnknownEffect(mutable(ArraySchema(options.Result)));
1318
1345
  return (request) => flatMap(flatMap(encodeRequest(request), options.execute), decode);
1319
1346
  };
1320
1347
  //#endregion
1321
- //#region node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/sql/SqlModel.js
1348
+ //#region node_modules/.pnpm/effect@4.0.4/node_modules/effect/dist/sql/SqlModel.js
1322
1349
  const makeResolvers = (Model, options) => gen(function* () {
1323
1350
  const sql = yield* SqlClient;
1324
1351
  const idSchema = Model.fields[options.idColumn];
@@ -1331,7 +1358,7 @@ const makeResolvers = (Model, options) => gen(function* () {
1331
1358
  Request: Model.insert,
1332
1359
  Result: Model,
1333
1360
  execute: (request) => sql.onDialectOrElse({
1334
- mysql: () => forEach(request, (request) => sql`insert into ${sql(options.tableName)} ${sql.insert(request)};
1361
+ mysql: () => forEach$1(request, (request) => sql`insert into ${sql(options.tableName)} ${sql.insert(request)};
1335
1362
  select * from ${sql(options.tableName)} where ${withSoftDeleteFilter(sql`${sql(idColumn)} = LAST_INSERT_ID()`)};`.unprepared.pipe(map(([, results]) => results[0])), { concurrency: 10 }),
1336
1363
  orElse: () => sql`insert into ${sql(options.tableName)} ${sql.insert(request).returning("*")}`
1337
1364
  })
@@ -1884,7 +1911,7 @@ const layer$3 = effect(CodeChunker, gen(function* () {
1884
1911
  const listFiles = fn("CodeChunker.listFiles")(function* (options) {
1885
1912
  const root = pathService.resolve(options.root);
1886
1913
  const maxFileSize = options.maxFileSize ?? "1M";
1887
- return yield* pipe(spawner.streamLines(make$14("rg", [
1914
+ return yield* pipe(spawner.streamLines(make$13("rg", [
1888
1915
  "--files",
1889
1916
  "--hidden",
1890
1917
  "--max-filesize",
@@ -1932,7 +1959,7 @@ const layer$3 = effect(CodeChunker, gen(function* () {
1932
1959
  });
1933
1960
  }));
1934
1961
  //#endregion
1935
- //#region node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/FiberHandle.js
1962
+ //#region node_modules/.pnpm/effect@4.0.4/node_modules/effect/dist/FiberHandle.js
1936
1963
  const TypeId$1 = "~effect/FiberHandle";
1937
1964
  const isFiberHandle = (u) => hasProperty(u, TypeId$1);
1938
1965
  const Proto = {
@@ -1966,16 +1993,17 @@ const setUnsafe = dual((args) => isFiberHandle(args[0]), (self, fiber, options)
1966
1993
  if (self.state._tag === "Closed") {
1967
1994
  fiber.interruptUnsafe(internalFiberId);
1968
1995
  return;
1969
- } else if (self.state.fiber !== void 0) {
1970
- if (self.state.fiber === fiber) return;
1996
+ }
1997
+ const previous = self.state.fiber;
1998
+ if (previous !== void 0) {
1999
+ if (previous === fiber) return;
1971
2000
  else if (options?.onlyIfMissing === true) {
1972
2001
  fiber.interruptUnsafe(internalFiberId);
1973
2002
  return;
1974
2003
  }
1975
- self.state.fiber.interruptUnsafe(internalFiberId);
1976
- self.state.fiber = void 0;
1977
2004
  }
1978
2005
  self.state.fiber = fiber;
2006
+ previous?.interruptUnsafe(internalFiberId);
1979
2007
  fiber.addObserver((exit) => {
1980
2008
  if (self.state._tag === "Open" && fiber === self.state.fiber) self.state.fiber = void 0;
1981
2009
  if (isFailure(exit) && (options?.propagateInterruption === true ? !isInternalInterruption(exit.cause) : !hasInterruptsOnly(exit.cause))) doneUnsafe(self.deferred, exit);
@@ -2002,45 +2030,59 @@ const runImpl = (self, effect, options) => withFiber((parent) => {
2002
2030
  return succeed(fiber);
2003
2031
  });
2004
2032
  //#endregion
2005
- //#region node_modules/.pnpm/@effect+sql-sqlite-node@4.0.0_effect@4.0.0/node_modules/@effect/sql-sqlite-node/dist/SqliteClient.js
2033
+ //#region node_modules/.pnpm/@effect+sql-sqlite-node@4.0.4_effect@4.0.4/node_modules/@effect/sql-sqlite-node/dist/SqliteClient.js
2006
2034
  const ATTR_DB_SYSTEM_NAME = "db.system.name";
2007
2035
  const MAX_BUSY_TIMEOUT = 2147483647;
2036
+ const NANOS_PER_MILLI = BigInt(1e6);
2008
2037
  const TypeId = "~@effect/sql-sqlite-node/SqliteClient";
2009
2038
  const SqliteClient = Service("@effect/sql-sqlite-node/SqliteClient");
2010
2039
  const make$1 = (options) => gen(function* () {
2011
2040
  const compiler = makeCompilerSqlite(options.transformQueryNames);
2012
2041
  const transformRows = options.transformResultNames ? defaultTransforms(options.transformResultNames).array : void 0;
2013
2042
  const connection = yield* gen(function* () {
2014
- const scope$1 = yield* scope;
2015
- const db = new DatabaseSync(options.filename, {
2016
- readOnly: options.readonly ?? false,
2017
- allowExtension: true
2018
- });
2019
- yield* addFinalizer(scope$1, sync(() => db.close()));
2020
- db.enableLoadExtension(false);
2043
+ const db = yield* acquireRelease(try_({
2044
+ try: () => new DatabaseSync(options.filename, {
2045
+ readOnly: options.readonly ?? false,
2046
+ allowExtension: true
2047
+ }),
2048
+ catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to open database", "connect") })
2049
+ }), (db) => sync(() => db.close()));
2050
+ setLoadExtensionEnabled(db, false);
2021
2051
  const busyTimeout = Math.min(MAX_BUSY_TIMEOUT, Math.max(0, Math.round(toMillis(options.busyTimeout ?? seconds(5)))));
2022
- db.exec(`PRAGMA busy_timeout = ${busyTimeout}`);
2023
- if (options.disableWAL !== true) db.exec("PRAGMA journal_mode = WAL");
2052
+ const exec = (sql) => try_({
2053
+ try: () => db.exec(sql),
2054
+ catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to configure database", "connect") })
2055
+ });
2056
+ yield* exec(`PRAGMA busy_timeout = ${busyTimeout}`);
2057
+ if (options.disableWAL !== true && !options.readonly) {
2058
+ const deadline = (yield* monotonicTimeNanos) + BigInt(busyTimeout) * NANOS_PER_MILLI;
2059
+ const remainingMillis = map(monotonicTimeNanos, (now) => Math.max(0, Number((deadline - now) / NANOS_PER_MILLI)));
2060
+ yield* remainingMillis.pipe(flatMap((remaining) => exec(`PRAGMA busy_timeout = ${remaining}`)), andThen(exec("PRAGMA journal_mode = WAL")), retry({
2061
+ while: (error) => error.reason._tag === "LockTimeoutError" && map(remainingMillis, (remaining) => remaining > 0),
2062
+ schedule: spaced("10 millis")
2063
+ }));
2064
+ yield* exec(`PRAGMA busy_timeout = ${busyTimeout}`);
2065
+ }
2024
2066
  const prepare = (sql) => try_({
2025
2067
  try: () => db.prepare(sql),
2026
2068
  catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to prepare statement", "prepare") })
2027
2069
  });
2028
- const prepareCache = yield* make$4({
2070
+ const prepareCacheTTL = options.prepareCacheTTL ?? minutes(10);
2071
+ const prepareCache = yield* makeWith(prepare, {
2029
2072
  capacity: options.prepareCacheSize ?? 200,
2030
- timeToLive: options.prepareCacheTTL ?? minutes(10),
2031
- lookup: prepare
2073
+ timeToLive: (exit) => isSuccess(exit) ? prepareCacheTTL : zero
2032
2074
  });
2033
2075
  const runStatement = (statement, params, raw) => withFiber((fiber) => {
2034
2076
  const useSafeIntegers = get$1(fiber.context, SafeIntegers);
2035
2077
  return try_({
2036
2078
  try: () => {
2037
2079
  statement.setReadBigInts(useSafeIntegers);
2038
- if (statement.columns().length > 0) return statement.all(...params);
2080
+ if (!raw || statement.columns().length > 0) return statement.all(...params);
2039
2081
  const result = statement.run(...params);
2040
- return raw ? {
2082
+ return {
2041
2083
  changes: result.changes,
2042
2084
  lastInsertRowid: result.lastInsertRowid
2043
- } : [];
2085
+ };
2044
2086
  },
2045
2087
  catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
2046
2088
  });
@@ -2050,9 +2092,7 @@ const make$1 = (options) => gen(function* () {
2050
2092
  return try_({
2051
2093
  try: () => {
2052
2094
  statement.setReadBigInts(useSafeIntegers);
2053
- if (statement.columns().length > 0) return statement.all(...params);
2054
- statement.run(...params);
2055
- return [];
2095
+ return statement.all(...params);
2056
2096
  },
2057
2097
  catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
2058
2098
  });
@@ -2063,9 +2103,7 @@ const make$1 = (options) => gen(function* () {
2063
2103
  try: () => {
2064
2104
  statement.setReadBigInts(useSafeIntegers);
2065
2105
  statement.setReturnArrays(true);
2066
- if (statement.columns().length > 0) return statement.all(...params);
2067
- statement.run(...params);
2068
- return [];
2106
+ return statement.all(...params);
2069
2107
  },
2070
2108
  catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
2071
2109
  });
@@ -2112,10 +2150,10 @@ const make$1 = (options) => gen(function* () {
2112
2150
  });
2113
2151
  },
2114
2152
  loadExtension(path) {
2115
- return acquireUseRelease(sync(() => db.enableLoadExtension(true)), () => try_({
2153
+ return acquireUseRelease(sync(() => setLoadExtensionEnabled(db, true)), () => try_({
2116
2154
  try: () => db.loadExtension(path),
2117
2155
  catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to load extension", "loadExtension") })
2118
- }), () => sync(() => db.enableLoadExtension(false)));
2156
+ }), () => sync(() => setLoadExtensionEnabled(db, false)));
2119
2157
  }
2120
2158
  });
2121
2159
  });
@@ -2124,7 +2162,7 @@ const make$1 = (options) => gen(function* () {
2124
2162
  semaphore: yield* make$12(1),
2125
2163
  isTransaction: (conn) => conn.isTransaction()
2126
2164
  });
2127
- return Object.assign(yield* make$5({
2165
+ return Object.assign(yield* make$4({
2128
2166
  acquirer,
2129
2167
  compiler,
2130
2168
  transactionAcquirer,
@@ -2136,8 +2174,8 @@ const make$1 = (options) => gen(function* () {
2136
2174
  }), {
2137
2175
  [TypeId]: TypeId,
2138
2176
  config: options,
2139
- backup: (destination) => flatMap(acquirer, (_) => _.backup(destination)),
2140
- loadExtension: (path) => flatMap(acquirer, (_) => _.loadExtension(path))
2177
+ backup: (destination) => scoped(flatMap(acquirer, (_) => _.backup(destination))),
2178
+ loadExtension: (path) => scoped(flatMap(acquirer, (_) => _.loadExtension(path)))
2141
2179
  });
2142
2180
  });
2143
2181
  const layer$2 = (config) => effectContext(map(make$1(config), (client) => make$9(SqliteClient, client).pipe(add(SqlClient, client)))).pipe(provide$1(layer$5));
@@ -2151,8 +2189,11 @@ const sqliteCauseWithErrno = (cause) => {
2151
2189
  if (typeof errcode !== "number") return cause;
2152
2190
  return Object.assign(cause, { errno: errcode });
2153
2191
  };
2192
+ const setLoadExtensionEnabled = (db, enabled) => {
2193
+ if (typeof db.enableLoadExtension === "function") db.enableLoadExtension(enabled);
2194
+ };
2154
2195
  //#endregion
2155
- //#region node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/sql/Migrator.js
2196
+ //#region node_modules/.pnpm/effect@4.0.4/node_modules/effect/dist/sql/Migrator.js
2156
2197
  var __rewriteRelativeImportExtension = void 0 && (void 0).__rewriteRelativeImportExtension || function(path, preserveJsx) {
2157
2198
  if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
2158
2199
  return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
@@ -2175,11 +2216,11 @@ const make = ({ dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, tab
2175
2216
  name VARCHAR(255) NOT NULL,
2176
2217
  PRIMARY KEY (migration_id)
2177
2218
  )`,
2178
- pg: () => catch_(sql`select ${table}::regclass`, () => sql`CREATE TABLE ${sql(table)} (
2219
+ pg: () => flatMap(migrationsTableExists(sql, table), (exists) => exists ? void_$1 : asVoid(sql`CREATE TABLE ${sql(table)} (
2179
2220
  migration_id integer primary key,
2180
2221
  created_at timestamp with time zone not null default now(),
2181
2222
  name text not null
2182
- )`),
2223
+ )`).pipe(catch_((error) => flatMap(migrationsTableExists(sql, table), (exists) => exists ? void_$1 : fail(error))))),
2183
2224
  orElse: () => sql`CREATE TABLE IF NOT EXISTS ${sql(table)} (
2184
2225
  migration_id integer PRIMARY KEY NOT NULL,
2185
2226
  created_at datetime NOT NULL DEFAULT current_timestamp,
@@ -2237,7 +2278,7 @@ const make = ({ dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, tab
2237
2278
  kind: "Locked",
2238
2279
  message: "Migrations already running"
2239
2280
  }) : error));
2240
- yield* forEach(required, ([id, name, effect]) => logDebug(`Running migration`).pipe(flatMap(() => runMigration(id, name, effect)), annotateLogs("migration_id", String(id)), annotateLogs("migration_name", name), withSpan(`Migrator ${id}_${name}`)), { discard: true });
2281
+ yield* forEach$1(required, ([id, name, effect]) => logDebug(`Running migration`).pipe(flatMap(() => runMigration(id, name, effect)), annotateLogs("migration_id", String(id)), annotateLogs("migration_name", name), withSpan(`Migrator ${id}_${name}`)), { discard: true });
2241
2282
  yield* pipe(latestMigration, flatMap(match({
2242
2283
  onNone: () => logDebug(`Migrations complete`),
2243
2284
  onSome: (_) => logDebug(`Migrations complete`).pipe(annotateLogs("latest_migration_id", _.id.toString()), annotateLogs("latest_migration_name", _.name))
@@ -2249,6 +2290,10 @@ const make = ({ dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, tab
2249
2290
  if (schemaDirectory && completed.length > 0) yield* dumpSchema(`${schemaDirectory}/_schema.sql`, table).pipe(catchCause((cause) => logInfo("Could not dump schema", cause)));
2250
2291
  return completed;
2251
2292
  });
2293
+ const migrationsTableExists = (sql, table) => {
2294
+ const quotedTable = sql`${sql(table)}`.compile(true)[0];
2295
+ return map(sql`SELECT 1 AS found WHERE to_regclass(${quotedTable}) IS NOT NULL`.withoutTransform, (rows) => rows.length > 0);
2296
+ };
2252
2297
  const migrationOrder = make$10(([a], [b]) => Number$1(a, b));
2253
2298
  const isConstraintConflict = (error) => error.reason._tag === "ConstraintError" || error.reason._tag === "UniqueViolation";
2254
2299
  const fromRecord = (migrations) => pipe(Object.keys(migrations), flatMapNullishOr((_) => _.match(/^(\d+)_(.+)$/)), map$2(([key, id, name]) => [
@@ -2257,7 +2302,7 @@ const fromRecord = (migrations) => pipe(Object.keys(migrations), flatMapNullishO
2257
2302
  succeed(migrations[key])
2258
2303
  ]), sort(migrationOrder), succeed);
2259
2304
  //#endregion
2260
- //#region node_modules/.pnpm/@effect+sql-sqlite-node@4.0.0_effect@4.0.0/node_modules/@effect/sql-sqlite-node/dist/SqliteMigrator.js
2305
+ //#region node_modules/.pnpm/@effect+sql-sqlite-node@4.0.4_effect@4.0.4/node_modules/@effect/sql-sqlite-node/dist/SqliteMigrator.js
2261
2306
  const run = make({});
2262
2307
  const layer$1 = (options) => effectDiscard(run(options));
2263
2308
  //#endregion
@@ -2401,4 +2446,4 @@ const layer = (options) => effect(SemanticSearch, gen(function* () {
2401
2446
  //#endregion
2402
2447
  export { SemanticSearch, chunkEmbeddingInput, layer, makeEmbeddingResolver, maybeRemoveFile, maybeUpdateFile };
2403
2448
 
2404
- //# sourceMappingURL=SemanticSearch-cqSnq90g.mjs.map
2449
+ //# sourceMappingURL=SemanticSearch-4Jes3jCl.mjs.map