clanka 0.16.1 → 0.17.1

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 (85) hide show
  1. package/README.md +61 -0
  2. package/dist/Agent.d.ts.map +1 -1
  3. package/dist/Agent.js +5 -1
  4. package/dist/Agent.js.map +1 -1
  5. package/dist/AgentCallerConfig.test.js +5 -3
  6. package/dist/AgentCallerConfig.test.js.map +1 -1
  7. package/dist/ChunkRepo.d.ts +1 -1
  8. package/dist/ClaudeAgent.d.ts +111 -0
  9. package/dist/ClaudeAgent.d.ts.map +1 -0
  10. package/dist/ClaudeAgent.js +772 -0
  11. package/dist/ClaudeAgent.js.map +1 -0
  12. package/dist/ClaudeAgent.test.d.ts +2 -0
  13. package/dist/ClaudeAgent.test.d.ts.map +1 -0
  14. package/dist/ClaudeAgent.test.js +416 -0
  15. package/dist/ClaudeAgent.test.js.map +1 -0
  16. package/dist/Compaction.test.js +2 -1
  17. package/dist/Compaction.test.js.map +1 -1
  18. package/dist/CompactionTokens.test.js +15 -8
  19. package/dist/CompactionTokens.test.js.map +1 -1
  20. package/dist/ModelLayer.d.ts +2 -2
  21. package/dist/ModelLayer.d.ts.map +1 -1
  22. package/dist/ModelLayer.js +13 -7
  23. package/dist/ModelLayer.js.map +1 -1
  24. package/dist/ModelLayer.test.js +3 -0
  25. package/dist/ModelLayer.test.js.map +1 -1
  26. package/dist/ModelsRepo.d.ts +7 -6
  27. package/dist/ModelsRepo.d.ts.map +1 -1
  28. package/dist/ModelsRepo.js +44 -27
  29. package/dist/ModelsRepo.js.map +1 -1
  30. package/dist/ModelsRepo.test.js +47 -3
  31. package/dist/ModelsRepo.test.js.map +1 -1
  32. package/dist/bin/{Effect-4B1lzxy4.mjs → Effect-DNYYQ84C.mjs} +467 -365
  33. package/dist/bin/Effect-DNYYQ84C.mjs.map +1 -0
  34. package/dist/bin/Latch-BSlIwuxI.mjs +7 -0
  35. package/dist/bin/Latch-BSlIwuxI.mjs.map +1 -0
  36. package/dist/bin/{McpClient-DMfHHEx3.mjs → McpClient-C7ctqJWo.mjs} +4 -5
  37. package/dist/bin/{McpClient-DMfHHEx3.mjs.map → McpClient-C7ctqJWo.mjs.map} +1 -1
  38. package/dist/bin/{OutputFormatter-DRycCEdr.mjs → OutputFormatter-DXej05JW.mjs} +8 -13
  39. package/dist/bin/{OutputFormatter-DRycCEdr.mjs.map → OutputFormatter-DXej05JW.mjs.map} +1 -1
  40. package/dist/bin/{Schema-D4fxUgEU.mjs → Schema-CSQN_Zso.mjs} +754 -800
  41. package/dist/bin/Schema-CSQN_Zso.mjs.map +1 -0
  42. package/dist/bin/{SemanticSearch-BcLFv9qz.mjs → SemanticSearch-BiwCnpKX.mjs} +241 -148
  43. package/dist/bin/SemanticSearch-BiwCnpKX.mjs.map +1 -0
  44. package/dist/bin/{Stream-i37nF1ep.mjs → Stream-Dwvj9X5X.mjs} +244 -120
  45. package/dist/bin/Stream-Dwvj9X5X.mjs.map +1 -0
  46. package/dist/bin/cli.mjs +5122 -15959
  47. package/dist/bin/cli.mjs.map +1 -1
  48. package/dist/bin/helpers-CljL9OKa.mjs +7157 -0
  49. package/dist/bin/helpers-CljL9OKa.mjs.map +1 -0
  50. package/dist/bin/index.min-ClUfQ5ji.mjs +3782 -0
  51. package/dist/bin/index.min-ClUfQ5ji.mjs.map +1 -0
  52. package/dist/bin/{rolldown-runtime-zY4HT0JA.mjs → rolldown-runtime-5zChB7MF.mjs} +15 -3
  53. package/dist/bin/server-HlLriZxF.mjs +319 -0
  54. package/dist/bin/server-HlLriZxF.mjs.map +1 -0
  55. package/dist/bin/{turndown.cjs-LntFxFyd.mjs → turndown.cjs-C2WBxeA-.mjs} +56 -110
  56. package/dist/bin/{turndown.cjs-LntFxFyd.mjs.map → turndown.cjs-C2WBxeA-.mjs.map} +1 -1
  57. package/dist/bin/types-LcwjLVkt.mjs +5260 -0
  58. package/dist/bin/types-LcwjLVkt.mjs.map +1 -0
  59. package/dist/bin/upgrade-BSNjCnra.mjs +342 -0
  60. package/dist/bin/upgrade-BSNjCnra.mjs.map +1 -0
  61. package/dist/cli.js +4 -0
  62. package/dist/cli.js.map +1 -1
  63. package/dist/index.d.ts +4 -0
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +4 -0
  66. package/dist/index.js.map +1 -1
  67. package/package.json +15 -13
  68. package/src/Agent.ts +7 -1
  69. package/src/AgentCallerConfig.test.ts +5 -3
  70. package/src/ClaudeAgent.test.ts +526 -0
  71. package/src/ClaudeAgent.ts +1113 -0
  72. package/src/Compaction.test.ts +2 -1
  73. package/src/CompactionTokens.test.ts +15 -11
  74. package/src/ModelLayer.test.ts +4 -0
  75. package/src/ModelLayer.ts +21 -15
  76. package/src/ModelsRepo.test.ts +69 -3
  77. package/src/ModelsRepo.ts +24 -8
  78. package/src/cli.ts +4 -0
  79. package/src/index.ts +5 -0
  80. package/dist/bin/Effect-4B1lzxy4.mjs.map +0 -1
  81. package/dist/bin/Schema-D4fxUgEU.mjs.map +0 -1
  82. package/dist/bin/SemanticSearch-BcLFv9qz.mjs.map +0 -1
  83. package/dist/bin/Stream-i37nF1ep.mjs.map +0 -1
  84. package/dist/bin/index.min-Bkz7vIWv.mjs +0 -3300
  85. package/dist/bin/index.min-Bkz7vIWv.mjs.map +0 -1
@@ -1,25 +1,33 @@
1
- import { $n as combine, $t as tryPromise, At as request$1, B as fn, C as catchTags, Cc as pipe, Cn as make$8, Ct as orElseSucceed, D as contextWith, Da as map$2, Do as fromNullishOr, Dt as provideService, E as context, Ec as pipeArguments, Ei as exitHasInterrupts, En as size, Er as effectDiscard, Et as provideContext, Fi as fiberJoin, Fo as isSome, Fs as symbol, Gs as hasProperty, Ho as some, I as filterOrFail, Ji as onExitUnsafe, Jn as NoSuchElementError, Jt as tap, Ko as Number$1, Kr as provide, Kt as suspend, L as flatMap, Lo as map$1, Lt as scope, Mt as retry, N as fail, Nn as spaced, No as isNone, Nr as provide$1, Ns as byReferenceUnsafe, Nt as runFork, O as delay, P as failCause$1, Pr as provideMerge, Ps as equals, Pt as runForkWith, Q as interrupt, Qa as isZero, Qo as make$10, Qr as doneUnsafe, Qs as isNotNull, Ri as forkUnsafe, Ro as match, Rr as Scope, Rs as hash, Rt as scoped, S as catchTag, Si as contextWith$1, Sn as isEmpty, So as filter, St as orDie, Ti as endSpan, Tn as set, To as flatten, Tr as effectContext, U as forEach$1, Ut as succeed, V as fnUntraced, Vr as close, Vt as serviceOption, W as forever, Wi as makeSpanUnsafe, Wr as make$7, Ws as symbol$1, X as gen, Xi as succeed$1, Ya as infinity, Yr as TracerTimingEnabled, Yt as tapCause, Z as ignore, Za as isFinite, Zr as done, _a as flatMapNullishOr, _n as Class$1, _o as make$9, _s as assignProperty, _t as onError, a as andThen, ao as toMillis, as as PipeInspectableProto, b as catchNoSuchElement, ba as isArrayNonEmpty, bc as identity, bn as forEach, br as reasonAnnotations, c as as, ca as toPredicate, ci as failCause, co as Reference, cr as hasInterruptsOnly, dn as withLogSpan, ei as into, en as try_, eo as millis, et as isEffect, fi as isFailure, fo as get$1, fr as isFailReason, g as catchDefect, gi as ClockRef, go as getUnsafe, hc as constUndefined, hi as void_$3, hr as makeDieReason, hs as withFiber$1, i as all, ia as ParentSpan, ii as makeUnsafe$2, io as seconds, it as logInfo, ja as sort, ji as fiberInterrupt, k as die, lo as Service, m as catchCause, mi as succeed$2, mo as getOrUndefined, mt as matchCauseEffect, n as acquireUseRelease, na as void_$2, ns as Prototype, o as annotateCurrentSpan, oa as compose, on as useSpan, or as fromReasons, ot as makeSpanScoped, pa as empty, pi as isSuccess, pn as withSpan, po as getOption, pt as matchCauseEager, q as forkScoped, qa as fromInputUnsafe, qt as sync, rn as uninterruptibleMask, rr as filterInterruptors, s as annotateLogs, sa as has, si as fail$1, sn as void_$1, so as zero, st as map, t as acquireRelease, ta as updateContext, to as minutes, tt as logDebug, u as asVoid, un as withFiber, uo as add, ut as mapError, va as fromIterable, vc as dual, vt as onExit, w as catch_, wn as remove, wr as effect, xn as get$2, y as catchIf, yc as flow, yn as empty$1, yo as merge, yt as onExitPrimitive, zo as none, zr as addFinalizer } from "./Effect-4B1lzxy4.mjs";
2
- import { E as fromQueue, It as interruptAs, Lt as join$1, Rt as runIn, U as runCollect, V as provideService$1, W as runDrain, _t as make$11, b as fromArrayEffect, c as die$1, g as flatMap$1, gt as failCauseUnsafe, it as unwrap, lt as make$12, nt as tap$1, ut as makeUnsafe$3, xt as offerUnsafe, y as fromArray } from "./Stream-i37nF1ep.mjs";
3
- import { Cn as toType, Ct as instanceOf, D as Natural, Dn as evolve, F as Option, H as String$1, I as OptionFromNullOr, J as TaggedError, Kr as now, M as NullOr, N as Number$2, Qr as Clock, W as Struct$2, Wr as formatIsoDate, a as BooleanFromBit, an as isSchema, d as DateTimeUtcFromMillis, dr as transform$1, ei as monotonicTimeNanos, f as DateTimeUtcFromString, gn as optionalKey, gt as decodeUnknownEffect, hn as optional, hr as map$3, ht as decodeTo, i as Boolean, ii as TaggedError$1, l as DateTimeUtc, mr as dateTimeUtcFromInput, n as ArraySchema, ot as Union$2, p as Defect, pn as mutable, pr as transformOptional, qr as removeTime, s as Class$2, u as DateTimeUtcFromDate, ut as brand, vr as transform, wn as withConstructorDefault, yt as encodeEffect } from "./Schema-D4fxUgEU.mjs";
4
- import { _ as Path, a as makeGrouped, d as maybeRemoveFile, f as maybeUpdateFile, g as Console, h as ChildProcessSpawner, i as batchN, m as make$13, n as EmbeddingModel, o as setDelay, p as map$4, r as EmbeddingRequest, s as withSpan$1, t as Dimensions, u as SemanticSearch, v as FileSystem } from "./cli.mjs";
1
+ import { $ as ignoreCause, $o as some, Ai as exitHasInterrupts, An as size, Ao as omit, B as fn, C as catchTags, Cn as empty$1, Co as getOption, Cr as reasonAnnotations, D as delay, Dn as make$8, Do as make$9, Dr as effect, Ds as withFiber$1, E as contextWith, Ei as contextWith$1, En as isEmpty, Eo as getUnsafe, Fa as map$1, Fi as fiberInterrupt, Ft as runFork, Gs as byReferenceUnsafe, Hi as forkUnsafe, Hr as addFinalizer, I as filterOrFail, Ic as pipe, Io as flatten, Ir as provide$1, It as runForkWith, J as forkScoped, Ji as makeSpanUnsafe, Jo as map$2, Ko as isSome, Ks as equals, Kt as succeed, L as flatMap, Ln as spaced, Lr as provideMerge, M as fail, Mc as flow, Mt as request$1, N as failCause$1, Nc as identity, No as filter, O as die, Oa as isArrayNonEmpty, Oc as constUndefined, On as remove, Or as effectContext, Ot as provideContext, Pt as retry, Q as ignore, Qi as onExitUnsafe, Qr as TracerTimingEnabled, Qt as tapCause, Ri as fiberJoin, Ro as fromNullishOr, S as catchTag, So as get$1, T as context, Ta as fromIterable, Tn as get$2, Tt as orElseSucceed, U as forEach, V as fnUntraced, Vr as Scope, Vt as scoped, W as forever, Wo as isNone, Wr as close, Wt as serviceOption, Xo as none, Xs as hash, Xt as sync, Yo as match, Yr as provide, Yt as suspend, Z as gen, Zn as NoSuchElementError, Zt as tap, _i as isSuccess, _n as withSpan, _o as zero, _s as PipeInspectableProto, a as andThen, ao as infinity, b as catchNoSuchElement, bi as ClockRef, bo as add, bt as onExit, c as as, ca as void_$2, co as isZero, cr as fromReasons, ct as makeSpanScoped, dc as isNotNull, di as fail$1, dn as void_$1, do as minutes, ei as doneUnsafe, et as interrupt, fa as compose, fi as failCause, ft as mapError, g as catchDefect, gi as isFailure, gt as matchCauseEffect, hn as withLogSpan, ho as toMillis, hr as isFailReason, ht as matchCauseEager, i as all, ic as hasProperty, in as try_, jc as dual, ki as endSpan, kn as set, ko as merge, kr as effectDiscard, ks as assignProperty, kt as provideService, ls as make$10, lt as map, m as catchCause, ma as toPredicate, mn as withFiber, mo as seconds, ms as Prototype, n as acquireUseRelease, na as succeed$1, nr as combine, nt as isEffect, o as annotateCurrentSpan, or as filterInterruptors, ot as logInfo, pa as has, qr as make$7, qs as symbol, rc as symbol$1, ri as into, rn as tryPromise, ro as fromInputUnsafe, rs as Number$1, rt as logDebug, s as annotateLogs, sa as updateContext, si as makeUnsafe$2, sn as uninterruptibleMask, so as isFinite, t as acquireRelease, u as asVoid, ua as ParentSpan, un as useSpan, uo as millis, ur as hasInterruptsOnly, vi as succeed$2, vo as Reference, vr as makeDieReason, w as catch_, wa as flatMapNullishOr, wn as forEach$1, wo as getOrUndefined, wt as orDie, xn as Class$1, xt as onExitPrimitive, y as catchIf, ya as empty, yi as void_$3, yo as Service, yt as onError, za as sort, zc as pipeArguments } from "./Effect-DNYYQ84C.mjs";
2
+ import { B as String$1, Cn as evolve, E as Natural, Gr as formatIsoDate, H as Struct$2, Jr as removeTime, K as TaggedError, M as Number$2, N as Option, P as OptionFromNullOr, a as BooleanFromBit, bn as withConstructorDefault, d as DateTimeUtcFromMillis, dn as optional, dr as transformOptional, dt as decodeTo, f as DateTimeUtcFromString, fn as optionalKey, fr as dateTimeUtcFromInput, ft as decodeUnknownEffect, gr as transform, ht as encodeEffect, i as Boolean, j as NullOr, l as DateTimeUtc, lr as transform$1, n as ArraySchema, ot as brand, p as Defect, pr as map$3, qr as now, ri as monotonicTimeNanos, rt as Union$2, s as Class$2, si as TaggedError$1, ti as Clock, tn as isSchema, u as DateTimeUtcFromDate, un as mutable, yn as toType, yt as instanceOf } from "./Schema-CSQN_Zso.mjs";
3
+ import { C as ChildProcessSpawner, E as FileSystem, S as make$11, T as Path, a as makeGrouped, d as maybeRemoveFile, f as maybeUpdateFile, i as batchN, n as EmbeddingModel, o as setDelay, p as map$4, r as EmbeddingRequest, s as withSpan$1, t as Dimensions, u as SemanticSearch, w as Console } from "./cli.mjs";
4
+ import { A as fromQueue, C as fromArray, Ct as failCauseUnsafe, G as provideService$1, Ht as interruptAllAs, J as runDrain, Ot as offerUnsafe, Ut as join$1, Wt as runIn, _t as makeUnsafe$3, dt as unwrap, gt as make$13, q as runCollect, st as tap$1, u as die$1, w as fromArrayEffect, wt as make$12, y as flatMap$1 } from "./Stream-Dwvj9X5X.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.5/node_modules/effect/dist/reactivity/Reactivity.js
11
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/internal/sql.js
12
+ const CurrentTransactionService = Reference("effect/sql/CurrentTransactionService", { defaultValue: () => void 0 });
13
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/reactivity/Reactivity.js
12
14
  const TypeId$6 = "~effect/reactivity/Reactivity";
13
15
  const Reactivity = Service("effect/reactivity/Reactivity");
14
16
  const make$6 = sync(() => {
15
17
  const handlers = new Map();
16
- const invalidateUnsafe = (keys) => {
17
- keysToHashes(keys, (hash) => {
18
- const set = handlers.get(hash);
19
- if (set === void 0) return;
20
- set.forEach((run) => run());
18
+ const runHandlers = (hashes) => {
19
+ const ran = new Set();
20
+ for (const hash of hashes) handlers.get(hash)?.forEach((run) => {
21
+ if (ran.has(run)) return;
22
+ ran.add(run);
23
+ run();
21
24
  });
22
25
  };
26
+ const invalidateUnsafe = (keys) => {
27
+ const hashes = new Set();
28
+ keysToHashes(keys, (hash) => hashes.add(hash));
29
+ runHandlers(hashes);
30
+ };
23
31
  const invalidate = (keys) => contextWith((services) => {
24
32
  const pending = getOrUndefined(services, PendingInvalidation);
25
33
  if (pending) keysToHashes(keys, (hash) => {
@@ -52,19 +60,27 @@ const make$6 = sync(() => {
52
60
  const query = (keys, effect) => gen(function* () {
53
61
  const services = yield* context();
54
62
  const scope = get$1(services, Scope);
55
- const results = yield* make$11();
63
+ const results = yield* make$12();
56
64
  const runFork = flow(runForkWith(services), runIn(scope));
57
65
  let running = false;
58
66
  let pending = false;
67
+ let stopped = false;
59
68
  const handleExit = (exit) => {
60
- if (exit._tag === "Failure") failCauseUnsafe(results, exit.cause);
61
- else offerUnsafe(results, exit.value);
69
+ if (exit._tag === "Failure") {
70
+ stopped = true;
71
+ pending = false;
72
+ running = false;
73
+ cancel();
74
+ failCauseUnsafe(results, exit.cause);
75
+ return;
76
+ } else offerUnsafe(results, exit.value);
62
77
  if (pending) {
63
78
  pending = false;
64
79
  runFork(effect).addObserver(handleExit);
65
80
  } else running = false;
66
81
  };
67
82
  function run() {
83
+ if (stopped) return;
68
84
  if (running) {
69
85
  pending = true;
70
86
  return;
@@ -80,13 +96,7 @@ const make$6 = sync(() => {
80
96
  const stream = (tables, effect) => query(tables, effect).pipe(map(fromQueue), unwrap);
81
97
  const withBatch = (effect) => suspend(() => {
82
98
  const pending = new Set();
83
- return effect.pipe(provideService(PendingInvalidation, pending), onExit((_) => sync(() => {
84
- pending.forEach((hash) => {
85
- const set = handlers.get(hash);
86
- if (set === void 0) return;
87
- set.forEach((run) => run());
88
- });
89
- })));
99
+ return effect.pipe(provideService(PendingInvalidation, pending), onExit((_) => sync(() => runHandlers(pending))));
90
100
  });
91
101
  return Reactivity.of({
92
102
  [TypeId$6]: TypeId$6,
@@ -121,8 +131,7 @@ const keysToHashes = (keys, f) => {
121
131
  for (let i = 0; i < ids.length; i++) f(`${key}:${stringOrHash(ids[i])}`);
122
132
  }
123
133
  };
124
- //#endregion
125
- //#region node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/sql/SqlError.js
134
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/SqlError.js
126
135
  const TypeId$5 = "~effect/sql/SqlError";
127
136
  const ReasonTypeId = "~effect/sql/SqlError/Reason";
128
137
  const ReasonFields = {
@@ -295,9 +304,9 @@ var ResultLengthMismatch = class extends TaggedError("effect/sql/ResultLengthMis
295
304
  return `Expected ${this.expected} results but got ${this.actual}`;
296
305
  }
297
306
  };
298
- //#endregion
299
- //#region node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/sql/Statement.js
300
- const FragmentTypeId = "~effect/sql/Statement/Fragment";
307
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/Statement.js
308
+ const FragmentTypeId = Symbol.for("~effect/sql/Statement/Fragment");
309
+ const SegmentTypeId = Symbol.for("~effect/sql/Statement/Segment");
301
310
  const fragment = (segments) => ({
302
311
  [FragmentTypeId]: FragmentTypeId,
303
312
  segments
@@ -306,23 +315,28 @@ const CurrentTransformer = Reference("effect/sql/CurrentTransformer", { defaultV
306
315
  const SpanPropagationEnabled = Reference("effect/sql/SpanPropagationEnabled", { defaultValue: () => false });
307
316
  const isFragment = (u) => hasProperty(u, FragmentTypeId);
308
317
  const literal = (value, params) => ({
318
+ [SegmentTypeId]: SegmentTypeId,
309
319
  _tag: "Literal",
310
320
  value,
311
321
  params
312
322
  });
313
323
  const identifier = (value) => ({
324
+ [SegmentTypeId]: SegmentTypeId,
314
325
  _tag: "Identifier",
315
326
  value
316
327
  });
317
328
  const parameter = (value) => ({
329
+ [SegmentTypeId]: SegmentTypeId,
318
330
  _tag: "Parameter",
319
331
  value
320
332
  });
321
333
  const arrayHelper = (value) => ({
334
+ [SegmentTypeId]: SegmentTypeId,
322
335
  _tag: "ArrayHelper",
323
336
  value
324
337
  });
325
338
  const RecordInsertHelperProto = {
339
+ [SegmentTypeId]: SegmentTypeId,
326
340
  _tag: "RecordInsertHelper",
327
341
  returning(sql) {
328
342
  const self = Object.create(Object.getPrototypeOf(this));
@@ -470,6 +484,13 @@ const CompilerProto = {
470
484
  binds.push(segment.value);
471
485
  break;
472
486
  case "ArrayHelper":
487
+ if (segment.value.length === 0) {
488
+ const inKeyword = emptyInKeyword.exec(sql);
489
+ if (inKeyword === null || isInLineComment(sql, inKeyword.index)) sql += "()";
490
+ else if (this.dialect === "pg") sql = sql.slice(0, inKeyword.index) + (inKeyword[1] ? "<> ALL('{}')" : "= ANY('{}')");
491
+ else sql += "(SELECT NULL WHERE 1=0)";
492
+ break;
493
+ }
473
494
  sql += `(${placeholders(segment.value)})`;
474
495
  binds.push.apply(binds, segment.value);
475
496
  break;
@@ -559,7 +580,7 @@ const CompilerProto = {
559
580
  }
560
581
  placeholders += ")";
561
582
  }
562
- const [s, b] = opts.onRecordUpdate(placeholders, segment.alias, generateColumns(keys, opts.onIdentifier, withoutTransform), values, typeof segment.returningIdentifier === "string" ? [segment.returningIdentifier, []] : segment.returningIdentifier ? this.compile(segment.returningIdentifier, withoutTransform, placeholder) : void 0);
583
+ const [s, b] = opts.onRecordUpdate(placeholders, opts.onIdentifier(segment.alias, true), generateColumns(keys, opts.onIdentifier, withoutTransform), values, typeof segment.returningIdentifier === "string" ? [segment.returningIdentifier, []] : segment.returningIdentifier ? this.compile(segment.returningIdentifier, withoutTransform, placeholder) : void 0);
563
584
  sql += s;
564
585
  binds.push.apply(binds, b);
565
586
  break;
@@ -609,7 +630,7 @@ function defaultEscape(c) {
609
630
  const defaultTransforms = (transformer, nested = true) => {
610
631
  const transformValue = (value) => {
611
632
  if (Array.isArray(value)) {
612
- if (value.length === 0 || value[0].constructor !== Object) return value;
633
+ if (value.length === 0 || value[0]?.constructor !== Object) return value;
613
634
  return array(value);
614
635
  } else if (value?.constructor === Object) return transformObject(value);
615
636
  return value;
@@ -624,6 +645,7 @@ const defaultTransforms = (transformer, nested = true) => {
624
645
  for (let i = 0, len = rows.length; i < len; i++) {
625
646
  const row = rows[i];
626
647
  if (Array.isArray(row)) newRows[i] = transformArrayNested(row);
648
+ else if (row === null || typeof row !== "object") newRows[i] = row;
627
649
  else {
628
650
  const obj = {};
629
651
  for (const [key, value] of Object.entries(row)) assignProperty(obj, transformer(key), transformValue(value));
@@ -637,6 +659,7 @@ const defaultTransforms = (transformer, nested = true) => {
637
659
  for (let i = 0, len = rows.length; i < len; i++) {
638
660
  const row = rows[i];
639
661
  if (Array.isArray(row)) newRows[i] = transformArray(row);
662
+ else if (row === null || typeof row !== "object") newRows[i] = row;
640
663
  else {
641
664
  const obj = {};
642
665
  for (const [key, value] of Object.entries(row)) assignProperty(obj, transformer(key), value);
@@ -668,6 +691,7 @@ const spanName = (spanAttributes) => {
668
691
  return isNonEmptyString(system) ? system : "sql.execute";
669
692
  };
670
693
  const ATTR_DB_QUERY_TEXT = "db.query.text";
694
+ const ATTR_DB_CLIENT_CONNECTION_WAIT_TIME = "db.client.connection.wait_time_ms";
671
695
  const ATTR_SQL_METHOD = "effect.sql.method";
672
696
  const spanAttribute = (spanAttributes, key) => {
673
697
  for (let i = spanAttributes.length - 1; i >= 0; i--) if (spanAttributes[i][0] === key) return spanAttributes[i][1];
@@ -694,8 +718,14 @@ const StatementProto = {
694
718
  for (const [key, value] of this.spanAttributes) span.attribute(key, value);
695
719
  span.attribute(ATTR_SQL_METHOD, operation);
696
720
  span.attribute(ATTR_DB_QUERY_TEXT, sql);
697
- const execute = this.borrower === void 0 ? scoped(flatMap(this.acquirer, (_) => f(_, sql, params))) : this.borrower((connection) => f(connection, sql, params));
698
- return fiber.cache.tracerEnabled && fiber.getRef(SpanPropagationEnabled) ? provideService(execute, ParentSpan, span) : execute;
721
+ const propagate = fiber.cache.tracerEnabled && fiber.getRef(SpanPropagationEnabled);
722
+ const clock = propagate ? waitClock(fiber) : void 0;
723
+ const run = clock === void 0 ? (connection) => f(connection, sql, params) : (connection) => suspend(() => {
724
+ recordConnectionWait(span, clock);
725
+ return f(connection, sql, params);
726
+ });
727
+ const execute = this.borrower === void 0 ? scoped(flatMap(this.acquirer, run)) : this.borrower(run);
728
+ return propagate ? provideService(execute, ParentSpan, span) : execute;
699
729
  });
700
730
  },
701
731
  get withoutTransform() {
@@ -711,8 +741,13 @@ const StatementProto = {
711
741
  for (const [key, value] of self.spanAttributes) span.attribute(key, value);
712
742
  span.attribute(ATTR_SQL_METHOD, "executeStream");
713
743
  span.attribute(ATTR_DB_QUERY_TEXT, sql);
714
- const acquire = map(self.acquirer, (_) => _.executeStream(sql, params, self.transformRows));
715
- return fiber.cache.tracerEnabled && fiber.getRef(SpanPropagationEnabled) ? succeed(provideService$1(unwrap(acquire), ParentSpan, span)) : acquire;
744
+ const propagate = fiber.cache.tracerEnabled && fiber.getRef(SpanPropagationEnabled);
745
+ const clock = propagate ? waitClock(fiber) : void 0;
746
+ const acquire = map(self.acquirer, (connection) => {
747
+ if (clock !== void 0) recordConnectionWait(span, clock);
748
+ return connection.executeStream(sql, params, self.transformRows);
749
+ });
750
+ return propagate ? succeed(provideService$1(unwrap(acquire), ParentSpan, span)) : acquire;
716
751
  })));
717
752
  },
718
753
  get values() {
@@ -747,25 +782,14 @@ const StatementProto = {
747
782
  };
748
783
  }
749
784
  };
785
+ const waitClock = (fiber) => fiber.getRef(TracerTimingEnabled) ? fiber.getRef(Clock) : void 0;
786
+ const recordConnectionWait = (span, clock) => span.attribute(ATTR_DB_CLIENT_CONNECTION_WAIT_TIME, Number(clock.currentTimeNanosUnsafe() - span.status.startTime) / 1e6);
750
787
  const withStatement = (self, span, f) => withFiber((fiber) => {
751
788
  const transform = fiber.getRef(CurrentTransformer);
752
789
  if (transform === void 0) return f(self, fiber);
753
790
  return flatMap(transform(self, make$5(self.acquirer, self.compiler, self.spanAttributes, self.transformRows, self.borrower), fiber, span), (statement) => f(statement, fiber));
754
791
  });
755
- const isSegment = (u) => {
756
- if (!hasProperty(u, "_tag")) return false;
757
- switch (u._tag) {
758
- case "Literal":
759
- case "Parameter":
760
- case "ArrayHelper":
761
- case "RecordInsertHelper":
762
- case "RecordUpdateHelper":
763
- case "RecordUpdateHelperSingle":
764
- case "Identifier":
765
- case "Custom": return true;
766
- default: return false;
767
- }
768
- };
792
+ const isSegment = (u) => hasProperty(u, SegmentTypeId);
769
793
  function convertLiteralOrFragment(clause) {
770
794
  if (typeof clause === "string") return [literal(clause)];
771
795
  return clause.segments;
@@ -804,8 +828,9 @@ function in_() {
804
828
  ]);
805
829
  }
806
830
  const neverFragment = fragment([literal("1=0")]);
807
- //#endregion
808
- //#region node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/sql/SqlClient.js
831
+ const emptyInKeyword = /\b(NOT\s+)?IN\s*$/i;
832
+ const isInLineComment = (sql, index) => sql.lastIndexOf("--", index) > sql.lastIndexOf("\n", index);
833
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/SqlClient.js
809
834
  const TypeId$4 = "~effect/sql/SqlClient";
810
835
  const SqlClient = Service("effect/sql/SqlClient");
811
836
  let clientIdCounter = 0;
@@ -823,19 +848,23 @@ const make$4 = fnUntraced(function* (options) {
823
848
  const rollback = options.rollback ?? "ROLLBACK";
824
849
  const rollbackSavepoint = options.rollbackSavepoint ?? ((name) => `ROLLBACK TO SAVEPOINT ${name}`);
825
850
  const transactionAcquirer = options.transactionAcquirer ?? options.acquirer;
826
- const control = options.prepareTransactionControls === true ? (conn, sql) => conn.execute(sql, [], void 0) : (conn, sql) => conn.executeUnprepared(sql, [], void 0);
851
+ const unprepared = (conn, sql) => conn.executeUnprepared(sql, [], void 0);
852
+ const control = options.prepareTransactionControls === true ? (conn, sql) => conn.execute(sql, [], void 0) : unprepared;
853
+ const isTransaction = options.isTransaction;
854
+ const cleanup = isTransaction ? (conn, sql) => isTransaction(conn) ? unprepared(conn, sql) : void_$1 : unprepared;
827
855
  const withTransaction = makeWithTransaction({
828
856
  transactionService,
829
857
  spanAttributes: options.spanAttributes,
830
- acquireConnection: flatMap(make$7(), (scope) => provide(transactionAcquirer, scope).pipe(onError((cause) => close(scope, failCause(cause))), map((conn) => [scope, conn]))),
831
- begin: (conn) => control(conn, beginTransaction),
858
+ acquireConnection: (restore) => restore(transactionAcquirer),
859
+ begin: (conn, statement) => statement === void 0 ? control(conn, beginTransaction) : unprepared(conn, statement),
832
860
  savepoint: (conn, id) => control(conn, savepoint(`effect_sql_${id}`)),
833
- releaseSavepoint: releaseSavepoint ? (conn, id) => control(conn, releaseSavepoint(`effect_sql_${id}`)) : void 0,
861
+ releaseSavepoint: releaseSavepoint ? (conn, id) => cleanup(conn, releaseSavepoint(`effect_sql_${id}`)) : void 0,
834
862
  commit: typeof commit === "string" ? (conn) => control(conn, commit) : commit,
835
863
  onCommitFailure: options.onCommitFailure,
836
- rollback: (conn) => control(conn, rollback),
837
- rollbackSavepoint: (conn, id) => control(conn, rollbackSavepoint(`effect_sql_${id}`))
864
+ rollback: (conn) => cleanup(conn, rollback),
865
+ rollbackSavepoint: (conn, id) => cleanup(conn, rollbackSavepoint(`effect_sql_${id}`))
838
866
  });
867
+ const afterCommit = makeAfterCommit(transactionService);
839
868
  const reactivity = yield* Reactivity;
840
869
  const borrower = options.borrower === void 0 ? void 0 : (f) => flatMap(serviceOption(transactionService), match({
841
870
  onNone: () => options.borrower(f),
@@ -846,7 +875,9 @@ const make$4 = fnUntraced(function* (options) {
846
875
  safe: void 0,
847
876
  withTransaction,
848
877
  transactionService,
878
+ afterCommit,
849
879
  reserve: transactionAcquirer,
880
+ driver: options.driver,
850
881
  withoutTransforms() {
851
882
  if (options.transformRows === void 0) return this;
852
883
  const statement = make$5(getConnection, options.compiler.withoutTransform, options.spanAttributes, void 0, borrower);
@@ -886,12 +917,13 @@ const makeSqliteAcquirers = (options) => {
886
917
  }
887
918
  });
888
919
  });
889
- const lease = uninterruptibleMask((restore) => flatMap(scope, (scope) => restore(semaphore.take(1)).pipe(andThen(addFinalizer(scope, semaphore.release(1))), andThen(available))));
920
+ const lease = uninterruptibleMask((restore) => andThen(restore(semaphore.takeScoped(1)), available));
890
921
  return {
891
922
  acquirer: lease,
892
923
  borrower: (f) => semaphore.withPermit(flatMap(available, f)),
893
924
  transactionAcquirer: lease,
894
- onCommitFailure: (conn) => tapCause(rollback(conn), (cause) => sync(() => poison(cause)))
925
+ onCommitFailure: (conn) => tapCause(rollback(conn), (cause) => sync(() => poison(cause))),
926
+ isTransaction: isTransaction && ((conn) => isTransaction(conn))
895
927
  };
896
928
  };
897
929
  const isNoTransactionError = (error) => {
@@ -900,43 +932,88 @@ const isNoTransactionError = (error) => {
900
932
  return /no transaction is active/i.test(message);
901
933
  };
902
934
  const failuresToDefects = (cause) => fromReasons(cause.reasons.map((reason) => isFailReason(reason) ? makeDieReason(reason.error).annotate(reasonAnnotations(reason)) : reason));
935
+ const afterCommitBuffers = new WeakMap();
936
+ const runAfterCommit = (effect) => ignoreCause(effect, {
937
+ log: "Unhandled",
938
+ message: "Unhandled error in SqlClient.afterCommit callback"
939
+ });
940
+ const makeAfterCommit = (transactionService) => (effect) => withFiber((fiber) => {
941
+ const transaction = getOrUndefined(fiber.context, transactionService);
942
+ const buffer = transaction && afterCommitBuffers.get(transaction);
943
+ if (buffer === void 0) return runAfterCommit(effect);
944
+ for (let current = buffer; current !== void 0; current = current.parent) if (!current.open) return die(new Error("SqlClient.afterCommit: the transaction has already ended"));
945
+ buffer.callbacks.push(provideContext(effect, omit(transactionService)(fiber.context)));
946
+ return void_$1;
947
+ });
903
948
  const makeWithTransaction = (options) => {
904
949
  const transactionSemaphore = Service(`effect/sql/SqlClient/TransactionSemaphore/${transactionSemaphoreIdCounter++}`);
950
+ const afterCommit = makeAfterCommit(options.transactionService);
951
+ const deferInvalidations = (reactivity) => {
952
+ const invalidate = (keys) => afterCommit(sync(() => reactivity.invalidateUnsafe(keys)));
953
+ return {
954
+ ...reactivity,
955
+ invalidate,
956
+ mutation: (keys, effect) => tap(effect, invalidate(keys))
957
+ };
958
+ };
905
959
  return (effect) => uninterruptibleMask((restore) => useSpan("sql.transaction", { kind: "internal" }, (span) => withFiber((fiber) => {
906
960
  for (const [key, value] of options.spanAttributes) span.attribute(key, value);
907
961
  const services = fiber.context;
962
+ const reactivity = getOrUndefined(services, Reactivity);
908
963
  const clock = fiber.getRef(Clock);
909
964
  const connOption = getOption(services, options.transactionService);
910
- const conn = connOption._tag === "Some" ? succeed([void 0, connOption.value[0]]) : options.acquireConnection;
965
+ const conn = connOption._tag === "Some" ? succeed([void 0, connOption.value[0]]) : flatMap(make$7(), (scope) => provide(options.acquireConnection(restore), scope).pipe(map((conn) => [scope, conn]), onError((cause) => close(scope, failCause(cause)))));
911
966
  const id = connOption._tag === "Some" ? connOption.value[1] + 1 : 0;
912
- const transaction = flatMap(conn, ([scope, conn]) => (id === 0 ? options.begin(conn) : options.savepoint(conn, id)).pipe(flatMap(() => onExitPrimitive(provideContext(restore(effect), services.pipe(add(options.transactionService, [conn, id]), add(transactionSemaphore, makeUnsafe$3(1)), add(ParentSpan, span))), (exit) => {
913
- let effect;
914
- if (isSuccess(exit)) {
915
- if (id === 0) {
916
- span.event("effect.sql.transaction.commit", clock.currentTimeNanosUnsafe());
917
- const onCommitFailure = options.onCommitFailure;
918
- effect = onCommitFailure ? catchCause(options.commit(conn), (commitCause) => matchCauseEffect(onCommitFailure(conn), {
919
- onFailure: (cleanupCause) => failCause$1(failuresToDefects(combine(commitCause, cleanupCause))),
920
- onSuccess: () => failCause$1(commitCause)
921
- })) : options.commit(conn);
967
+ const buffer = {
968
+ callbacks: [],
969
+ parent: connOption._tag === "Some" ? afterCommitBuffers.get(connOption.value) : void 0,
970
+ open: true
971
+ };
972
+ let committed = false;
973
+ const transaction = flatMap(conn, ([scope, conn]) => (id === 0 ? options.begin(conn, fiber.getRef(BeginTransaction)) : options.savepoint(conn, id)).pipe(flatMap(() => {
974
+ const level = [conn, id];
975
+ afterCommitBuffers.set(level, buffer);
976
+ return onExitPrimitive(provideContext(restore(effect), services.pipe(add(options.transactionService, level), add(CurrentTransactionService, options.transactionService), reactivity ? add(Reactivity, deferInvalidations(reactivity)) : identity, add(transactionSemaphore, makeUnsafe$3(1)), add(ParentSpan, span))), (exit) => {
977
+ let effect;
978
+ if (isSuccess(exit)) {
979
+ if (id === 0) {
980
+ span.event("effect.sql.transaction.commit", clock.currentTimeNanosUnsafe());
981
+ const onCommitFailure = options.onCommitFailure;
982
+ effect = onCommitFailure ? catchCause(options.commit(conn), (commitCause) => matchCauseEffect(onCommitFailure(conn), {
983
+ onFailure: (cleanupCause) => failCause$1(failuresToDefects(combine(commitCause, cleanupCause))),
984
+ onSuccess: () => failCause$1(commitCause)
985
+ })) : options.commit(conn);
986
+ } else {
987
+ span.event("effect.sql.transaction.savepoint", clock.currentTimeNanosUnsafe());
988
+ effect = void_$1;
989
+ }
922
990
  } else {
923
- span.event("effect.sql.transaction.savepoint", clock.currentTimeNanosUnsafe());
924
- effect = void_$1;
991
+ span.event("effect.sql.transaction.rollback", clock.currentTimeNanosUnsafe());
992
+ effect = orDie(id > 0 ? options.rollbackSavepoint(conn, id) : options.rollback(conn));
925
993
  }
926
- } else {
927
- span.event("effect.sql.transaction.rollback", clock.currentTimeNanosUnsafe());
928
- effect = orDie(id > 0 ? options.rollbackSavepoint(conn, id) : options.rollback(conn));
994
+ if (id > 0 && options.releaseSavepoint) effect = andThen(effect, orDie(options.releaseSavepoint(conn, id)));
995
+ return flatMap(effect, () => {
996
+ committed = isSuccess(exit);
997
+ return exit;
998
+ });
999
+ }, true);
1000
+ }), scope ? (eff) => onExitPrimitive(eff, (exit) => close(scope, exit), true) : identity));
1001
+ const settled = onExitPrimitive(transaction, () => {
1002
+ buffer.open = false;
1003
+ if (!committed || buffer.callbacks.length === 0) return;
1004
+ if (buffer.parent !== void 0) {
1005
+ buffer.parent.callbacks.push(...buffer.callbacks);
1006
+ return;
929
1007
  }
930
- if (id > 0 && options.releaseSavepoint) effect = andThen(effect, orDie(options.releaseSavepoint(conn, id)));
931
- return flatMap(effect, () => exit);
932
- }, true)), scope ? (eff) => onExitPrimitive(eff, (exit) => close(scope, exit), true) : identity));
933
- return id === 0 ? transaction : getUnsafe(services, transactionSemaphore).withPermit(transaction);
1008
+ return forEach(buffer.callbacks, runAfterCommit, { discard: true });
1009
+ }, true);
1010
+ return id === 0 ? settled : getUnsafe(services, transactionSemaphore).withPermit(settled);
934
1011
  })));
935
1012
  };
936
1013
  const TransactionConnection = (clientId) => Service(`effect/sql/SqlClient/TransactionConnection/${clientId}`);
937
1014
  const SafeIntegers = Reference("effect/sql/SqlClient/SafeIntegers", { defaultValue: () => false });
938
- //#endregion
939
- //#region node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Cache.js
1015
+ const BeginTransaction = Reference("effect/sql/SqlClient/BeginTransaction", { defaultValue: () => void 0 });
1016
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/Cache.js
940
1017
  const TypeId$3 = "~effect/Cache";
941
1018
  const makeWith = (lookup, options) => contextWith$1((context) => {
942
1019
  const self = Object.create(Proto$1);
@@ -1028,8 +1105,7 @@ const checkCapacity = (self) => {
1028
1105
  if (diff === 0) return;
1029
1106
  }
1030
1107
  };
1031
- //#endregion
1032
- //#region node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/schema/VariantSchema.js
1108
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/schema/VariantSchema.js
1033
1109
  const TypeId$2 = "~effect/schema/VariantSchema";
1034
1110
  const cacheSymbol = Symbol.for(`${TypeId$2}/cache`);
1035
1111
  const defaultCacheSymbol = Symbol.for(`${TypeId$2}/defaultCache`);
@@ -1038,7 +1114,8 @@ const FieldTypeId = "~effect/schema/VariantSchema/Field";
1038
1114
  const isField = (u) => hasProperty(u, FieldTypeId);
1039
1115
  const extract$1 = dual((args) => isStruct(args[0]), (self, variant, options) => {
1040
1116
  if (options?.isDefault === true && isSchema(self)) return self;
1041
- const cache = options?.isDefault === true ? self[defaultCacheSymbol] ?? (self[defaultCacheSymbol] = Object.create(null)) : self[cacheSymbol] ?? (self[cacheSymbol] = Object.create(null));
1117
+ const cacheKey = options?.isDefault === true ? defaultCacheSymbol : cacheSymbol;
1118
+ const cache = Object.hasOwn(self, cacheKey) ? self[cacheKey] : self[cacheKey] = Object.create(null);
1042
1119
  if (Object.hasOwn(cache, variant)) return cache[variant];
1043
1120
  const fields = {};
1044
1121
  for (const key of Object.keys(self[TypeId$2])) {
@@ -1061,19 +1138,31 @@ const extract$1 = dual((args) => isStruct(args[0]), (self, variant, options) =>
1061
1138
  const make$3 = (options) => {
1062
1139
  function Class(identifier) {
1063
1140
  return function(fields, annotations) {
1064
- const variantStruct = Struct$1(fields);
1065
- const schema = extract$1(variantStruct, options.defaultVariant, { isDefault: true });
1066
- const SClass = Class$2;
1067
- class Base extends SClass(identifier)(schema.fields, annotations) {
1068
- static [TypeId$2] = fields;
1069
- }
1070
- for (const variant of options.variants) Object.defineProperty(Base, variant, { value: extract$1(variantStruct, variant).annotate({
1071
- id: `${identifier}.${variant}`,
1072
- title: `${identifier}.${variant}`
1073
- }) });
1074
- return Base;
1141
+ return makeClass(fields, (defaultFields) => Class$2(identifier)(defaultFields, annotations));
1075
1142
  };
1076
1143
  }
1144
+ function makeClass(fields, makeSchemaClass) {
1145
+ const struct = Struct$1(fields);
1146
+ const SchemaClass = makeSchemaClass(extract$1(struct, options.defaultVariant, { isDefault: true }).fields);
1147
+ class Base extends SchemaClass {
1148
+ static [TypeId$2] = fields;
1149
+ static extend(identifier) {
1150
+ const extend = super.extend(identifier);
1151
+ return (extension, annotations) => isSchema(extension) ? makeClass({
1152
+ ...fields,
1153
+ ...extension.fields
1154
+ }, () => extend(extension, annotations)) : makeClass({
1155
+ ...fields,
1156
+ ...extension
1157
+ }, (defaultFields) => extend(defaultFields, annotations));
1158
+ }
1159
+ }
1160
+ for (const variant of options.variants) Object.defineProperty(Base, variant, { value: extract$1(struct, variant).annotate({
1161
+ id: `${SchemaClass.identifier}.${variant}`,
1162
+ title: `${SchemaClass.identifier}.${variant}`
1163
+ }) });
1164
+ return Base;
1165
+ }
1077
1166
  function FieldOnly(keys) {
1078
1167
  return function(schema) {
1079
1168
  const obj = {};
@@ -1133,8 +1222,7 @@ const Union$1 = (members, defaultVariant, variants) => {
1133
1222
  for (const variant of variants) Object.defineProperty(VariantUnion, variant, { value: Union$2(members.map((member) => extract$1(member, variant))) });
1134
1223
  return VariantUnion;
1135
1224
  };
1136
- //#endregion
1137
- //#region node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/schema/Model.js
1225
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/schema/Model.js
1138
1226
  const { Class, Field, FieldExcept, FieldOnly, Struct, Union, extract, fieldEvolve } = make$3({
1139
1227
  variants: [
1140
1228
  "select",
@@ -1207,8 +1295,7 @@ const DateTimeUpdateFromNumber = Field({
1207
1295
  update: DateTimeFromNumberWithNow,
1208
1296
  json: DateTimeUtcFromMillis
1209
1297
  });
1210
- //#endregion
1211
- //#region node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/sql/SqlResolver.js
1298
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/SqlResolver.js
1212
1299
  const SqlRequestProto = {
1213
1300
  ...Class$1.prototype,
1214
1301
  [symbol](that) {
@@ -1265,7 +1352,7 @@ const findById = (options) => {
1265
1352
  request.value.completeUnsafe(succeed$2(result));
1266
1353
  }
1267
1354
  if (isEmpty(idMap)) return;
1268
- forEach(idMap, (request) => {
1355
+ forEach$1(idMap, (request) => {
1269
1356
  request.completeUnsafe(constNoSuchElement);
1270
1357
  });
1271
1358
  })
@@ -1333,20 +1420,20 @@ const partitionRequestsById = function* (requests, schema) {
1333
1420
  };
1334
1421
  function transactionKey(entry) {
1335
1422
  const client = getOrUndefined(entry.context, SqlClient);
1336
- if (!client) return void 0;
1337
- const conn = getOrUndefined(entry.context, client.transactionService);
1338
- if (!conn) return void 0;
1339
- return byReferenceUnsafe(conn);
1423
+ const clientTransaction = client && getOrUndefined(entry.context, client.transactionService);
1424
+ const currentService = get$1(entry.context, CurrentTransactionService);
1425
+ const currentTransaction = currentService && getOrUndefined(entry.context, currentService);
1426
+ if (clientTransaction === void 0 || clientTransaction === currentTransaction) return currentTransaction && byReferenceUnsafe(currentTransaction);
1427
+ if (currentTransaction === void 0) return byReferenceUnsafe(clientTransaction);
1428
+ return [byReferenceUnsafe(clientTransaction), byReferenceUnsafe(currentTransaction)];
1340
1429
  }
1341
- //#endregion
1342
- //#region node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/sql/SqlSchema.js
1430
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/SqlSchema.js
1343
1431
  const findAll = (options) => {
1344
1432
  const encodeRequest = encodeEffect(options.Request);
1345
1433
  const decode = decodeUnknownEffect(mutable(ArraySchema(options.Result)));
1346
1434
  return (request) => flatMap(flatMap(encodeRequest(request), options.execute), decode);
1347
1435
  };
1348
- //#endregion
1349
- //#region node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/sql/SqlModel.js
1436
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/SqlModel.js
1350
1437
  const makeResolvers = (Model, options) => gen(function* () {
1351
1438
  const sql = yield* SqlClient;
1352
1439
  const idSchema = Model.fields[options.idColumn];
@@ -1359,7 +1446,7 @@ const makeResolvers = (Model, options) => gen(function* () {
1359
1446
  Request: Model.insert,
1360
1447
  Result: Model,
1361
1448
  execute: (request) => sql.onDialectOrElse({
1362
- mysql: () => forEach$1(request, (request) => sql`insert into ${sql(options.tableName)} ${sql.insert(request)};
1449
+ mysql: () => forEach(request, (request) => sql`insert into ${sql(options.tableName)} ${sql.insert(request)};
1363
1450
  select * from ${sql(options.tableName)} where ${withSoftDeleteFilter(sql`${sql(idColumn)} = LAST_INSERT_ID()`)};`.unprepared.pipe(map(([, results]) => results[0])), { concurrency: 10 }),
1364
1451
  orElse: () => sql`insert into ${sql(options.tableName)} ${sql.insert(request).returning("*")}`
1365
1452
  })
@@ -1382,8 +1469,7 @@ select * from ${sql(options.tableName)} where ${withSoftDeleteFilter(sql`${sql(i
1382
1469
  }).pipe(withSpan$1(`${options.spanPrefix}.deleteResolver`))
1383
1470
  };
1384
1471
  });
1385
- //#endregion
1386
- //#region src/ChunkRepo.ts
1472
+ // src/ChunkRepo.ts
1387
1473
  const ChunkId = Number$2.pipe(brand("ChunkRepo/ChunkId"));
1388
1474
  const SyncId = String$1.pipe(brand("ChunkRepo/SyncId"));
1389
1475
  const Float32ArraySchema = instanceOf(Float32Array);
@@ -1497,8 +1583,7 @@ const layer$4 = effect(ChunkRepo, gen(function* () {
1497
1583
  deleteForSyncId: (syncId) => sql`delete from chunks where syncId != ${syncId}`.pipe(mapError((reason) => new ChunkRepoError({ reason })))
1498
1584
  });
1499
1585
  }));
1500
- //#endregion
1501
- //#region src/CodeChunker.ts
1586
+ // src/CodeChunker.ts
1502
1587
  var CodeChunker = class extends Service()("clanka/CodeChunker") {};
1503
1588
  const sourceExtensions = new Set([
1504
1589
  "c",
@@ -1912,7 +1997,7 @@ const layer$3 = effect(CodeChunker, gen(function* () {
1912
1997
  const listFiles = fn("CodeChunker.listFiles")(function* (options) {
1913
1998
  const root = pathService.resolve(options.root);
1914
1999
  const maxFileSize = options.maxFileSize ?? "1M";
1915
- return yield* pipe(spawner.streamLines(make$13("rg", [
2000
+ return yield* pipe(spawner.streamLines(make$11("rg", [
1916
2001
  "--files",
1917
2002
  "--hidden",
1918
2003
  "--max-filesize",
@@ -1959,8 +2044,7 @@ const layer$3 = effect(CodeChunker, gen(function* () {
1959
2044
  chunkCodebase
1960
2045
  });
1961
2046
  }));
1962
- //#endregion
1963
- //#region node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/FiberHandle.js
2047
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/FiberHandle.js
1964
2048
  const TypeId$1 = "~effect/FiberHandle";
1965
2049
  const isFiberHandle = (u) => hasProperty(u, TypeId$1);
1966
2050
  const Proto = {
@@ -1977,7 +2061,8 @@ const makeUnsafe = () => {
1977
2061
  const self = Object.create(Proto);
1978
2062
  self.state = {
1979
2063
  _tag: "Open",
1980
- fiber: void 0
2064
+ fiber: void 0,
2065
+ fibers: new Set()
1981
2066
  };
1982
2067
  self.deferred = makeUnsafe$2();
1983
2068
  return self;
@@ -1986,7 +2071,7 @@ const make$2 = () => acquireRelease(sync(() => makeUnsafe()), (handle) => {
1986
2071
  const state = handle.state;
1987
2072
  if (state._tag === "Closed") return void_$1;
1988
2073
  handle.state = { _tag: "Closed" };
1989
- return state.fiber ? into(asVoid(interruptAs(state.fiber, internalFiberId)), handle.deferred) : done(handle.deferred, void_$3);
2074
+ return into(interruptAllAs(state.fibers, internalFiberId), handle.deferred);
1990
2075
  });
1991
2076
  const internalFiberId = -1;
1992
2077
  const isInternalInterruption = toPredicate(compose(filterInterruptors, has(internalFiberId)));
@@ -2004,9 +2089,13 @@ const setUnsafe = dual((args) => isFiberHandle(args[0]), (self, fiber, options)
2004
2089
  }
2005
2090
  }
2006
2091
  self.state.fiber = fiber;
2092
+ self.state.fibers.add(fiber);
2007
2093
  previous?.interruptUnsafe(internalFiberId);
2008
2094
  fiber.addObserver((exit) => {
2009
- if (self.state._tag === "Open" && fiber === self.state.fiber) self.state.fiber = void 0;
2095
+ if (self.state._tag === "Open") {
2096
+ self.state.fibers.delete(fiber);
2097
+ if (fiber === self.state.fiber) self.state.fiber = void 0;
2098
+ }
2010
2099
  if (isFailure(exit) && (options?.propagateInterruption === true ? !isInternalInterruption(exit.cause) : !hasInterruptsOnly(exit.cause))) doneUnsafe(self.deferred, exit);
2011
2100
  });
2012
2101
  });
@@ -2030,8 +2119,7 @@ const runImpl = (self, effect, options) => withFiber((parent) => {
2030
2119
  setUnsafe(self, fiber, options);
2031
2120
  return succeed(fiber);
2032
2121
  });
2033
- //#endregion
2034
- //#region node_modules/.pnpm/@effect+sql-sqlite-node@4.0.5_effect@4.0.5/node_modules/@effect/sql-sqlite-node/dist/SqliteClient.js
2122
+ // node_modules/.pnpm/@effect+sql-sqlite-node@4.1.1_effect@4.1.1/node_modules/@effect/sql-sqlite-node/dist/SqliteClient.js
2035
2123
  const ATTR_DB_SYSTEM_NAME = "db.system.name";
2036
2124
  const MAX_BUSY_TIMEOUT = 2147483647;
2037
2125
  const NANOS_PER_MILLI = BigInt(1e6);
@@ -2162,17 +2250,19 @@ const make$1 = (options) => gen(function* () {
2162
2250
  }
2163
2251
  });
2164
2252
  });
2165
- const { acquirer, borrower, onCommitFailure, transactionAcquirer } = makeSqliteAcquirers({
2253
+ const { acquirer, borrower, isTransaction, onCommitFailure, transactionAcquirer } = makeSqliteAcquirers({
2166
2254
  connection: succeed(connection),
2167
- semaphore: yield* make$12(1),
2255
+ semaphore: yield* make$13(1),
2168
2256
  isTransaction: (conn) => conn.isTransaction()
2169
2257
  });
2170
2258
  return Object.assign(yield* make$4({
2259
+ driver: "sqlite-node",
2171
2260
  acquirer,
2172
2261
  borrower,
2173
2262
  compiler,
2174
2263
  transactionAcquirer,
2175
2264
  onCommitFailure,
2265
+ isTransaction,
2176
2266
  releaseSavepoint: (name) => `RELEASE SAVEPOINT ${name}`,
2177
2267
  beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
2178
2268
  spanAttributes: [...options.spanAttributes ? Object.entries(options.spanAttributes) : [], [ATTR_DB_SYSTEM_NAME, "sqlite"]],
@@ -2198,18 +2288,11 @@ const sqliteCauseWithErrno = (cause) => {
2198
2288
  const setLoadExtensionEnabled = (db, enabled) => {
2199
2289
  if (typeof db.enableLoadExtension === "function") db.enableLoadExtension(enabled);
2200
2290
  };
2201
- //#endregion
2202
- //#region node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/sql/Migrator.js
2203
- var __rewriteRelativeImportExtension = void 0 && (void 0).__rewriteRelativeImportExtension || function(path, preserveJsx) {
2204
- if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
2205
- return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
2206
- });
2207
- return path;
2208
- };
2291
+ // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/Migrator.js
2209
2292
  var MigrationError = class extends TaggedError$1("MigrationError") {};
2210
- const make = ({ dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, table = "effect_sql_migrations" }) => gen(function* () {
2293
+ const make = ({ transformWrites = identity, dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, table = "effect_sql_migrations" }) => gen(function* () {
2211
2294
  const sql = yield* SqlClient;
2212
- const ensureMigrationsTable = sql.onDialectOrElse({
2295
+ const createMigrationsTable = transformWrites(sql.onDialectOrElse({
2213
2296
  mssql: () => sql`IF OBJECT_ID(N'${sql.literal(table)}', N'U') IS NULL
2214
2297
  CREATE TABLE ${sql(table)} (
2215
2298
  migration_id INT NOT NULL PRIMARY KEY,
@@ -2222,22 +2305,32 @@ const make = ({ dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, tab
2222
2305
  name VARCHAR(255) NOT NULL,
2223
2306
  PRIMARY KEY (migration_id)
2224
2307
  )`,
2225
- pg: () => flatMap(migrationsTableExists(sql, table), (exists) => exists ? void_$1 : asVoid(sql`CREATE TABLE ${sql(table)} (
2308
+ clickhouse: () => sql`CREATE TABLE IF NOT EXISTS ${sql(table)} (
2309
+ migration_id Int32,
2310
+ created_at DateTime DEFAULT now(),
2311
+ name String
2312
+ ) ENGINE = MergeTree
2313
+ ORDER BY migration_id`,
2314
+ pg: () => sql`CREATE TABLE ${sql(table)} (
2226
2315
  migration_id integer primary key,
2227
2316
  created_at timestamp with time zone not null default now(),
2228
2317
  name text not null
2229
- )`).pipe(catch_((error) => flatMap(migrationsTableExists(sql, table), (exists) => exists ? void_$1 : fail(error))))),
2318
+ )`,
2230
2319
  orElse: () => sql`CREATE TABLE IF NOT EXISTS ${sql(table)} (
2231
2320
  migration_id integer PRIMARY KEY NOT NULL,
2232
2321
  created_at datetime NOT NULL DEFAULT current_timestamp,
2233
2322
  name VARCHAR(255) NOT NULL
2234
2323
  )`
2324
+ }));
2325
+ const ensureMigrationsTable = sql.onDialectOrElse({
2326
+ pg: () => flatMap(migrationsTableExists(sql, table), (exists) => exists ? void_$1 : asVoid(createMigrationsTable).pipe(catch_((error) => flatMap(migrationsTableExists(sql, table), (exists) => exists ? void_$1 : fail(error))))),
2327
+ orElse: () => createMigrationsTable
2235
2328
  });
2236
- const insertMigrations = (rows) => sql`INSERT INTO ${sql(table)} ${sql.insert(rows.map(([migration_id, name]) => ({
2329
+ const insertMigrations = (rows) => transformWrites(sql`INSERT INTO ${sql(table)} ${sql.insert(map$1(rows, ([migration_id, name]) => ({
2237
2330
  migration_id,
2238
2331
  name
2239
- })))}`.withoutTransform;
2240
- const latestMigration = map(sql`SELECT migration_id, name, created_at FROM ${sql(table)} ORDER BY migration_id DESC`.withoutTransform, (_) => map$1(fromNullishOr(_[0]), ({ created_at, migration_id, name }) => ({
2332
+ })))}`.withoutTransform);
2333
+ const latestMigration = map(sql`SELECT migration_id, name, created_at FROM ${sql(table)} ORDER BY migration_id DESC`.withoutTransform, (_) => map$2(fromNullishOr(_[0]), ({ created_at, migration_id, name }) => ({
2241
2334
  id: migration_id,
2242
2335
  name,
2243
2336
  createdAt: created_at
@@ -2252,11 +2345,15 @@ const make = ({ dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, tab
2252
2345
  kind: "ImportError",
2253
2346
  message: `Default export was not an Effect for migration "${id}_${name}"`
2254
2347
  })));
2255
- const runMigration = (id, name, effect) => catch_(effect, (error) => die(new MigrationError({
2348
+ const runMigration = (id, name, effect) => mapError(effect, (error) => new MigrationError({
2256
2349
  cause: error,
2257
2350
  kind: "Failed",
2258
2351
  message: `Migration "${id}_${name}" failed`
2259
- })));
2352
+ }));
2353
+ const transactional = sql.onDialectOrElse({
2354
+ clickhouse: () => false,
2355
+ orElse: () => true
2356
+ });
2260
2357
  const run = gen(function* () {
2261
2358
  yield* sql.onDialectOrElse({
2262
2359
  pg: () => sql`LOCK TABLE ${sql(table)} IN ACCESS EXCLUSIVE MODE`,
@@ -2280,11 +2377,11 @@ const make = ({ dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, tab
2280
2377
  yield* loadMigration(resolved)
2281
2378
  ]);
2282
2379
  }
2283
- if (required.length > 0) yield* pipe(insertMigrations(required.map(([id, name]) => [id, name])), mapError((error) => isConstraintConflict(error) ? new MigrationError({
2380
+ if (transactional && isArrayNonEmpty(required)) yield* pipe(insertMigrations(map$1(required, ([id, name]) => [id, name])), mapError((error) => isConstraintConflict(error) ? new MigrationError({
2284
2381
  kind: "Locked",
2285
2382
  message: "Migrations already running"
2286
2383
  }) : error));
2287
- 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 });
2384
+ yield* forEach(required, ([id, name, effect]) => logDebug(`Running migration`).pipe(flatMap(() => runMigration(id, name, effect)), andThen(transactional ? void_$1 : insertMigrations([[id, name]])), annotateLogs("migration_id", String(id)), annotateLogs("migration_name", name), withSpan(`Migrator ${id}_${name}`)), { discard: true });
2288
2385
  yield* pipe(latestMigration, flatMap(match({
2289
2386
  onNone: () => logDebug(`Migrations complete`),
2290
2387
  onSome: (_) => logDebug(`Migrations complete`).pipe(annotateLogs("latest_migration_id", _.id.toString()), annotateLogs("latest_migration_name", _.name))
@@ -2292,7 +2389,7 @@ const make = ({ dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, tab
2292
2389
  return required.map(([id, name]) => [id, name]);
2293
2390
  });
2294
2391
  yield* ensureMigrationsTable;
2295
- const completed = yield* pipe(sql.withTransaction(run), catchTag("MigrationError", (_) => _.kind === "Locked" ? as(logDebug(_.message), []) : fail(_)));
2392
+ const completed = yield* pipe(transactional ? sql.withTransaction(run) : run, catchTag("MigrationError", (_) => _.kind === "Locked" ? as(logDebug(_.message), []) : fail(_)));
2296
2393
  if (schemaDirectory && completed.length > 0) yield* dumpSchema(`${schemaDirectory}/_schema.sql`, table).pipe(catchCause((cause) => logInfo("Could not dump schema", cause)));
2297
2394
  return completed;
2298
2395
  });
@@ -2302,17 +2399,15 @@ const migrationsTableExists = (sql, table) => {
2302
2399
  };
2303
2400
  const migrationOrder = make$10(([a], [b]) => Number$1(a, b));
2304
2401
  const isConstraintConflict = (error) => error.reason._tag === "ConstraintError" || error.reason._tag === "UniqueViolation";
2305
- const fromRecord = (migrations) => pipe(Object.keys(migrations), flatMapNullishOr((_) => _.match(/^(\d+)_(.+)$/)), map$2(([key, id, name]) => [
2402
+ const fromRecord = (migrations) => pipe(Object.keys(migrations), flatMapNullishOr((_) => _.match(/^(\d+)_(.+)$/)), map$1(([key, id, name]) => [
2306
2403
  Number(id),
2307
2404
  name,
2308
2405
  succeed(migrations[key])
2309
2406
  ]), sort(migrationOrder), succeed);
2310
- //#endregion
2311
- //#region node_modules/.pnpm/@effect+sql-sqlite-node@4.0.5_effect@4.0.5/node_modules/@effect/sql-sqlite-node/dist/SqliteMigrator.js
2407
+ // node_modules/.pnpm/@effect+sql-sqlite-node@4.1.1_effect@4.1.1/node_modules/@effect/sql-sqlite-node/dist/SqliteMigrator.js
2312
2408
  const run = make({});
2313
2409
  const layer$1 = (options) => effectDiscard(run(options));
2314
- //#endregion
2315
- //#region src/Sqlite.ts
2410
+ // src/Sqlite.ts
2316
2411
  const SqliteLayer = (database) => layer$1({ loader: fromRecord({ "0001_create_chunks": gen(function* () {
2317
2412
  const sql = yield* SqlClient;
2318
2413
  yield* sql`CREATE TABLE IF NOT EXISTS chunks (
@@ -2332,8 +2427,7 @@ const SqliteLayer = (database) => layer$1({ loader: fromRecord({ "0001_create_ch
2332
2427
  if (directory === ".") return;
2333
2428
  yield* fs.makeDirectory(directory, { recursive: true });
2334
2429
  }))));
2335
- //#endregion
2336
- //#region src/SemanticSearch.ts
2430
+ // src/SemanticSearch.ts
2337
2431
  const normalizePath = (path) => path.replace(/\\/g, "/");
2338
2432
  const resolveChunkConfig = (options) => ({
2339
2433
  chunkSize: 30,
@@ -2449,7 +2543,6 @@ const layer = (options) => effect(SemanticSearch, gen(function* () {
2449
2543
  }, orDie)
2450
2544
  });
2451
2545
  })).pipe(provide$1([layer$3, layer$4.pipe(provide$1(SqliteLayer(options.database ?? ".clanka/search.sqlite")))]));
2452
- //#endregion
2453
2546
  export { SemanticSearch, chunkEmbeddingInput, layer, makeEmbeddingResolver, maybeRemoveFile, maybeUpdateFile };
2454
2547
 
2455
- //# sourceMappingURL=SemanticSearch-BcLFv9qz.mjs.map
2548
+ //# sourceMappingURL=SemanticSearch-BiwCnpKX.mjs.map