clanka 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -3
- package/dist/Acp.test.js +2 -3
- package/dist/Acp.test.js.map +1 -1
- package/dist/AcpImage.test.js +0 -1
- package/dist/AcpImage.test.js.map +1 -1
- package/dist/Agent.d.ts.map +1 -1
- package/dist/Agent.js +7 -7
- package/dist/Agent.js.map +1 -1
- package/dist/Agent.test.js +7 -7
- package/dist/Agent.test.js.map +1 -1
- package/dist/AgentBashJobs.test.js +7 -7
- package/dist/AgentBashJobs.test.js.map +1 -1
- package/dist/AgentCallerConfig.test.js +0 -1
- package/dist/AgentCallerConfig.test.js.map +1 -1
- package/dist/AgentExecutor.d.ts +2 -3
- package/dist/AgentExecutor.d.ts.map +1 -1
- package/dist/AgentExecutor.js +4 -13
- package/dist/AgentExecutor.js.map +1 -1
- package/dist/AgentExecutor.test.js +20 -20
- package/dist/AgentExecutor.test.js.map +1 -1
- package/dist/AgentImage.test.js +1 -2
- package/dist/AgentImage.test.js.map +1 -1
- package/dist/AgentSkills.test.js +0 -2
- package/dist/AgentSkills.test.js.map +1 -1
- package/dist/AgentSubagents.test.js +57 -29
- package/dist/AgentSubagents.test.js.map +1 -1
- package/dist/AgentTools.d.ts +6 -238
- package/dist/AgentTools.d.ts.map +1 -1
- package/dist/AgentTools.js +11 -39
- package/dist/AgentTools.js.map +1 -1
- package/dist/ClaudeAgent.test.js +0 -1
- package/dist/ClaudeAgent.test.js.map +1 -1
- package/dist/ScriptFormatting.d.ts +5 -0
- package/dist/ScriptFormatting.d.ts.map +1 -1
- package/dist/ScriptFormatting.js +255 -53
- package/dist/ScriptFormatting.js.map +1 -1
- package/dist/ScriptFormatting.test.js +16 -0
- package/dist/ScriptFormatting.test.js.map +1 -1
- package/dist/bin/{Latch-DOdbsGMQ.mjs → Latch-BE6_TYRL.mjs} +1 -1
- package/dist/bin/{McpClient-B-FFG6Pg.mjs → McpClient-DCt4v5W5.mjs} +2 -2
- package/dist/bin/{OutputFormatter-DhhP2i-7.mjs → OutputFormatter-DaFv_C_I.mjs} +2 -3
- package/dist/bin/{Schema-CFdSO6iH.mjs → Schema-B3MiG1aD.mjs} +204 -568
- package/dist/bin/cli.mjs +5106 -2479
- package/dist/bin/{upgrade-C4aOEWJH.mjs → upgrade-WqgIU_21.mjs} +3 -3
- package/dist/cli.js +2 -25
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +0 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -8
- package/dist/index.js.map +1 -1
- package/package.json +1 -7
- package/src/Acp.test.ts +2 -3
- package/src/AcpImage.test.ts +0 -1
- package/src/Agent.test.ts +10 -7
- package/src/Agent.ts +8 -10
- package/src/AgentBashJobs.test.ts +9 -9
- package/src/AgentCallerConfig.test.ts +0 -1
- package/src/AgentExecutor.test.ts +20 -20
- package/src/AgentExecutor.ts +4 -16
- package/src/AgentImage.test.ts +1 -2
- package/src/AgentSkills.test.ts +0 -2
- package/src/AgentSubagents.test.ts +77 -34
- package/src/AgentTools.ts +19 -51
- package/src/ClaudeAgent.test.ts +0 -1
- package/src/ScriptFormatting.test.ts +20 -0
- package/src/ScriptFormatting.ts +234 -47
- package/src/cli.ts +1 -56
- package/src/index.ts +0 -10
- package/dist/ChunkRepo.d.ts +0 -173
- package/dist/ChunkRepo.d.ts.map +0 -1
- package/dist/ChunkRepo.js +0 -168
- package/dist/ChunkRepo.js.map +0 -1
- package/dist/ChunkRepo.test.d.ts +0 -2
- package/dist/ChunkRepo.test.d.ts.map +0 -1
- package/dist/ChunkRepo.test.js +0 -63
- package/dist/ChunkRepo.test.js.map +0 -1
- package/dist/CodeChunker.d.ts +0 -84
- package/dist/CodeChunker.d.ts.map +0 -1
- package/dist/CodeChunker.js +0 -658
- package/dist/CodeChunker.js.map +0 -1
- package/dist/CodeChunker.test.d.ts +0 -2
- package/dist/CodeChunker.test.d.ts.map +0 -1
- package/dist/CodeChunker.test.js +0 -434
- package/dist/CodeChunker.test.js.map +0 -1
- package/dist/SemanticSearch/Service.d.ts +0 -31
- package/dist/SemanticSearch/Service.d.ts.map +0 -1
- package/dist/SemanticSearch/Service.js +0 -29
- package/dist/SemanticSearch/Service.js.map +0 -1
- package/dist/SemanticSearch.d.ts +0 -34
- package/dist/SemanticSearch.d.ts.map +0 -1
- package/dist/SemanticSearch.js +0 -171
- package/dist/SemanticSearch.js.map +0 -1
- package/dist/SemanticSearch.test.d.ts +0 -2
- package/dist/SemanticSearch.test.d.ts.map +0 -1
- package/dist/SemanticSearch.test.js +0 -34
- package/dist/SemanticSearch.test.js.map +0 -1
- package/dist/Sqlite.d.ts +0 -15
- package/dist/Sqlite.d.ts.map +0 -1
- package/dist/Sqlite.js +0 -44
- package/dist/Sqlite.js.map +0 -1
- package/dist/bin/AiError-DBaKz35C.mjs +0 -2723
- package/dist/bin/SemanticSearch-C3a7LAQr.mjs +0 -2558
- package/src/ChunkRepo.test.ts +0 -89
- package/src/ChunkRepo.ts +0 -260
- package/src/CodeChunker.test.ts +0 -493
- package/src/CodeChunker.ts +0 -1018
- package/src/SemanticSearch/Service.ts +0 -50
- package/src/SemanticSearch.test.ts +0 -51
- package/src/SemanticSearch.ts +0 -282
- package/src/Sqlite.ts +0 -60
|
@@ -1,2558 +0,0 @@
|
|
|
1
|
-
import { $a as tapCause, $i as gen, Aa as provideService, Ac as exitHasInterrupts, Ai as contextWith, Ao as set, As as effectDiscard, Au as fromNullishOr, B as String$1, Bd as flow, Bi as flatMap, Bu as none, Cd as isNotNull, Ci as catchIf, Cl as fromIterable, Cu as omit, Di as catchTags, Do as isEmpty, E as Natural, Ea as orElseSucceed, Ei as catchTag, El as isArrayNonEmpty, Eo as get$2, Eu as filter, Fc as fiberInterrupt, Ga as serviceOption, Gi as forEach, Gu as Number$2, H as Struct$2, Ha as scoped, Hc as forkUnsafe, Ia as retry, Id as constUndefined, Ii as fail, Il as sort, Iu as isNone, Jc as onExitUnsafe, K as TaggedError, Kc as makeSpanUnsafe, Ki as forever, Ks as close, La as runFork, Li as failCause$1, Ls as provide$1, Lu as isSome, M as Number$1, Mi as die, Ml as map$2, N as Option, Oc as contextWith$1, Oi as catch_, Oo as make$8, Os as effect, P as OptionFromNullOr, Pa as request$1, Qa as tap, Ra as runForkWith, Rc as fiberJoin, Ro as spaced, Rs as provideMerge, Ru as map$3, Sa as onExitPrimitive, Sc as ClockRef, Sl as flatMapNullishOr, So as Class$2, Su as merge, Ta as orDie, To as forEach$1, Ud as pipe, Ui as fn, Us as Scope, Uu as some, Vd as identity, Wd as pipeArguments, Wi as fnUntraced, Ws as addFinalizer, Xa as suspend, Xi as forkScoped, Xr as removeTime, Yo as Clock, Yr as now, Ys as make$7, Yu as Prototype, Za as sync, Zc as succeed$1, Zo as monotonicTimeNanos, Zs as provide, Zu as PipeInspectableProto, _a as matchCauseEffect, _d as equals, _l as empty, _u as getOrUndefined, a as BooleanFromBit, aa as logDebug, ac as into, ai as acquireRelease, ao as try_, as as combine, ba as onError, bc as succeed$2, bd as symbol$1, bi as catchDefect, bn as toType, bs as makeDieReason, bt as instanceOf, bu as make$9, ca as logInfo, ci as all, co as uninterruptibleMask, cu as seconds, d as DateTimeUtcFromMillis, da as map, di as annotateLogs, dn as mutable, do as useSpan, dr as transform$1, ds as fromReasons, du as Reference, ea as ignore, ec as TracerTimingEnabled$1, es as NoSuchElementError, eu as fromInputUnsafe, f as DateTimeUtcFromString, fi as as, fl as compose, fn as optional, fo as void_$1, ft as decodeTo, fu as Service, ga as matchCauseEager, gd as byReferenceUnsafe, go as withLogSpan, gt as encodeEffect, gu as getOption, ho as withFiber, hr as map$1, hu as get$1, i as Boolean, ia as isEffect, il as TracerTimingEnabled, io as tryPromise, iu as isZero, j as NullOr, ji as delay, jo as size, ka as provideContext, kc as endSpan, ki as context, ko as remove, ks as effectContext, ku as flatten, l as DateTimeUtc, lc as makeUnsafe$2, li as andThen, ls as filterInterruptors, lu as toMillis, ma as mapError, mc as failCause, mi as asVoid, ml as toPredicate, mr as dateTimeUtcFromInput, n as ArraySchema, na as interrupt, nc as doneUnsafe, nl as updateContext, nn as isSchema, nu as infinity, od as withFiber$1, oi as acquireUseRelease, ol as ParentSpan, ot as brand, ou as millis, p as Defect, pc as fail$1, pl as has, pn as optionalKey, pr as transformOptional, ps as hasInterruptsOnly, pt as decodeUnknownEffect, pu as add, qa as succeed, qr as formatIsoDate, qu as make$10, rl as void_$2, rt as Union$2, ru as isFinite, s as Class$1, sd as assignProperty, so as uninterruptible, su as minutes, ta as ignoreCause, u as DateTimeUtcFromDate, ua as makeSpanScoped, ui as annotateCurrentSpan, ul as TaggedError$1, uu as zero, vc as isFailure, vd as symbol, vi as catchCause, vo as withSpan, vr as transform, vs as isFailReason, wi as catchNoSuchElement, wn as evolve, wo as empty$1, ws as reasonAnnotations, xa as onExit, xc as void_$3, xd as hasProperty, xn as withConstructorDefault, yc as isSuccess, yd as hash, yu as getUnsafe, zd as dual, zi as filterOrFail, zu as match } from "./Schema-CFdSO6iH.mjs";
|
|
2
|
-
import { D as Path, E as Console, O as FileSystem, T as ChildProcessSpawner, a as makeGrouped, f as SemanticSearch, h as map$4, i as batchN, m as maybeUpdateFile, n as EmbeddingModel, o as setDelay, p as maybeRemoveFile, r as EmbeddingRequest, s as withSpan$1, t as Dimensions, w as make$11 } from "./cli.mjs";
|
|
3
|
-
import { $t as offerUnsafe, Ht as makeUnsafe$3, It as unwrap, J as fromArrayEffect, Jt as failCauseUnsafe, Mt as tap$1, P as die$1, U as flatMap$1, Vt as make$13, Yt as make$12, gt as provideService$1, hn as runIn, mn as join$1, pn as interruptAllAs, q as fromArray, tt as fromQueue, vt as runCollect, yt as runDrain } from "./AiError-DBaKz35C.mjs";
|
|
4
|
-
import { createHash } from "node:crypto";
|
|
5
|
-
import TreeSitter from "tree-sitter";
|
|
6
|
-
import JavaScript from "tree-sitter-javascript";
|
|
7
|
-
import { DatabaseSync, backup } from "node:sqlite";
|
|
8
|
-
import TreeSitterTypeScript from "tree-sitter-typescript";
|
|
9
|
-
import { getLoadablePath } from "sqlite-vec";
|
|
10
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/internal/sql.js
|
|
11
|
-
const CurrentTransactionService = Reference("effect/sql/CurrentTransactionService", { defaultValue: () => void 0 });
|
|
12
|
-
const waitClock = (fiber) => fiber.getRef(TracerTimingEnabled) ? fiber.getRef(Clock) : void 0;
|
|
13
|
-
const recordConnectionWait = (span, clock) => span.attribute("db.client.connection.wait_time_ms", Number(clock.currentTimeNanosUnsafe() - span.status.startTime) / 1e6);
|
|
14
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/reactivity/Reactivity.js
|
|
15
|
-
const TypeId$6 = "~effect/reactivity/Reactivity";
|
|
16
|
-
const Reactivity = Service("effect/reactivity/Reactivity");
|
|
17
|
-
const make$6 = sync(() => {
|
|
18
|
-
const handlers = new Map();
|
|
19
|
-
const runHandlers = (hashes) => {
|
|
20
|
-
const ran = new Set();
|
|
21
|
-
for (const hash of hashes) handlers.get(hash)?.forEach((run) => {
|
|
22
|
-
if (ran.has(run)) return;
|
|
23
|
-
ran.add(run);
|
|
24
|
-
run();
|
|
25
|
-
});
|
|
26
|
-
};
|
|
27
|
-
const invalidateUnsafe = (keys) => {
|
|
28
|
-
const hashes = new Set();
|
|
29
|
-
keysToHashes(keys, (hash) => hashes.add(hash));
|
|
30
|
-
runHandlers(hashes);
|
|
31
|
-
};
|
|
32
|
-
const invalidate = (keys) => contextWith((services) => {
|
|
33
|
-
const pending = getOrUndefined(services, PendingInvalidation);
|
|
34
|
-
if (pending) keysToHashes(keys, (hash) => {
|
|
35
|
-
pending.add(hash);
|
|
36
|
-
});
|
|
37
|
-
else invalidateUnsafe(keys);
|
|
38
|
-
return void_$1;
|
|
39
|
-
});
|
|
40
|
-
const mutation = (keys, effect) => tap(effect, invalidate(keys));
|
|
41
|
-
const registerUnsafe = (keys, handler) => {
|
|
42
|
-
const resolvedKeys = [];
|
|
43
|
-
keysToHashes(keys, (hash) => {
|
|
44
|
-
resolvedKeys.push(hash);
|
|
45
|
-
let set = handlers.get(hash);
|
|
46
|
-
if (set === void 0) {
|
|
47
|
-
set = new Set();
|
|
48
|
-
handlers.set(hash, set);
|
|
49
|
-
}
|
|
50
|
-
set.add(handler);
|
|
51
|
-
});
|
|
52
|
-
return () => {
|
|
53
|
-
for (let i = 0; i < resolvedKeys.length; i++) {
|
|
54
|
-
const set = handlers.get(resolvedKeys[i]);
|
|
55
|
-
if (set === void 0) continue;
|
|
56
|
-
set.delete(handler);
|
|
57
|
-
if (set.size === 0) handlers.delete(resolvedKeys[i]);
|
|
58
|
-
}
|
|
59
|
-
};
|
|
60
|
-
};
|
|
61
|
-
const query = (keys, effect) => gen(function* () {
|
|
62
|
-
const services = yield* context();
|
|
63
|
-
const scope = get$1(services, Scope);
|
|
64
|
-
const results = yield* make$12();
|
|
65
|
-
const runFork = flow(runForkWith(services), runIn(scope));
|
|
66
|
-
let running = false;
|
|
67
|
-
let pending = false;
|
|
68
|
-
let stopped = false;
|
|
69
|
-
const handleExit = (exit) => {
|
|
70
|
-
if (exit._tag === "Failure") {
|
|
71
|
-
stopped = true;
|
|
72
|
-
pending = false;
|
|
73
|
-
running = false;
|
|
74
|
-
cancel();
|
|
75
|
-
failCauseUnsafe(results, exit.cause);
|
|
76
|
-
return;
|
|
77
|
-
} else offerUnsafe(results, exit.value);
|
|
78
|
-
if (pending) {
|
|
79
|
-
pending = false;
|
|
80
|
-
runFork(effect).addObserver(handleExit);
|
|
81
|
-
} else running = false;
|
|
82
|
-
};
|
|
83
|
-
function run() {
|
|
84
|
-
if (stopped) return;
|
|
85
|
-
if (running) {
|
|
86
|
-
pending = true;
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
running = true;
|
|
90
|
-
runFork(effect).addObserver(handleExit);
|
|
91
|
-
}
|
|
92
|
-
const cancel = registerUnsafe(keys, run);
|
|
93
|
-
yield* addFinalizer(scope, sync(cancel));
|
|
94
|
-
run();
|
|
95
|
-
return results;
|
|
96
|
-
});
|
|
97
|
-
const stream = (tables, effect) => query(tables, effect).pipe(map(fromQueue), unwrap);
|
|
98
|
-
const withBatch = (effect) => suspend(() => {
|
|
99
|
-
const pending = new Set();
|
|
100
|
-
return effect.pipe(provideService(PendingInvalidation, pending), onExit((_) => sync(() => runHandlers(pending))));
|
|
101
|
-
});
|
|
102
|
-
return Reactivity.of({
|
|
103
|
-
[TypeId$6]: TypeId$6,
|
|
104
|
-
mutation,
|
|
105
|
-
query,
|
|
106
|
-
stream,
|
|
107
|
-
invalidateUnsafe,
|
|
108
|
-
invalidate,
|
|
109
|
-
registerUnsafe,
|
|
110
|
-
withBatch
|
|
111
|
-
});
|
|
112
|
-
});
|
|
113
|
-
var PendingInvalidation = class extends Service()("effect/reactivity/Reactivity/PendingInvalidation") {};
|
|
114
|
-
const layer$5 = effect(Reactivity)(make$6);
|
|
115
|
-
function stringOrHash(u) {
|
|
116
|
-
switch (typeof u) {
|
|
117
|
-
case "string":
|
|
118
|
-
case "number":
|
|
119
|
-
case "bigint":
|
|
120
|
-
case "boolean": return String(u);
|
|
121
|
-
default: return hash(u);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
const keysToHashes = (keys, f) => {
|
|
125
|
-
if (Array.isArray(keys)) {
|
|
126
|
-
for (let i = 0; i < keys.length; i++) f(stringOrHash(keys[i]));
|
|
127
|
-
return;
|
|
128
|
-
}
|
|
129
|
-
for (const key in keys) {
|
|
130
|
-
f(key);
|
|
131
|
-
const ids = keys[key];
|
|
132
|
-
for (let i = 0; i < ids.length; i++) f(`${key}:${stringOrHash(ids[i])}`);
|
|
133
|
-
}
|
|
134
|
-
};
|
|
135
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/SqlError.js
|
|
136
|
-
const TypeId$5 = "~effect/sql/SqlError";
|
|
137
|
-
const ReasonTypeId = "~effect/sql/SqlError/Reason";
|
|
138
|
-
const ReasonFields = {
|
|
139
|
-
cause: Defect(),
|
|
140
|
-
message: optional(String$1),
|
|
141
|
-
operation: optional(String$1)
|
|
142
|
-
};
|
|
143
|
-
var ConnectionError = class extends TaggedError("effect/sql/SqlError/ConnectionError")("ConnectionError", ReasonFields) {
|
|
144
|
-
[ReasonTypeId] = ReasonTypeId;
|
|
145
|
-
get isRetryable() {
|
|
146
|
-
return true;
|
|
147
|
-
}
|
|
148
|
-
};
|
|
149
|
-
var AuthenticationError = class extends TaggedError("effect/sql/SqlError/AuthenticationError")("AuthenticationError", ReasonFields) {
|
|
150
|
-
[ReasonTypeId] = ReasonTypeId;
|
|
151
|
-
get isRetryable() {
|
|
152
|
-
return false;
|
|
153
|
-
}
|
|
154
|
-
};
|
|
155
|
-
var AuthorizationError = class extends TaggedError("effect/sql/SqlError/AuthorizationError")("AuthorizationError", ReasonFields) {
|
|
156
|
-
[ReasonTypeId] = ReasonTypeId;
|
|
157
|
-
get isRetryable() {
|
|
158
|
-
return false;
|
|
159
|
-
}
|
|
160
|
-
};
|
|
161
|
-
var SqlSyntaxError = class extends TaggedError("effect/sql/SqlError/SqlSyntaxError")("SqlSyntaxError", ReasonFields) {
|
|
162
|
-
[ReasonTypeId] = ReasonTypeId;
|
|
163
|
-
get isRetryable() {
|
|
164
|
-
return false;
|
|
165
|
-
}
|
|
166
|
-
};
|
|
167
|
-
const UniqueViolationFields = {
|
|
168
|
-
...ReasonFields,
|
|
169
|
-
constraint: String$1
|
|
170
|
-
};
|
|
171
|
-
var UniqueViolation = class extends TaggedError("effect/sql/SqlError/UniqueViolation")("UniqueViolation", UniqueViolationFields) {
|
|
172
|
-
[ReasonTypeId] = ReasonTypeId;
|
|
173
|
-
get isRetryable() {
|
|
174
|
-
return false;
|
|
175
|
-
}
|
|
176
|
-
};
|
|
177
|
-
var ConstraintError = class extends TaggedError("effect/sql/SqlError/ConstraintError")("ConstraintError", ReasonFields) {
|
|
178
|
-
[ReasonTypeId] = ReasonTypeId;
|
|
179
|
-
get isRetryable() {
|
|
180
|
-
return false;
|
|
181
|
-
}
|
|
182
|
-
};
|
|
183
|
-
var DeadlockError = class extends TaggedError("effect/sql/SqlError/DeadlockError")("DeadlockError", ReasonFields) {
|
|
184
|
-
[ReasonTypeId] = ReasonTypeId;
|
|
185
|
-
get isRetryable() {
|
|
186
|
-
return true;
|
|
187
|
-
}
|
|
188
|
-
};
|
|
189
|
-
var SerializationError = class extends TaggedError("effect/sql/SqlError/SerializationError")("SerializationError", ReasonFields) {
|
|
190
|
-
[ReasonTypeId] = ReasonTypeId;
|
|
191
|
-
get isRetryable() {
|
|
192
|
-
return true;
|
|
193
|
-
}
|
|
194
|
-
};
|
|
195
|
-
var LockTimeoutError = class extends TaggedError("effect/sql/SqlError/LockTimeoutError")("LockTimeoutError", ReasonFields) {
|
|
196
|
-
[ReasonTypeId] = ReasonTypeId;
|
|
197
|
-
get isRetryable() {
|
|
198
|
-
return true;
|
|
199
|
-
}
|
|
200
|
-
};
|
|
201
|
-
var StatementTimeoutError = class extends TaggedError("effect/sql/SqlError/StatementTimeoutError")("StatementTimeoutError", ReasonFields) {
|
|
202
|
-
[ReasonTypeId] = ReasonTypeId;
|
|
203
|
-
get isRetryable() {
|
|
204
|
-
return true;
|
|
205
|
-
}
|
|
206
|
-
};
|
|
207
|
-
var UnknownError = class extends TaggedError("effect/sql/SqlError/UnknownError")("UnknownError", ReasonFields) {
|
|
208
|
-
[ReasonTypeId] = ReasonTypeId;
|
|
209
|
-
get isRetryable() {
|
|
210
|
-
return false;
|
|
211
|
-
}
|
|
212
|
-
};
|
|
213
|
-
const SqlErrorReason = Union$2([
|
|
214
|
-
ConnectionError,
|
|
215
|
-
AuthenticationError,
|
|
216
|
-
AuthorizationError,
|
|
217
|
-
SqlSyntaxError,
|
|
218
|
-
UniqueViolation,
|
|
219
|
-
ConstraintError,
|
|
220
|
-
DeadlockError,
|
|
221
|
-
SerializationError,
|
|
222
|
-
LockTimeoutError,
|
|
223
|
-
StatementTimeoutError,
|
|
224
|
-
UnknownError
|
|
225
|
-
]);
|
|
226
|
-
var SqlError = class extends TaggedError("effect/sql/SqlError")("SqlError", { reason: SqlErrorReason }) {
|
|
227
|
-
[TypeId$5] = TypeId$5;
|
|
228
|
-
cause = this.reason;
|
|
229
|
-
get message() {
|
|
230
|
-
return this.reason.message || this.reason._tag;
|
|
231
|
-
}
|
|
232
|
-
get isRetryable() {
|
|
233
|
-
return this.reason.isRetryable;
|
|
234
|
-
}
|
|
235
|
-
};
|
|
236
|
-
const sqliteCodeFromCause = (cause) => {
|
|
237
|
-
if (!hasProperty(cause, "code")) return;
|
|
238
|
-
const code = cause.code;
|
|
239
|
-
return typeof code === "string" || typeof code === "number" ? code : void 0;
|
|
240
|
-
};
|
|
241
|
-
const sqliteNumericCodeFromCause = (cause) => {
|
|
242
|
-
const code = sqliteCodeFromCause(cause);
|
|
243
|
-
if (typeof code === "number") return code;
|
|
244
|
-
if (!hasProperty(cause, "errno")) return;
|
|
245
|
-
const errno = cause.errno;
|
|
246
|
-
return typeof errno === "number" ? errno : void 0;
|
|
247
|
-
};
|
|
248
|
-
const matchesSqliteNumericCode = (cause, expected) => {
|
|
249
|
-
if (sqliteCodeFromCause(cause) === expected) return true;
|
|
250
|
-
if (!hasProperty(cause, "errno")) return false;
|
|
251
|
-
return cause.errno === expected;
|
|
252
|
-
};
|
|
253
|
-
const matchesSqliteCode = (code, expected) => code === expected || code.startsWith(expected + "_");
|
|
254
|
-
const UNKNOWN_CONSTRAINT = "unknown";
|
|
255
|
-
const SQLITE_CONSTRAINT_UNIQUE = "SQLITE_CONSTRAINT_UNIQUE";
|
|
256
|
-
const SQLITE_CONSTRAINT_UNIQUE_CODE = 2067;
|
|
257
|
-
const normalizeConstraintIdentifier = (identifier) => {
|
|
258
|
-
if (typeof identifier !== "string") return UNKNOWN_CONSTRAINT;
|
|
259
|
-
const trimmed = identifier.trim();
|
|
260
|
-
return trimmed.length === 0 ? UNKNOWN_CONSTRAINT : trimmed;
|
|
261
|
-
};
|
|
262
|
-
const sqliteUniqueConstraintFromCause = (cause) => {
|
|
263
|
-
if (hasProperty(cause, "constraint")) return normalizeConstraintIdentifier(cause.constraint);
|
|
264
|
-
if (!hasProperty(cause, "message")) return UNKNOWN_CONSTRAINT;
|
|
265
|
-
const message = cause.message;
|
|
266
|
-
if (typeof message !== "string") return UNKNOWN_CONSTRAINT;
|
|
267
|
-
const index = message.indexOf("UNIQUE constraint failed:");
|
|
268
|
-
return index === -1 ? UNKNOWN_CONSTRAINT : normalizeConstraintIdentifier(message.slice(index + 25));
|
|
269
|
-
};
|
|
270
|
-
const classifySqliteError = (cause, { message, operation } = {}) => {
|
|
271
|
-
const props = {
|
|
272
|
-
cause,
|
|
273
|
-
message,
|
|
274
|
-
operation
|
|
275
|
-
};
|
|
276
|
-
const code = sqliteCodeFromCause(cause);
|
|
277
|
-
const numericCode = sqliteNumericCodeFromCause(cause);
|
|
278
|
-
if (code === SQLITE_CONSTRAINT_UNIQUE || matchesSqliteNumericCode(cause, SQLITE_CONSTRAINT_UNIQUE_CODE)) return new UniqueViolation({
|
|
279
|
-
...props,
|
|
280
|
-
constraint: sqliteUniqueConstraintFromCause(cause)
|
|
281
|
-
});
|
|
282
|
-
if (typeof code === "string") {
|
|
283
|
-
if (matchesSqliteCode(code, "SQLITE_AUTH")) return new AuthenticationError(props);
|
|
284
|
-
if (matchesSqliteCode(code, "SQLITE_PERM")) return new AuthorizationError(props);
|
|
285
|
-
if (matchesSqliteCode(code, "SQLITE_CONSTRAINT")) return new ConstraintError(props);
|
|
286
|
-
if (matchesSqliteCode(code, "SQLITE_BUSY") || matchesSqliteCode(code, "SQLITE_LOCKED")) return new LockTimeoutError(props);
|
|
287
|
-
if (matchesSqliteCode(code, "SQLITE_CANTOPEN")) return new ConnectionError(props);
|
|
288
|
-
}
|
|
289
|
-
if (typeof numericCode === "number") switch (numericCode & 255) {
|
|
290
|
-
case 23: return new AuthenticationError(props);
|
|
291
|
-
case 3: return new AuthorizationError(props);
|
|
292
|
-
case 19: return new ConstraintError(props);
|
|
293
|
-
case 5:
|
|
294
|
-
case 6: return new LockTimeoutError(props);
|
|
295
|
-
case 14: return new ConnectionError(props);
|
|
296
|
-
default: return new UnknownError(props);
|
|
297
|
-
}
|
|
298
|
-
return new UnknownError(props);
|
|
299
|
-
};
|
|
300
|
-
var ResultLengthMismatch = class extends TaggedError("effect/sql/ResultLengthMismatch")("ResultLengthMismatch", {
|
|
301
|
-
expected: Natural,
|
|
302
|
-
actual: Natural
|
|
303
|
-
}) {
|
|
304
|
-
get message() {
|
|
305
|
-
return `Expected ${this.expected} results but got ${this.actual}`;
|
|
306
|
-
}
|
|
307
|
-
};
|
|
308
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/Statement.js
|
|
309
|
-
const FragmentTypeId = Symbol.for("~effect/sql/Statement/Fragment");
|
|
310
|
-
const SegmentTypeId = Symbol.for("~effect/sql/Statement/Segment");
|
|
311
|
-
const fragment = (segments) => ({
|
|
312
|
-
[FragmentTypeId]: FragmentTypeId,
|
|
313
|
-
segments
|
|
314
|
-
});
|
|
315
|
-
const CurrentTransformer = Reference("effect/sql/CurrentTransformer", { defaultValue: constUndefined });
|
|
316
|
-
const SpanPropagationEnabled = Reference("effect/sql/SpanPropagationEnabled", { defaultValue: () => false });
|
|
317
|
-
const isFragment = (u) => hasProperty(u, FragmentTypeId);
|
|
318
|
-
const literal = (value, params) => ({
|
|
319
|
-
[SegmentTypeId]: SegmentTypeId,
|
|
320
|
-
_tag: "Literal",
|
|
321
|
-
value,
|
|
322
|
-
params
|
|
323
|
-
});
|
|
324
|
-
const identifier = (value) => ({
|
|
325
|
-
[SegmentTypeId]: SegmentTypeId,
|
|
326
|
-
_tag: "Identifier",
|
|
327
|
-
value
|
|
328
|
-
});
|
|
329
|
-
const parameter = (value) => ({
|
|
330
|
-
[SegmentTypeId]: SegmentTypeId,
|
|
331
|
-
_tag: "Parameter",
|
|
332
|
-
value
|
|
333
|
-
});
|
|
334
|
-
const arrayHelper = (value) => ({
|
|
335
|
-
[SegmentTypeId]: SegmentTypeId,
|
|
336
|
-
_tag: "ArrayHelper",
|
|
337
|
-
value
|
|
338
|
-
});
|
|
339
|
-
const RecordInsertHelperProto = {
|
|
340
|
-
[SegmentTypeId]: SegmentTypeId,
|
|
341
|
-
_tag: "RecordInsertHelper",
|
|
342
|
-
returning(sql) {
|
|
343
|
-
const self = Object.create(Object.getPrototypeOf(this));
|
|
344
|
-
Object.assign(self, this, { returningIdentifier: typeof sql === "string" || isFragment(sql) ? sql : fragment([sql]) });
|
|
345
|
-
return self;
|
|
346
|
-
}
|
|
347
|
-
};
|
|
348
|
-
const recordInsertHelper = (value) => Object.assign(Object.create(RecordInsertHelperProto), {
|
|
349
|
-
value,
|
|
350
|
-
returningIdentifier: void 0
|
|
351
|
-
});
|
|
352
|
-
const RecordUpdateHelperProto = {
|
|
353
|
-
...RecordInsertHelperProto,
|
|
354
|
-
_tag: "RecordUpdateHelper"
|
|
355
|
-
};
|
|
356
|
-
const recordUpdateHelper = (value, alias) => Object.assign(Object.create(RecordUpdateHelperProto), {
|
|
357
|
-
value,
|
|
358
|
-
alias,
|
|
359
|
-
returningIdentifier: void 0
|
|
360
|
-
});
|
|
361
|
-
const RecordUpdateHelperSingleProto = {
|
|
362
|
-
...RecordInsertHelperProto,
|
|
363
|
-
_tag: "RecordUpdateHelperSingle"
|
|
364
|
-
};
|
|
365
|
-
const recordUpdateHelperSingle = (value, omit) => Object.assign(Object.create(RecordUpdateHelperSingleProto), {
|
|
366
|
-
value,
|
|
367
|
-
omit,
|
|
368
|
-
returningIdentifier: void 0
|
|
369
|
-
});
|
|
370
|
-
const make$5 = (acquirer, compiler, spanAttributes, transformRows, borrower) => {
|
|
371
|
-
const self = Object.assign(function sql(strings, ...args) {
|
|
372
|
-
if (typeof strings === "string") return identifier(strings);
|
|
373
|
-
else if (Array.isArray(strings) && "raw" in strings) return makeUnsafe$1(templateSegments(strings, args), acquirer, compiler, spanAttributes, transformRows, borrower, self);
|
|
374
|
-
throw "absurd";
|
|
375
|
-
}, {
|
|
376
|
-
unsafe(sql, params) {
|
|
377
|
-
return makeUnsafe$1([literal(sql, params)], acquirer, compiler, spanAttributes, transformRows, borrower, self);
|
|
378
|
-
},
|
|
379
|
-
literal(sql) {
|
|
380
|
-
return fragment([literal(sql)]);
|
|
381
|
-
},
|
|
382
|
-
in: in_,
|
|
383
|
-
insert(value) {
|
|
384
|
-
return recordInsertHelper(Array.isArray(value) ? value : [value]);
|
|
385
|
-
},
|
|
386
|
-
update(value, omit) {
|
|
387
|
-
return recordUpdateHelperSingle(value, omit ?? []);
|
|
388
|
-
},
|
|
389
|
-
updateValues(value, alias) {
|
|
390
|
-
return recordUpdateHelper(value, alias);
|
|
391
|
-
},
|
|
392
|
-
and,
|
|
393
|
-
or,
|
|
394
|
-
csv,
|
|
395
|
-
join,
|
|
396
|
-
onDialect(options) {
|
|
397
|
-
return options[compiler.dialect]();
|
|
398
|
-
},
|
|
399
|
-
onDialectOrElse(options) {
|
|
400
|
-
return options[compiler.dialect] !== void 0 ? options[compiler.dialect]() : options.orElse();
|
|
401
|
-
}
|
|
402
|
-
});
|
|
403
|
-
return self;
|
|
404
|
-
};
|
|
405
|
-
const templateSegments = (strings, args) => {
|
|
406
|
-
const segments = strings[0].length > 0 ? [literal(strings[0])] : [];
|
|
407
|
-
for (let i = 0; i < args.length; i++) {
|
|
408
|
-
const arg = args[i];
|
|
409
|
-
if (isFragment(arg)) segments.push(...arg.segments);
|
|
410
|
-
else if (isSegment(arg)) segments.push(arg);
|
|
411
|
-
else segments.push(parameter(arg));
|
|
412
|
-
if (strings[i + 1].length > 0) segments.push(literal(strings[i + 1]));
|
|
413
|
-
}
|
|
414
|
-
return segments;
|
|
415
|
-
};
|
|
416
|
-
function join(lit, addParens = true, fallback = "") {
|
|
417
|
-
const literalStatement = literal(lit);
|
|
418
|
-
const fallbackFragment = fragment([literal(fallback)]);
|
|
419
|
-
return (clauses) => {
|
|
420
|
-
if (clauses.length === 0) return fallbackFragment;
|
|
421
|
-
else if (clauses.length === 1) return fragment(convertLiteralOrFragment(clauses[0]));
|
|
422
|
-
const segments = [];
|
|
423
|
-
if (addParens) segments.push(literal("("));
|
|
424
|
-
segments.push.apply(segments, convertLiteralOrFragment(clauses[0]));
|
|
425
|
-
for (let i = 1; i < clauses.length; i++) {
|
|
426
|
-
segments.push(literalStatement);
|
|
427
|
-
segments.push.apply(segments, convertLiteralOrFragment(clauses[i]));
|
|
428
|
-
}
|
|
429
|
-
if (addParens) segments.push(literal(")"));
|
|
430
|
-
return fragment(segments);
|
|
431
|
-
};
|
|
432
|
-
}
|
|
433
|
-
const and = join(" AND ", true, "1=1");
|
|
434
|
-
const or = join(" OR ", true, "1=1");
|
|
435
|
-
const csv = function(...args) {
|
|
436
|
-
if (args[args.length - 1].length === 0) return emptyFragment;
|
|
437
|
-
if (args.length === 1) return csvRaw(args[0]);
|
|
438
|
-
return fragment([literal(`${args[0]} `), ...csvRaw(args[1]).segments]);
|
|
439
|
-
};
|
|
440
|
-
const csvRaw = join(",", false);
|
|
441
|
-
const emptyFragment = fragment([literal("")]);
|
|
442
|
-
const makeCompiler = (options) => {
|
|
443
|
-
const self = Object.create(CompilerProto);
|
|
444
|
-
self.options = options;
|
|
445
|
-
self.dialect = options.dialect;
|
|
446
|
-
self.disableTransforms = false;
|
|
447
|
-
self.statementCache = new WeakMap();
|
|
448
|
-
self.statementCacheNoTransform = new WeakMap();
|
|
449
|
-
return self;
|
|
450
|
-
};
|
|
451
|
-
const CompilerProto = {
|
|
452
|
-
compile(statement, withoutTransform = false, placeholderOverride) {
|
|
453
|
-
const opts = this.options;
|
|
454
|
-
withoutTransform = withoutTransform || this.disableTransforms;
|
|
455
|
-
const cache = withoutTransform ? this.statementCacheNoTransform : this.statementCache;
|
|
456
|
-
const cached = cache.get(statement);
|
|
457
|
-
if (cached !== void 0 && placeholderOverride === void 0) return cached;
|
|
458
|
-
const segments = statement.segments;
|
|
459
|
-
const len = segments.length;
|
|
460
|
-
let sql = "";
|
|
461
|
-
const binds = [];
|
|
462
|
-
let placeholderCount = 0;
|
|
463
|
-
const placeholder = placeholderOverride ?? ((u) => opts.placeholder(++placeholderCount, u));
|
|
464
|
-
const placeholderNoIncrement = (u) => opts.placeholder(placeholderCount, u);
|
|
465
|
-
const placeholders = makePlaceholdersArray(placeholder);
|
|
466
|
-
for (let i = 0; i < len; i++) {
|
|
467
|
-
const segment = segments[i];
|
|
468
|
-
switch (segment._tag) {
|
|
469
|
-
case "Literal":
|
|
470
|
-
sql += segment.value;
|
|
471
|
-
if (segment.params) binds.push.apply(binds, segment.params);
|
|
472
|
-
break;
|
|
473
|
-
case "Identifier":
|
|
474
|
-
sql += opts.onIdentifier(segment.value, withoutTransform);
|
|
475
|
-
break;
|
|
476
|
-
case "Parameter":
|
|
477
|
-
sql += placeholder(segment.value);
|
|
478
|
-
binds.push(segment.value);
|
|
479
|
-
break;
|
|
480
|
-
case "ArrayHelper":
|
|
481
|
-
if (segment.value.length === 0) {
|
|
482
|
-
const inKeyword = emptyInKeyword.exec(sql);
|
|
483
|
-
if (inKeyword === null || isInLineComment(sql, inKeyword.index)) sql += "()";
|
|
484
|
-
else if (this.dialect === "pg") sql = sql.slice(0, inKeyword.index) + (inKeyword[1] ? "<> ALL('{}')" : "= ANY('{}')");
|
|
485
|
-
else sql += "(SELECT NULL WHERE 1=0)";
|
|
486
|
-
break;
|
|
487
|
-
}
|
|
488
|
-
sql += `(${placeholders(segment.value)})`;
|
|
489
|
-
binds.push.apply(binds, segment.value);
|
|
490
|
-
break;
|
|
491
|
-
case "RecordInsertHelper": {
|
|
492
|
-
const keys = Object.keys(segment.value[0]);
|
|
493
|
-
if (opts.onInsert) {
|
|
494
|
-
const values = new Array(segment.value.length);
|
|
495
|
-
let placeholders = "";
|
|
496
|
-
for (let i = 0; i < segment.value.length; i++) {
|
|
497
|
-
const row = new Array(keys.length);
|
|
498
|
-
values[i] = row;
|
|
499
|
-
placeholders += i === 0 ? "(" : ",(";
|
|
500
|
-
for (let j = 0; j < keys.length; j++) {
|
|
501
|
-
const key = keys[j];
|
|
502
|
-
const value = segment.value[i][key];
|
|
503
|
-
const primitive = extractPrimitive(value, opts.onCustom, placeholderNoIncrement, withoutTransform);
|
|
504
|
-
row[j] = primitive;
|
|
505
|
-
placeholders += j === 0 ? placeholder(value) : `,${placeholder(value)}`;
|
|
506
|
-
}
|
|
507
|
-
placeholders += ")";
|
|
508
|
-
}
|
|
509
|
-
const [s, b] = opts.onInsert(keys.map((_) => opts.onIdentifier(_, withoutTransform)), placeholders, values, typeof segment.returningIdentifier === "string" ? [segment.returningIdentifier, []] : segment.returningIdentifier ? this.compile(segment.returningIdentifier, withoutTransform, placeholder) : void 0);
|
|
510
|
-
sql += s;
|
|
511
|
-
binds.push.apply(binds, b);
|
|
512
|
-
} else {
|
|
513
|
-
let placeholders = "";
|
|
514
|
-
for (let i = 0; i < segment.value.length; i++) {
|
|
515
|
-
placeholders += i === 0 ? "(" : ",(";
|
|
516
|
-
for (let j = 0; j < keys.length; j++) {
|
|
517
|
-
const value = segment.value[i][keys[j]];
|
|
518
|
-
const primitive = extractPrimitive(value, opts.onCustom, placeholderNoIncrement, withoutTransform);
|
|
519
|
-
binds.push(primitive);
|
|
520
|
-
placeholders += j === 0 ? placeholder(value) : `,${placeholder(value)}`;
|
|
521
|
-
}
|
|
522
|
-
placeholders += ")";
|
|
523
|
-
}
|
|
524
|
-
sql += `${generateColumns(keys, opts.onIdentifier, withoutTransform)} VALUES ${placeholders}`;
|
|
525
|
-
if (typeof segment.returningIdentifier === "string") sql += ` RETURNING ${segment.returningIdentifier}`;
|
|
526
|
-
else if (segment.returningIdentifier) {
|
|
527
|
-
sql += " RETURNING ";
|
|
528
|
-
const [s, b] = this.compile(segment.returningIdentifier, withoutTransform, placeholder);
|
|
529
|
-
sql += s;
|
|
530
|
-
binds.push.apply(binds, b);
|
|
531
|
-
}
|
|
532
|
-
}
|
|
533
|
-
break;
|
|
534
|
-
}
|
|
535
|
-
case "RecordUpdateHelperSingle": {
|
|
536
|
-
let keys = Object.keys(segment.value);
|
|
537
|
-
if (segment.omit.length > 0) keys = keys.filter((key) => !segment.omit.includes(key));
|
|
538
|
-
if (opts.onRecordUpdateSingle) {
|
|
539
|
-
const [s, b] = opts.onRecordUpdateSingle(keys.map((_) => opts.onIdentifier(_, withoutTransform)), keys.map((key) => extractPrimitive(segment.value[key], opts.onCustom, placeholderNoIncrement, withoutTransform)), typeof segment.returningIdentifier === "string" ? [segment.returningIdentifier, []] : segment.returningIdentifier ? this.compile(segment.returningIdentifier, withoutTransform, placeholder) : void 0);
|
|
540
|
-
sql += s;
|
|
541
|
-
binds.push.apply(binds, b);
|
|
542
|
-
} else {
|
|
543
|
-
for (let i = 0, len = keys.length; i < len; i++) {
|
|
544
|
-
const column = opts.onIdentifier(keys[i], withoutTransform);
|
|
545
|
-
if (i === 0) sql += `${column} = ${placeholder(segment.value[keys[i]])}`;
|
|
546
|
-
else sql += `, ${column} = ${placeholder(segment.value[keys[i]])}`;
|
|
547
|
-
binds.push(extractPrimitive(segment.value[keys[i]], opts.onCustom, placeholderNoIncrement, withoutTransform));
|
|
548
|
-
}
|
|
549
|
-
if (typeof segment.returningIdentifier === "string") {
|
|
550
|
-
if (this.dialect === "mssql") sql += ` OUTPUT ${segment.returningIdentifier === "*" ? "INSERTED.*" : segment.returningIdentifier}`;
|
|
551
|
-
else sql += ` RETURNING ${segment.returningIdentifier}`;
|
|
552
|
-
} else if (segment.returningIdentifier) {
|
|
553
|
-
sql += this.dialect === "mssql" ? " OUTPUT " : " RETURNING ";
|
|
554
|
-
const [s, b] = this.compile(segment.returningIdentifier, withoutTransform, placeholder);
|
|
555
|
-
sql += s;
|
|
556
|
-
binds.push.apply(binds, b);
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
break;
|
|
560
|
-
}
|
|
561
|
-
case "RecordUpdateHelper": {
|
|
562
|
-
const keys = Object.keys(segment.value[0]);
|
|
563
|
-
const values = new Array(segment.value.length);
|
|
564
|
-
let placeholders = "";
|
|
565
|
-
for (let i = 0; i < segment.value.length; i++) {
|
|
566
|
-
const row = new Array(keys.length);
|
|
567
|
-
values[i] = row;
|
|
568
|
-
placeholders += i === 0 ? "(" : ",(";
|
|
569
|
-
for (let j = 0; j < keys.length; j++) {
|
|
570
|
-
const key = keys[j];
|
|
571
|
-
const value = segment.value[i][key];
|
|
572
|
-
row[j] = extractPrimitive(value, opts.onCustom, placeholderNoIncrement, withoutTransform);
|
|
573
|
-
placeholders += j === 0 ? placeholder(value) : `,${placeholder(value)}`;
|
|
574
|
-
}
|
|
575
|
-
placeholders += ")";
|
|
576
|
-
}
|
|
577
|
-
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);
|
|
578
|
-
sql += s;
|
|
579
|
-
binds.push.apply(binds, b);
|
|
580
|
-
break;
|
|
581
|
-
}
|
|
582
|
-
case "Custom": {
|
|
583
|
-
const [s, b] = opts.onCustom(segment, placeholder, withoutTransform);
|
|
584
|
-
sql += s;
|
|
585
|
-
binds.push.apply(binds, b);
|
|
586
|
-
break;
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
}
|
|
590
|
-
const result = [sql, binds];
|
|
591
|
-
if (placeholderOverride !== void 0) return result;
|
|
592
|
-
cache.set(statement, result);
|
|
593
|
-
return result;
|
|
594
|
-
},
|
|
595
|
-
get withoutTransform() {
|
|
596
|
-
const self = Object.create(CompilerProto);
|
|
597
|
-
Object.assign(self, this, { disableTransforms: true });
|
|
598
|
-
return self;
|
|
599
|
-
}
|
|
600
|
-
};
|
|
601
|
-
const makeCompilerSqlite = (transform) => makeCompiler({
|
|
602
|
-
dialect: "sqlite",
|
|
603
|
-
placeholder(_) {
|
|
604
|
-
return "?";
|
|
605
|
-
},
|
|
606
|
-
onIdentifier: transform ? function(value, withoutTransform) {
|
|
607
|
-
return withoutTransform ? escapeSqlite(value) : escapeSqlite(transform(value));
|
|
608
|
-
} : escapeSqlite,
|
|
609
|
-
onRecordUpdate() {
|
|
610
|
-
return ["", []];
|
|
611
|
-
},
|
|
612
|
-
onCustom() {
|
|
613
|
-
return ["", []];
|
|
614
|
-
}
|
|
615
|
-
});
|
|
616
|
-
function defaultEscape(c) {
|
|
617
|
-
const re = new RegExp(c, "g");
|
|
618
|
-
const double = c + c;
|
|
619
|
-
const dot = c + "." + c;
|
|
620
|
-
return function(str) {
|
|
621
|
-
return c + str.replace(re, double).replace(/\./g, dot) + c;
|
|
622
|
-
};
|
|
623
|
-
}
|
|
624
|
-
const defaultTransforms = (transformer, nested = true) => {
|
|
625
|
-
const transformValue = (value) => {
|
|
626
|
-
if (Array.isArray(value)) {
|
|
627
|
-
if (value.length === 0 || value[0]?.constructor !== Object) return value;
|
|
628
|
-
return array(value);
|
|
629
|
-
} else if (value?.constructor === Object) return transformObject(value);
|
|
630
|
-
return value;
|
|
631
|
-
};
|
|
632
|
-
const transformObject = (obj) => {
|
|
633
|
-
const newObj = {};
|
|
634
|
-
for (const key of Object.keys(obj)) assignProperty(newObj, transformer(key), transformValue(obj[key]));
|
|
635
|
-
return newObj;
|
|
636
|
-
};
|
|
637
|
-
const transformArrayNested = (rows) => {
|
|
638
|
-
const newRows = new Array(rows.length);
|
|
639
|
-
for (let i = 0, len = rows.length; i < len; i++) {
|
|
640
|
-
const row = rows[i];
|
|
641
|
-
if (Array.isArray(row)) newRows[i] = transformArrayNested(row);
|
|
642
|
-
else if (row === null || typeof row !== "object") newRows[i] = row;
|
|
643
|
-
else {
|
|
644
|
-
const obj = {};
|
|
645
|
-
for (const [key, value] of Object.entries(row)) assignProperty(obj, transformer(key), transformValue(value));
|
|
646
|
-
newRows[i] = obj;
|
|
647
|
-
}
|
|
648
|
-
}
|
|
649
|
-
return newRows;
|
|
650
|
-
};
|
|
651
|
-
const transformArray = (rows) => {
|
|
652
|
-
const newRows = new Array(rows.length);
|
|
653
|
-
for (let i = 0, len = rows.length; i < len; i++) {
|
|
654
|
-
const row = rows[i];
|
|
655
|
-
if (Array.isArray(row)) newRows[i] = transformArray(row);
|
|
656
|
-
else if (row === null || typeof row !== "object") newRows[i] = row;
|
|
657
|
-
else {
|
|
658
|
-
const obj = {};
|
|
659
|
-
for (const [key, value] of Object.entries(row)) assignProperty(obj, transformer(key), value);
|
|
660
|
-
newRows[i] = obj;
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
return newRows;
|
|
664
|
-
};
|
|
665
|
-
const array = nested ? transformArrayNested : transformArray;
|
|
666
|
-
return {
|
|
667
|
-
value: transformValue,
|
|
668
|
-
object: transformObject,
|
|
669
|
-
array
|
|
670
|
-
};
|
|
671
|
-
};
|
|
672
|
-
const spanTarget = (spanAttributes) => {
|
|
673
|
-
const namespace = spanAttribute(spanAttributes, "db.namespace");
|
|
674
|
-
if (isNonEmptyString(namespace)) return namespace;
|
|
675
|
-
const address = spanAttribute(spanAttributes, "server.address");
|
|
676
|
-
if (isNonEmptyString(address)) {
|
|
677
|
-
const port = spanAttribute(spanAttributes, "server.port");
|
|
678
|
-
return port === void 0 ? address : `${address}:${port}`;
|
|
679
|
-
}
|
|
680
|
-
};
|
|
681
|
-
const spanName = (spanAttributes) => {
|
|
682
|
-
const target = spanTarget(spanAttributes);
|
|
683
|
-
if (target !== void 0) return target;
|
|
684
|
-
const system = spanAttribute(spanAttributes, "db.system.name");
|
|
685
|
-
return isNonEmptyString(system) ? system : "sql.execute";
|
|
686
|
-
};
|
|
687
|
-
const ATTR_DB_QUERY_TEXT = "db.query.text";
|
|
688
|
-
const ATTR_SQL_METHOD = "effect.sql.method";
|
|
689
|
-
const spanAttribute = (spanAttributes, key) => {
|
|
690
|
-
for (let i = spanAttributes.length - 1; i >= 0; i--) if (spanAttributes[i][0] === key) return spanAttributes[i][1];
|
|
691
|
-
};
|
|
692
|
-
const isNonEmptyString = (u) => typeof u === "string" && u.length > 0;
|
|
693
|
-
const makeUnsafe$1 = (segments, acquirer, compiler, spanAttributes, transformRows, borrower, sql) => {
|
|
694
|
-
const self = Object.create(StatementProto);
|
|
695
|
-
self.segments = segments;
|
|
696
|
-
self.acquirer = acquirer;
|
|
697
|
-
self.compiler = compiler;
|
|
698
|
-
self.spanAttributes = spanAttributes;
|
|
699
|
-
self.transformRows = transformRows;
|
|
700
|
-
self.borrower = borrower;
|
|
701
|
-
self.sql = sql;
|
|
702
|
-
return self;
|
|
703
|
-
};
|
|
704
|
-
const StatementProto = {
|
|
705
|
-
[FragmentTypeId]: FragmentTypeId,
|
|
706
|
-
withConnection(operation, f, withoutTransform = false) {
|
|
707
|
-
return useSpan(spanName(this.spanAttributes), { kind: "client" }, (span) => this.withConnectionSpan(operation, f, withoutTransform, span));
|
|
708
|
-
},
|
|
709
|
-
withConnectionSpan(operation, f, withoutTransform, span) {
|
|
710
|
-
return withStatement(this, span, (statement, fiber) => {
|
|
711
|
-
const [sql, params] = statement.compile(withoutTransform);
|
|
712
|
-
for (const [key, value] of this.spanAttributes) span.attribute(key, value);
|
|
713
|
-
span.attribute(ATTR_SQL_METHOD, operation);
|
|
714
|
-
span.attribute(ATTR_DB_QUERY_TEXT, sql);
|
|
715
|
-
const propagate = fiber.cache.tracerEnabled && fiber.getRef(SpanPropagationEnabled);
|
|
716
|
-
const clock = propagate ? waitClock(fiber) : void 0;
|
|
717
|
-
const run = clock === void 0 ? (connection) => f(connection, sql, params) : (connection) => suspend(() => {
|
|
718
|
-
recordConnectionWait(span, clock);
|
|
719
|
-
return f(connection, sql, params);
|
|
720
|
-
});
|
|
721
|
-
const execute = this.borrower === void 0 ? scoped(flatMap(this.acquirer, run)) : this.borrower(run);
|
|
722
|
-
return propagate ? provideService(execute, ParentSpan, span) : execute;
|
|
723
|
-
});
|
|
724
|
-
},
|
|
725
|
-
get withoutTransform() {
|
|
726
|
-
return this.withConnection("executeWithoutTransform", (connection, sql, params) => connection.execute(sql, params, void 0), true);
|
|
727
|
-
},
|
|
728
|
-
get raw() {
|
|
729
|
-
return this.withConnection("executeRaw", (connection, sql, params) => connection.executeRaw(sql, params), true);
|
|
730
|
-
},
|
|
731
|
-
get stream() {
|
|
732
|
-
const self = this;
|
|
733
|
-
return unwrap(flatMap(makeSpanScoped(spanName(self.spanAttributes), { kind: "client" }), (span) => withStatement(self, span, (statement, fiber) => {
|
|
734
|
-
const [sql, params] = statement.compile();
|
|
735
|
-
for (const [key, value] of self.spanAttributes) span.attribute(key, value);
|
|
736
|
-
span.attribute(ATTR_SQL_METHOD, "executeStream");
|
|
737
|
-
span.attribute(ATTR_DB_QUERY_TEXT, sql);
|
|
738
|
-
const propagate = fiber.cache.tracerEnabled && fiber.getRef(SpanPropagationEnabled);
|
|
739
|
-
const clock = propagate ? waitClock(fiber) : void 0;
|
|
740
|
-
const acquire = map(self.acquirer, (connection) => {
|
|
741
|
-
if (clock !== void 0) recordConnectionWait(span, clock);
|
|
742
|
-
return connection.executeStream(sql, params, self.transformRows);
|
|
743
|
-
});
|
|
744
|
-
return propagate ? succeed(provideService$1(unwrap(acquire), ParentSpan, span)) : acquire;
|
|
745
|
-
})));
|
|
746
|
-
},
|
|
747
|
-
get values() {
|
|
748
|
-
return this.withConnection("executeValues", (connection, sql, params) => connection.executeValues(sql, params));
|
|
749
|
-
},
|
|
750
|
-
get valuesUnprepared() {
|
|
751
|
-
return this.withConnection("executeValuesUnprepared", (connection, sql, params) => connection.executeValuesUnprepared(sql, params));
|
|
752
|
-
},
|
|
753
|
-
get unprepared() {
|
|
754
|
-
const self = this;
|
|
755
|
-
return self.withConnection("executeUnprepared", (connection, sql, params) => connection.executeUnprepared(sql, params, self.transformRows));
|
|
756
|
-
},
|
|
757
|
-
...Prototype({
|
|
758
|
-
label: "Statement",
|
|
759
|
-
evaluate(fiber) {
|
|
760
|
-
const span = makeSpanUnsafe(fiber, spanName(this.spanAttributes), { kind: "client" });
|
|
761
|
-
const clock = fiber.getRef(Clock);
|
|
762
|
-
const timingEnabled = fiber.getRef(TracerTimingEnabled$1);
|
|
763
|
-
return onExit(this.withConnectionSpan("execute", (connection, sql, params) => connection.execute(sql, params, this.transformRows), false, span), (exit) => endSpan(span, exit, clock, timingEnabled));
|
|
764
|
-
}
|
|
765
|
-
}),
|
|
766
|
-
compile(withoutTransform) {
|
|
767
|
-
return this.compiler.compile(this, withoutTransform ?? false);
|
|
768
|
-
},
|
|
769
|
-
toJSON() {
|
|
770
|
-
const [sql, params] = this.compile();
|
|
771
|
-
return {
|
|
772
|
-
_id: "Statement",
|
|
773
|
-
segments: this.segments,
|
|
774
|
-
sql,
|
|
775
|
-
params
|
|
776
|
-
};
|
|
777
|
-
}
|
|
778
|
-
};
|
|
779
|
-
const withStatement = (self, span, f) => withFiber((fiber) => {
|
|
780
|
-
const transform = fiber.getRef(CurrentTransformer);
|
|
781
|
-
if (transform === void 0) return f(self, fiber);
|
|
782
|
-
return flatMap(transform(self, self.sql ?? make$5(self.acquirer, self.compiler, self.spanAttributes, self.transformRows, self.borrower), fiber, span), (statement) => f(statement, fiber));
|
|
783
|
-
});
|
|
784
|
-
const isSegment = (u) => hasProperty(u, SegmentTypeId);
|
|
785
|
-
function convertLiteralOrFragment(clause) {
|
|
786
|
-
if (typeof clause === "string") return [literal(clause)];
|
|
787
|
-
return clause.segments;
|
|
788
|
-
}
|
|
789
|
-
const makePlaceholdersArray = (evaluate) => (values) => {
|
|
790
|
-
if (values.length === 0) return "";
|
|
791
|
-
let result = evaluate(values[0]);
|
|
792
|
-
for (let i = 1; i < values.length; i++) result += `,${evaluate(values[i])}`;
|
|
793
|
-
return result;
|
|
794
|
-
};
|
|
795
|
-
const generateColumns = (keys, escape, withoutTransform) => {
|
|
796
|
-
if (keys.length === 0) return "()";
|
|
797
|
-
let str = `(${escape(keys[0], withoutTransform)}`;
|
|
798
|
-
for (let i = 1; i < keys.length; i++) str += `,${escape(keys[i], withoutTransform)}`;
|
|
799
|
-
return str + ")";
|
|
800
|
-
};
|
|
801
|
-
const extractPrimitive = (value, onCustom, placeholder, withoutTransform) => {
|
|
802
|
-
if (value === void 0) return null;
|
|
803
|
-
else if (isFragment(value)) {
|
|
804
|
-
const head = value.segments[0];
|
|
805
|
-
if (head._tag === "Custom") return onCustom(head, placeholder, withoutTransform)[1][0] ?? null;
|
|
806
|
-
else if (head._tag === "Parameter") return head.value;
|
|
807
|
-
return null;
|
|
808
|
-
}
|
|
809
|
-
return value;
|
|
810
|
-
};
|
|
811
|
-
const escapeSqlite = defaultEscape("\"");
|
|
812
|
-
function in_() {
|
|
813
|
-
if (arguments.length === 1) return arrayHelper(arguments[0]);
|
|
814
|
-
const column = arguments[0];
|
|
815
|
-
const values = arguments[1];
|
|
816
|
-
return values.length === 0 ? neverFragment : fragment([
|
|
817
|
-
identifier(column),
|
|
818
|
-
literal(" IN "),
|
|
819
|
-
arrayHelper(values)
|
|
820
|
-
]);
|
|
821
|
-
}
|
|
822
|
-
const neverFragment = fragment([literal("1=0")]);
|
|
823
|
-
const emptyInKeyword = /\b(NOT\s+)?IN\s*$/i;
|
|
824
|
-
const isInLineComment = (sql, index) => sql.lastIndexOf("--", index) > sql.lastIndexOf("\n", index);
|
|
825
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/SqlClient.js
|
|
826
|
-
const TypeId$4 = "~effect/sql/SqlClient";
|
|
827
|
-
const SqlClient = Service("effect/sql/SqlClient");
|
|
828
|
-
let clientIdCounter = 0;
|
|
829
|
-
let transactionSemaphoreIdCounter = 0;
|
|
830
|
-
const ATTR_DB_OPERATION_NAME = "db.operation.name";
|
|
831
|
-
const make$4 = fnUntraced(function* (options) {
|
|
832
|
-
const transactionService = options.transactionService ?? TransactionConnection(clientIdCounter++);
|
|
833
|
-
const getConnection = flatMap(serviceOption(transactionService), match({
|
|
834
|
-
onNone: () => options.acquirer,
|
|
835
|
-
onSome: activeTransactionConnection
|
|
836
|
-
}));
|
|
837
|
-
const beginTransaction = options.beginTransaction ?? "BEGIN";
|
|
838
|
-
const commit = options.commit ?? "COMMIT";
|
|
839
|
-
const savepoint = options.savepoint ?? ((name) => `SAVEPOINT ${name}`);
|
|
840
|
-
const releaseSavepoint = options.releaseSavepoint;
|
|
841
|
-
const rollback = options.rollback ?? "ROLLBACK";
|
|
842
|
-
const rollbackSavepoint = options.rollbackSavepoint ?? ((name) => `ROLLBACK TO SAVEPOINT ${name}`);
|
|
843
|
-
const transactionAcquirer = options.transactionAcquirer ?? options.acquirer;
|
|
844
|
-
const unprepared = (conn, sql) => conn.executeUnprepared(sql, [], void 0);
|
|
845
|
-
const control = options.prepareTransactionControls === true ? (conn, sql) => conn.execute(sql, [], void 0) : unprepared;
|
|
846
|
-
const isTransaction = options.isTransaction;
|
|
847
|
-
const cleanup = isTransaction ? (conn, sql) => isTransaction(conn) ? unprepared(conn, sql) : void_$1 : unprepared;
|
|
848
|
-
const withTransaction = makeWithTransaction({
|
|
849
|
-
transactionService,
|
|
850
|
-
spanAttributes: options.spanAttributes,
|
|
851
|
-
acquireConnection: (restore) => restore(transactionAcquirer),
|
|
852
|
-
begin: options.begin ?? ((conn, statement) => statement === void 0 ? control(conn, beginTransaction) : unprepared(conn, statement)),
|
|
853
|
-
savepoint: (conn, id) => control(conn, savepoint(`effect_sql_${id}`)),
|
|
854
|
-
releaseSavepoint: releaseSavepoint ? (conn, id) => cleanup(conn, releaseSavepoint(`effect_sql_${id}`)) : void 0,
|
|
855
|
-
commit: typeof commit === "string" ? (conn) => control(conn, commit) : commit,
|
|
856
|
-
onCommitFailure: options.onCommitFailure,
|
|
857
|
-
rollback: (conn) => cleanup(conn, rollback),
|
|
858
|
-
rollbackSavepoint: (conn, id) => cleanup(conn, rollbackSavepoint(`effect_sql_${id}`))
|
|
859
|
-
});
|
|
860
|
-
const afterCommit = makeAfterCommit(transactionService);
|
|
861
|
-
const reactivity = yield* Reactivity;
|
|
862
|
-
const borrower = options.borrower === void 0 ? void 0 : (f) => flatMap(serviceOption(transactionService), match({
|
|
863
|
-
onNone: () => options.borrower(f),
|
|
864
|
-
onSome: (transaction) => flatMap(activeTransactionConnection(transaction), f)
|
|
865
|
-
}));
|
|
866
|
-
const client = Object.assign(make$5(getConnection, options.compiler, options.spanAttributes, options.transformRows, borrower), {
|
|
867
|
-
[TypeId$4]: TypeId$4,
|
|
868
|
-
safe: void 0,
|
|
869
|
-
withTransaction,
|
|
870
|
-
transactionService,
|
|
871
|
-
afterCommit,
|
|
872
|
-
reserve: transactionAcquirer,
|
|
873
|
-
driver: options.driver,
|
|
874
|
-
withoutTransforms() {
|
|
875
|
-
const statement = make$5(getConnection, options.compiler.withoutTransform, options.spanAttributes, void 0, borrower);
|
|
876
|
-
const client = Object.assign(statement, {
|
|
877
|
-
...this,
|
|
878
|
-
...statement
|
|
879
|
-
});
|
|
880
|
-
client.safe = client;
|
|
881
|
-
client.withoutTransforms = () => client;
|
|
882
|
-
return client;
|
|
883
|
-
},
|
|
884
|
-
reactive: options.reactiveQueue ? (keys, effect) => options.reactiveQueue(keys, effect).pipe(map(fromQueue), unwrap) : reactivity.stream,
|
|
885
|
-
reactiveMailbox: options.reactiveQueue ?? reactivity.query
|
|
886
|
-
});
|
|
887
|
-
client.safe = client;
|
|
888
|
-
return client;
|
|
889
|
-
});
|
|
890
|
-
const makeSqliteAcquirers = (options) => {
|
|
891
|
-
const { isTransaction, semaphore } = options;
|
|
892
|
-
let poisoned;
|
|
893
|
-
const poison = (cause) => poisoned = new SqlError({ reason: new ConnectionError({
|
|
894
|
-
message: "SQLite connection cannot be reused after failed COMMIT cleanup",
|
|
895
|
-
operation: "rollback",
|
|
896
|
-
cause
|
|
897
|
-
}) });
|
|
898
|
-
const rollback = (conn) => {
|
|
899
|
-
if (isTransaction) return isTransaction(conn) ? asVoid(conn.executeUnprepared("ROLLBACK", [], void 0)) : void_$1;
|
|
900
|
-
return conn.executeUnprepared("ROLLBACK", [], void 0).pipe(asVoid, catchIf(isNoTransactionError, () => void_$1));
|
|
901
|
-
};
|
|
902
|
-
const available = flatMap(options.connection, (conn) => {
|
|
903
|
-
if (poisoned === void 0) return succeed(conn);
|
|
904
|
-
return matchCauseEffect(rollback(conn), {
|
|
905
|
-
onFailure: (cause) => fail(poison(cause)),
|
|
906
|
-
onSuccess: () => {
|
|
907
|
-
poisoned = void 0;
|
|
908
|
-
return succeed(conn);
|
|
909
|
-
}
|
|
910
|
-
});
|
|
911
|
-
});
|
|
912
|
-
const lease = uninterruptibleMask((restore) => andThen(restore(semaphore.takeScoped(1)), available));
|
|
913
|
-
return {
|
|
914
|
-
acquirer: lease,
|
|
915
|
-
borrower: (f) => semaphore.withPermit(flatMap(available, f)),
|
|
916
|
-
transactionAcquirer: lease,
|
|
917
|
-
onCommitFailure: (conn) => tapCause(rollback(conn), (cause) => sync(() => poison(cause))),
|
|
918
|
-
isTransaction: isTransaction && ((conn) => isTransaction(conn))
|
|
919
|
-
};
|
|
920
|
-
};
|
|
921
|
-
const isNoTransactionError = (error) => {
|
|
922
|
-
const cause = error.reason.cause;
|
|
923
|
-
const message = typeof cause === "string" ? cause : hasProperty(cause, "message") && typeof cause.message === "string" ? cause.message : "";
|
|
924
|
-
return /no transaction is active/i.test(message);
|
|
925
|
-
};
|
|
926
|
-
const failuresToDefects = (cause) => fromReasons(cause.reasons.map((reason) => isFailReason(reason) ? makeDieReason(reason.error).annotate(reasonAnnotations(reason)) : reason));
|
|
927
|
-
const afterCommitBuffers = new WeakMap();
|
|
928
|
-
const hasEnded = (buffer) => {
|
|
929
|
-
for (; buffer !== void 0; buffer = buffer.parent) if (!buffer.open) return true;
|
|
930
|
-
return false;
|
|
931
|
-
};
|
|
932
|
-
const transactionEnded = suspend(() => fail(new SqlError({ reason: new UnknownError({
|
|
933
|
-
cause: void 0,
|
|
934
|
-
message: "SqlClient: the transaction has already ended"
|
|
935
|
-
}) })));
|
|
936
|
-
const activeTransactionConnection = (transaction) => hasEnded(afterCommitBuffers.get(transaction)) ? transactionEnded : succeed(transaction[0]);
|
|
937
|
-
const runAfterCommit = (effect) => ignoreCause(effect, {
|
|
938
|
-
log: "Unhandled",
|
|
939
|
-
message: "Unhandled error in SqlClient.afterCommit callback"
|
|
940
|
-
});
|
|
941
|
-
const makeAfterCommit = (transactionService) => (effect) => withFiber((fiber) => {
|
|
942
|
-
const transaction = getOrUndefined(fiber.context, transactionService);
|
|
943
|
-
const buffer = transaction && afterCommitBuffers.get(transaction);
|
|
944
|
-
if (buffer === void 0) return runAfterCommit(effect);
|
|
945
|
-
if (hasEnded(buffer)) return die(new Error("SqlClient.afterCommit: the transaction has already ended"));
|
|
946
|
-
buffer.callbacks.push(provideContext(effect, omit(transactionService)(fiber.context)));
|
|
947
|
-
return void_$1;
|
|
948
|
-
});
|
|
949
|
-
const makeWithTransaction = (options) => {
|
|
950
|
-
const transactionSemaphore = Service(`effect/sql/SqlClient/TransactionSemaphore/${transactionSemaphoreIdCounter++}`);
|
|
951
|
-
const afterCommit = makeAfterCommit(options.transactionService);
|
|
952
|
-
const target = spanTarget(options.spanAttributes);
|
|
953
|
-
const deferInvalidations = (reactivity) => {
|
|
954
|
-
const invalidate = (keys) => afterCommit(sync(() => reactivity.invalidateUnsafe(keys)));
|
|
955
|
-
return {
|
|
956
|
-
...reactivity,
|
|
957
|
-
invalidate,
|
|
958
|
-
mutation: (keys, effect) => tap(effect, invalidate(keys))
|
|
959
|
-
};
|
|
960
|
-
};
|
|
961
|
-
return (effect) => uninterruptibleMask((restore) => useSpan("sql.transaction", { kind: "internal" }, (span) => withFiber((fiber) => {
|
|
962
|
-
for (const [key, value] of options.spanAttributes) span.attribute(key, value);
|
|
963
|
-
const services = fiber.context;
|
|
964
|
-
const reactivity = getOrUndefined(services, Reactivity);
|
|
965
|
-
const waitedClock = fiber.cache.tracerEnabled && fiber.getRef(SpanPropagationEnabled) ? waitClock(fiber) : void 0;
|
|
966
|
-
const control = (operation, effect) => useSpan(target === void 0 ? operation : `${operation} ${target}`, {
|
|
967
|
-
kind: "client",
|
|
968
|
-
parent: span
|
|
969
|
-
}, (controlSpan) => {
|
|
970
|
-
for (const [key, value] of options.spanAttributes) controlSpan.attribute(key, value);
|
|
971
|
-
controlSpan.attribute(ATTR_DB_OPERATION_NAME, operation);
|
|
972
|
-
return effect;
|
|
973
|
-
});
|
|
974
|
-
const connOption = getOption(services, options.transactionService);
|
|
975
|
-
const conn = connOption._tag === "Some" ? map(suspend(() => activeTransactionConnection(connOption.value)), (conn) => [void 0, conn]) : flatMap(make$7(), (scope) => provide(options.acquireConnection(restore), scope).pipe(provideService(ParentSpan, span), map((conn) => {
|
|
976
|
-
if (waitedClock !== void 0) recordConnectionWait(span, waitedClock);
|
|
977
|
-
return [scope, conn];
|
|
978
|
-
}), onError((cause) => close(scope, failCause(cause)))));
|
|
979
|
-
const id = connOption._tag === "Some" ? connOption.value[1] + 1 : 0;
|
|
980
|
-
const buffer = {
|
|
981
|
-
callbacks: [],
|
|
982
|
-
parent: connOption._tag === "Some" ? afterCommitBuffers.get(connOption.value) : void 0,
|
|
983
|
-
open: true
|
|
984
|
-
};
|
|
985
|
-
let committed = false;
|
|
986
|
-
const start = (conn) => id === 0 ? control("BEGIN", options.begin(conn, fiber.getRef(BeginTransaction))) : control("SAVEPOINT", options.savepoint(conn, id));
|
|
987
|
-
const transaction = flatMap(conn, ([scope, conn]) => start(conn).pipe(flatMap(() => {
|
|
988
|
-
const level = [conn, id];
|
|
989
|
-
afterCommitBuffers.set(level, buffer);
|
|
990
|
-
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) => {
|
|
991
|
-
buffer.open = false;
|
|
992
|
-
if (hasEnded(buffer.parent)) return isSuccess(exit) ? transactionEnded : exit;
|
|
993
|
-
let effect;
|
|
994
|
-
if (isSuccess(exit)) {
|
|
995
|
-
if (id === 0) {
|
|
996
|
-
const onCommitFailure = options.onCommitFailure;
|
|
997
|
-
const commit = control("COMMIT", options.commit(conn));
|
|
998
|
-
effect = onCommitFailure ? catchCause(commit, (commitCause) => matchCauseEffect(control("ROLLBACK", onCommitFailure(conn)), {
|
|
999
|
-
onFailure: (cleanupCause) => failCause$1(failuresToDefects(combine(commitCause, cleanupCause))),
|
|
1000
|
-
onSuccess: () => failCause$1(commitCause)
|
|
1001
|
-
})) : commit;
|
|
1002
|
-
} else effect = void_$1;
|
|
1003
|
-
} else effect = orDie(id > 0 ? control("ROLLBACK TO SAVEPOINT", options.rollbackSavepoint(conn, id)) : control("ROLLBACK", options.rollback(conn)));
|
|
1004
|
-
if (id > 0 && options.releaseSavepoint) {
|
|
1005
|
-
const release = orDie(control("RELEASE SAVEPOINT", options.releaseSavepoint(conn, id)));
|
|
1006
|
-
effect = flatMap(effect, () => hasEnded(buffer.parent) ? void_$1 : release);
|
|
1007
|
-
}
|
|
1008
|
-
return flatMap(effect, () => {
|
|
1009
|
-
committed = isSuccess(exit);
|
|
1010
|
-
return exit;
|
|
1011
|
-
});
|
|
1012
|
-
}, true);
|
|
1013
|
-
}), scope ? (eff) => onExitPrimitive(eff, (exit) => close(scope, exit), true) : identity));
|
|
1014
|
-
const settled = onExitPrimitive(transaction, () => {
|
|
1015
|
-
if (!committed || buffer.callbacks.length === 0) return;
|
|
1016
|
-
if (buffer.parent !== void 0) {
|
|
1017
|
-
buffer.parent.callbacks.push(...buffer.callbacks);
|
|
1018
|
-
return;
|
|
1019
|
-
}
|
|
1020
|
-
return forEach(buffer.callbacks, runAfterCommit, { discard: true });
|
|
1021
|
-
}, true);
|
|
1022
|
-
return id === 0 ? settled : restore(getUnsafe(services, transactionSemaphore).withPermit(uninterruptible(settled)));
|
|
1023
|
-
})));
|
|
1024
|
-
};
|
|
1025
|
-
const TransactionConnection = (clientId) => Service(`effect/sql/SqlClient/TransactionConnection/${clientId}`);
|
|
1026
|
-
const SafeIntegers = Reference("effect/sql/SqlClient/SafeIntegers", { defaultValue: () => false });
|
|
1027
|
-
const BeginTransaction = Reference("effect/sql/SqlClient/BeginTransaction", { defaultValue: () => void 0 });
|
|
1028
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/Cache.js
|
|
1029
|
-
const TypeId$3 = "~effect/Cache";
|
|
1030
|
-
const makeWith = (lookup, options) => contextWith$1((context) => {
|
|
1031
|
-
const self = Object.create(Proto$1);
|
|
1032
|
-
self.lookup = (key) => updateContext(lookup(key), (input) => merge(context, input));
|
|
1033
|
-
self.map = make$8();
|
|
1034
|
-
self.capacity = options.capacity;
|
|
1035
|
-
self.timeToLive = options.timeToLive ? (exit, key) => fromInputUnsafe(options.timeToLive(exit, key)) : defaultTimeToLive;
|
|
1036
|
-
return succeed$1(self);
|
|
1037
|
-
});
|
|
1038
|
-
const Proto$1 = {
|
|
1039
|
-
...PipeInspectableProto,
|
|
1040
|
-
[TypeId$3]: TypeId$3,
|
|
1041
|
-
toJSON() {
|
|
1042
|
-
return {
|
|
1043
|
-
_id: "Cache",
|
|
1044
|
-
capacity: this.capacity,
|
|
1045
|
-
map: this.map
|
|
1046
|
-
};
|
|
1047
|
-
}
|
|
1048
|
-
};
|
|
1049
|
-
const defaultTimeToLive = (_, _key) => infinity;
|
|
1050
|
-
const get = dual(2, (self, key) => withFiber$1((fiber) => {
|
|
1051
|
-
const oentry = get$2(self.map, key);
|
|
1052
|
-
if (isSome(oentry)) {
|
|
1053
|
-
remove(self.map, key);
|
|
1054
|
-
if (!hasExpired(oentry.value, fiber)) {
|
|
1055
|
-
set(self.map, key, oentry.value);
|
|
1056
|
-
return oentry.value.await(fiber);
|
|
1057
|
-
}
|
|
1058
|
-
}
|
|
1059
|
-
const entry = new EntryImpl(fiber, self.lookup(key));
|
|
1060
|
-
entry.onInterrupt = () => removeEntry(self, key, entry);
|
|
1061
|
-
let skipCache = false;
|
|
1062
|
-
entry.fiber.addObserver((exit) => {
|
|
1063
|
-
entry.onInterrupt = void 0;
|
|
1064
|
-
if (exitHasInterrupts(exit)) {
|
|
1065
|
-
removeEntry(self, key, entry);
|
|
1066
|
-
return;
|
|
1067
|
-
}
|
|
1068
|
-
const ttl = self.timeToLive(exit, key);
|
|
1069
|
-
if (isZero(ttl)) {
|
|
1070
|
-
skipCache = true;
|
|
1071
|
-
removeEntry(self, key, entry);
|
|
1072
|
-
} else if (isFinite(ttl)) entry.expiresAt = fiber.getRef(ClockRef).currentTimeMillisUnsafe() + toMillis(ttl);
|
|
1073
|
-
});
|
|
1074
|
-
const exit = entry.fiber.pollUnsafe();
|
|
1075
|
-
if (!skipCache && (exit === void 0 || !exitHasInterrupts(exit))) set(self.map, key, entry);
|
|
1076
|
-
if (Number.isFinite(self.capacity)) checkCapacity(self);
|
|
1077
|
-
return entry.await(fiber);
|
|
1078
|
-
}));
|
|
1079
|
-
var EntryImpl = class {
|
|
1080
|
-
expiresAt;
|
|
1081
|
-
awaiters;
|
|
1082
|
-
fiber;
|
|
1083
|
-
onInterrupt;
|
|
1084
|
-
constructor(parent, valueEffect) {
|
|
1085
|
-
this.fiber = forkUnsafe(parent, valueEffect, true, true);
|
|
1086
|
-
this.awaiters = 0;
|
|
1087
|
-
this.expiresAt = void 0;
|
|
1088
|
-
}
|
|
1089
|
-
await(fiber) {
|
|
1090
|
-
if (fiber === void 0) return withFiber$1((fiber) => this.await(fiber));
|
|
1091
|
-
const exit = this.fiber.pollUnsafe();
|
|
1092
|
-
if (exit) return exit;
|
|
1093
|
-
this.awaiters++;
|
|
1094
|
-
onExitUnsafe(fiber, () => {
|
|
1095
|
-
this.awaiters--;
|
|
1096
|
-
if (this.awaiters > 0 || this.fiber.pollUnsafe()) return void_$2;
|
|
1097
|
-
this.onInterrupt?.();
|
|
1098
|
-
return fiberInterrupt(this.fiber);
|
|
1099
|
-
});
|
|
1100
|
-
return fiberJoin(this.fiber);
|
|
1101
|
-
}
|
|
1102
|
-
};
|
|
1103
|
-
const removeEntry = (self, key, entry) => {
|
|
1104
|
-
const current = get$2(self.map, key);
|
|
1105
|
-
if (isSome(current) && current.value === entry) remove(self.map, key);
|
|
1106
|
-
};
|
|
1107
|
-
const hasExpired = (entry, fiber) => {
|
|
1108
|
-
if (entry.expiresAt === void 0) return false;
|
|
1109
|
-
return fiber.getRef(ClockRef).currentTimeMillisUnsafe() >= entry.expiresAt;
|
|
1110
|
-
};
|
|
1111
|
-
const checkCapacity = (self) => {
|
|
1112
|
-
let diff = size(self.map) - self.capacity;
|
|
1113
|
-
if (diff <= 0) return;
|
|
1114
|
-
for (const [key] of self.map) {
|
|
1115
|
-
remove(self.map, key);
|
|
1116
|
-
diff--;
|
|
1117
|
-
if (diff === 0) return;
|
|
1118
|
-
}
|
|
1119
|
-
};
|
|
1120
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/schema/VariantSchema.js
|
|
1121
|
-
const TypeId$2 = "~effect/schema/VariantSchema";
|
|
1122
|
-
const cacheSymbol = Symbol.for(`${TypeId$2}/cache`);
|
|
1123
|
-
const defaultCacheSymbol = Symbol.for(`${TypeId$2}/defaultCache`);
|
|
1124
|
-
const isStruct = (u) => hasProperty(u, TypeId$2);
|
|
1125
|
-
const FieldTypeId = "~effect/schema/VariantSchema/Field";
|
|
1126
|
-
const isField = (u) => hasProperty(u, FieldTypeId);
|
|
1127
|
-
const extract$1 = dual((args) => isStruct(args[0]), (self, variant, options) => {
|
|
1128
|
-
if (options?.isDefault === true && isSchema(self)) return self;
|
|
1129
|
-
const cacheKey = options?.isDefault === true ? defaultCacheSymbol : cacheSymbol;
|
|
1130
|
-
const cache = Object.hasOwn(self, cacheKey) ? self[cacheKey] : self[cacheKey] = Object.create(null);
|
|
1131
|
-
if (Object.hasOwn(cache, variant)) return cache[variant];
|
|
1132
|
-
const fields = {};
|
|
1133
|
-
for (const key of Object.keys(self[TypeId$2])) {
|
|
1134
|
-
const value = self[TypeId$2][key];
|
|
1135
|
-
if (value === void 0) continue;
|
|
1136
|
-
if ("~effect/schema/VariantSchema" in value) {
|
|
1137
|
-
if (options?.isDefault === true && isSchema(value)) assignProperty(fields, key, value);
|
|
1138
|
-
else assignProperty(fields, key, extract$1(value, variant));
|
|
1139
|
-
} else if (FieldTypeId in value) {
|
|
1140
|
-
if (Object.hasOwn(value.schemas, variant)) {
|
|
1141
|
-
const schema = value.schemas[variant];
|
|
1142
|
-
if (schema !== void 0) assignProperty(fields, key, schema);
|
|
1143
|
-
}
|
|
1144
|
-
} else assignProperty(fields, key, value);
|
|
1145
|
-
}
|
|
1146
|
-
const schema = Struct$2(fields);
|
|
1147
|
-
cache[variant] = schema;
|
|
1148
|
-
return schema;
|
|
1149
|
-
});
|
|
1150
|
-
const make$3 = (options) => {
|
|
1151
|
-
function Class(identifier) {
|
|
1152
|
-
return function(fields, annotations) {
|
|
1153
|
-
return makeClass(fields, (defaultFields) => Class$1(identifier)(defaultFields, annotations));
|
|
1154
|
-
};
|
|
1155
|
-
}
|
|
1156
|
-
function makeClass(fields, makeSchemaClass) {
|
|
1157
|
-
const struct = Struct$1(fields);
|
|
1158
|
-
const SchemaClass = makeSchemaClass(extract$1(struct, options.defaultVariant, { isDefault: true }).fields);
|
|
1159
|
-
class Base extends SchemaClass {
|
|
1160
|
-
static [TypeId$2] = fields;
|
|
1161
|
-
static extend(identifier) {
|
|
1162
|
-
const extend = super.extend(identifier);
|
|
1163
|
-
return (extension, annotations) => isSchema(extension) ? makeClass({
|
|
1164
|
-
...fields,
|
|
1165
|
-
...extension.fields
|
|
1166
|
-
}, () => extend(extension, annotations)) : makeClass({
|
|
1167
|
-
...fields,
|
|
1168
|
-
...extension
|
|
1169
|
-
}, (defaultFields) => extend(defaultFields, annotations));
|
|
1170
|
-
}
|
|
1171
|
-
}
|
|
1172
|
-
for (const variant of options.variants) Object.defineProperty(Base, variant, { value: extract$1(struct, variant).annotate({
|
|
1173
|
-
id: `${SchemaClass.identifier}.${variant}`,
|
|
1174
|
-
title: `${SchemaClass.identifier}.${variant}`
|
|
1175
|
-
}) });
|
|
1176
|
-
return Base;
|
|
1177
|
-
}
|
|
1178
|
-
function FieldOnly(keys) {
|
|
1179
|
-
return function(schema) {
|
|
1180
|
-
const obj = {};
|
|
1181
|
-
for (const key of keys) assignProperty(obj, key, schema);
|
|
1182
|
-
return Field$1(obj);
|
|
1183
|
-
};
|
|
1184
|
-
}
|
|
1185
|
-
function FieldExcept(keys) {
|
|
1186
|
-
return function(schema) {
|
|
1187
|
-
const obj = {};
|
|
1188
|
-
for (const variant of options.variants) if (!keys.includes(variant)) assignProperty(obj, variant, schema);
|
|
1189
|
-
return Field$1(obj);
|
|
1190
|
-
};
|
|
1191
|
-
}
|
|
1192
|
-
function UnionVariants(members) {
|
|
1193
|
-
return Union$1(members, options.defaultVariant, options.variants);
|
|
1194
|
-
}
|
|
1195
|
-
const fieldEvolve = dual(2, (self, f) => {
|
|
1196
|
-
const field = isField(self) ? self : Field$1(Object.fromEntries(options.variants.map((variant) => [variant, self])));
|
|
1197
|
-
return Field$1(evolve(field.schemas, f));
|
|
1198
|
-
});
|
|
1199
|
-
const extractVariants = dual(2, (self, variant) => extract$1(self, variant, { isDefault: variant === options.defaultVariant }));
|
|
1200
|
-
return {
|
|
1201
|
-
Struct: Struct$1,
|
|
1202
|
-
Field: Field$1,
|
|
1203
|
-
FieldOnly,
|
|
1204
|
-
FieldExcept,
|
|
1205
|
-
Class,
|
|
1206
|
-
Union: UnionVariants,
|
|
1207
|
-
fieldEvolve,
|
|
1208
|
-
extract: extractVariants
|
|
1209
|
-
};
|
|
1210
|
-
};
|
|
1211
|
-
const Override = (value) => value;
|
|
1212
|
-
const Overrideable = (schema, options) => schema.pipe(decodeTo(brand("Override")(toType(schema))), withConstructorDefault(map(options.defaultValue, Override)));
|
|
1213
|
-
const StructProto = { pipe() {
|
|
1214
|
-
return pipeArguments(this, arguments);
|
|
1215
|
-
} };
|
|
1216
|
-
const Struct$1 = (fields) => {
|
|
1217
|
-
const self = Object.create(StructProto);
|
|
1218
|
-
self[TypeId$2] = fields;
|
|
1219
|
-
return self;
|
|
1220
|
-
};
|
|
1221
|
-
const FieldProto = {
|
|
1222
|
-
[FieldTypeId]: FieldTypeId,
|
|
1223
|
-
pipe() {
|
|
1224
|
-
return pipeArguments(this, arguments);
|
|
1225
|
-
}
|
|
1226
|
-
};
|
|
1227
|
-
const Field$1 = (schemas) => {
|
|
1228
|
-
const self = Object.create(FieldProto);
|
|
1229
|
-
self.schemas = schemas;
|
|
1230
|
-
return self;
|
|
1231
|
-
};
|
|
1232
|
-
const Union$1 = (members, defaultVariant, variants) => {
|
|
1233
|
-
const VariantUnion = Union$2(members.map((member) => isSchema(member) ? member : extract$1(member, defaultVariant, { isDefault: true })));
|
|
1234
|
-
for (const variant of variants) Object.defineProperty(VariantUnion, variant, { value: Union$2(members.map((member) => extract$1(member, variant))) });
|
|
1235
|
-
return VariantUnion;
|
|
1236
|
-
};
|
|
1237
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/schema/Model.js
|
|
1238
|
-
const { Class, Field, FieldExcept, FieldOnly, Struct, Union, extract, fieldEvolve } = make$3({
|
|
1239
|
-
variants: [
|
|
1240
|
-
"select",
|
|
1241
|
-
"insert",
|
|
1242
|
-
"update",
|
|
1243
|
-
"json",
|
|
1244
|
-
"jsonCreate",
|
|
1245
|
-
"jsonUpdate"
|
|
1246
|
-
],
|
|
1247
|
-
defaultVariant: "select"
|
|
1248
|
-
});
|
|
1249
|
-
const optionalOption = (schema) => optionalKey(NullOr(schema)).pipe(decodeTo(Option(toType(schema)), transformOptional({
|
|
1250
|
-
decode: (oe) => oe.pipe(filter(isNotNull), some),
|
|
1251
|
-
encode: flatten
|
|
1252
|
-
})));
|
|
1253
|
-
const FieldOption = fieldEvolve({
|
|
1254
|
-
select: map$4(OptionFromNullOr),
|
|
1255
|
-
insert: map$4(OptionFromNullOr),
|
|
1256
|
-
update: map$4(OptionFromNullOr),
|
|
1257
|
-
json: map$4(optionalOption),
|
|
1258
|
-
jsonCreate: map$4(optionalOption),
|
|
1259
|
-
jsonUpdate: map$4(optionalOption)
|
|
1260
|
-
});
|
|
1261
|
-
const BooleanSqlite = Field({
|
|
1262
|
-
select: BooleanFromBit,
|
|
1263
|
-
insert: BooleanFromBit,
|
|
1264
|
-
update: BooleanFromBit,
|
|
1265
|
-
json: Boolean,
|
|
1266
|
-
jsonCreate: Boolean,
|
|
1267
|
-
jsonUpdate: Boolean
|
|
1268
|
-
});
|
|
1269
|
-
const Date$1 = String$1.pipe(decodeTo(DateTimeUtc, {
|
|
1270
|
-
decode: map$1(dateTimeUtcFromInput(), removeTime),
|
|
1271
|
-
encode: transform(formatIsoDate)
|
|
1272
|
-
}));
|
|
1273
|
-
const DateWithNow = Overrideable(Date$1, { defaultValue: map(now, removeTime) });
|
|
1274
|
-
const DateTimeWithNow = Overrideable(DateTimeUtcFromString, { defaultValue: now });
|
|
1275
|
-
const DateTimeFromDateWithNow = Overrideable(DateTimeUtcFromDate, { defaultValue: now });
|
|
1276
|
-
const DateTimeFromNumberWithNow = Overrideable(DateTimeUtcFromMillis, { defaultValue: now });
|
|
1277
|
-
const DateTimeInsert = Field({
|
|
1278
|
-
select: DateTimeUtcFromString,
|
|
1279
|
-
insert: DateTimeWithNow,
|
|
1280
|
-
json: DateTimeUtcFromString
|
|
1281
|
-
});
|
|
1282
|
-
const DateTimeInsertFromDate = Field({
|
|
1283
|
-
select: DateTimeUtcFromDate,
|
|
1284
|
-
insert: DateTimeFromDateWithNow,
|
|
1285
|
-
json: DateTimeUtcFromString
|
|
1286
|
-
});
|
|
1287
|
-
const DateTimeInsertFromNumber = Field({
|
|
1288
|
-
select: DateTimeUtcFromMillis,
|
|
1289
|
-
insert: DateTimeFromNumberWithNow,
|
|
1290
|
-
json: DateTimeUtcFromMillis
|
|
1291
|
-
});
|
|
1292
|
-
const DateTimeUpdate = Field({
|
|
1293
|
-
select: DateTimeUtcFromString,
|
|
1294
|
-
insert: DateTimeWithNow,
|
|
1295
|
-
update: DateTimeWithNow,
|
|
1296
|
-
json: DateTimeUtcFromString
|
|
1297
|
-
});
|
|
1298
|
-
const DateTimeUpdateFromDate = Field({
|
|
1299
|
-
select: DateTimeUtcFromDate,
|
|
1300
|
-
insert: DateTimeFromDateWithNow,
|
|
1301
|
-
update: DateTimeFromDateWithNow,
|
|
1302
|
-
json: DateTimeUtcFromString
|
|
1303
|
-
});
|
|
1304
|
-
const DateTimeUpdateFromNumber = Field({
|
|
1305
|
-
select: DateTimeUtcFromMillis,
|
|
1306
|
-
insert: DateTimeFromNumberWithNow,
|
|
1307
|
-
update: DateTimeFromNumberWithNow,
|
|
1308
|
-
json: DateTimeUtcFromMillis
|
|
1309
|
-
});
|
|
1310
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/SqlResolver.js
|
|
1311
|
-
const SqlRequestProto = {
|
|
1312
|
-
...Class$2.prototype,
|
|
1313
|
-
[symbol](that) {
|
|
1314
|
-
return equals(this.payload, that.payload);
|
|
1315
|
-
},
|
|
1316
|
-
[symbol$1]() {
|
|
1317
|
-
return hash(this.payload);
|
|
1318
|
-
}
|
|
1319
|
-
};
|
|
1320
|
-
const request = function() {
|
|
1321
|
-
if (arguments.length === 1) {
|
|
1322
|
-
const resolver = arguments[0];
|
|
1323
|
-
return (payload) => request$1(SqlRequest(payload), resolver);
|
|
1324
|
-
}
|
|
1325
|
-
return request$1(SqlRequest(arguments[0]), arguments[1]);
|
|
1326
|
-
};
|
|
1327
|
-
const SqlRequest = (payload) => {
|
|
1328
|
-
const self = Object.create(SqlRequestProto);
|
|
1329
|
-
self.payload = payload;
|
|
1330
|
-
return self;
|
|
1331
|
-
};
|
|
1332
|
-
const ordered = (options) => {
|
|
1333
|
-
const decodeArray = decodeUnknownEffect(ArraySchema(options.Result));
|
|
1334
|
-
return makeGrouped({
|
|
1335
|
-
key: transactionKey,
|
|
1336
|
-
resolver: fnUntraced(function* (entries) {
|
|
1337
|
-
const [inputs, encodedEntries] = yield* partitionRequests(entries, options.Request);
|
|
1338
|
-
if (!isArrayNonEmpty(inputs)) return;
|
|
1339
|
-
const results = yield* options.execute(inputs).pipe(provideContext(entries[0].context));
|
|
1340
|
-
if (results.length !== inputs.length) return yield* new ResultLengthMismatch({
|
|
1341
|
-
expected: inputs.length,
|
|
1342
|
-
actual: results.length
|
|
1343
|
-
});
|
|
1344
|
-
const decodedResults = yield* decodeArray(results).pipe(provideContext(entries[0].context));
|
|
1345
|
-
for (let i = 0; i < encodedEntries.length; i++) encodedEntries[i].completeUnsafe(succeed$2(decodedResults[i]));
|
|
1346
|
-
})
|
|
1347
|
-
});
|
|
1348
|
-
};
|
|
1349
|
-
const findById = (options) => {
|
|
1350
|
-
const decodeResults = decodeUnknownEffect(ArraySchema(options.Result));
|
|
1351
|
-
return makeGrouped({
|
|
1352
|
-
key: transactionKey,
|
|
1353
|
-
resolver: fnUntraced(function* (entries) {
|
|
1354
|
-
const [inputs, idMap] = yield* partitionRequestsById(entries, options.Id);
|
|
1355
|
-
if (!isArrayNonEmpty(inputs)) return;
|
|
1356
|
-
const results = yield* options.execute(inputs).pipe(provideContext(entries[0].context));
|
|
1357
|
-
const decodedResults = yield* decodeResults(results).pipe(provideContext(entries[0].context));
|
|
1358
|
-
for (let i = 0; i < decodedResults.length; i++) {
|
|
1359
|
-
const result = decodedResults[i];
|
|
1360
|
-
const id = options.ResultId(result, results[i]);
|
|
1361
|
-
const request = get$2(idMap, id);
|
|
1362
|
-
if (request._tag === "None") continue;
|
|
1363
|
-
remove(idMap, id);
|
|
1364
|
-
request.value.completeUnsafe(succeed$2(result));
|
|
1365
|
-
}
|
|
1366
|
-
if (isEmpty(idMap)) return;
|
|
1367
|
-
forEach$1(idMap, (request) => {
|
|
1368
|
-
request.completeUnsafe(constNoSuchElement);
|
|
1369
|
-
});
|
|
1370
|
-
})
|
|
1371
|
-
});
|
|
1372
|
-
};
|
|
1373
|
-
const void_ = (options) => makeGrouped({
|
|
1374
|
-
key: transactionKey,
|
|
1375
|
-
resolver: fnUntraced(function* (entries) {
|
|
1376
|
-
const [inputs] = yield* partitionRequests(entries, options.Request);
|
|
1377
|
-
if (!isArrayNonEmpty(inputs)) return;
|
|
1378
|
-
yield* options.execute(inputs).pipe(provideContext(entries[0].context));
|
|
1379
|
-
for (let i = 0; i < entries.length; i++) entries[i].completeUnsafe(void_$3);
|
|
1380
|
-
})
|
|
1381
|
-
});
|
|
1382
|
-
const constNoSuchElement = fail$1(new NoSuchElementError());
|
|
1383
|
-
const partitionRequests = function* (requests, schema) {
|
|
1384
|
-
const len = requests.length;
|
|
1385
|
-
const inputs = empty();
|
|
1386
|
-
const encodedEntries = empty();
|
|
1387
|
-
let entry;
|
|
1388
|
-
const encode = encodeEffect(schema);
|
|
1389
|
-
const handle = matchCauseEager({
|
|
1390
|
-
onFailure(cause) {
|
|
1391
|
-
entry.completeUnsafe(failCause(cause));
|
|
1392
|
-
},
|
|
1393
|
-
onSuccess(value) {
|
|
1394
|
-
inputs.push(value);
|
|
1395
|
-
encodedEntries.push(entry);
|
|
1396
|
-
}
|
|
1397
|
-
});
|
|
1398
|
-
for (let i = 0; i < len; i++) {
|
|
1399
|
-
entry = requests[i];
|
|
1400
|
-
yield provideContext(handle(encode(entry.request.payload)), entry.context);
|
|
1401
|
-
}
|
|
1402
|
-
return [inputs, encodedEntries];
|
|
1403
|
-
};
|
|
1404
|
-
const partitionRequestsById = function* (requests, schema) {
|
|
1405
|
-
const len = requests.length;
|
|
1406
|
-
const inputs = empty();
|
|
1407
|
-
const byIdMap = empty$1();
|
|
1408
|
-
for (let i = 0; i < len; i++) {
|
|
1409
|
-
const entry = requests[i];
|
|
1410
|
-
const existing = get$2(byIdMap, entry.request.payload);
|
|
1411
|
-
if (isSome(existing)) {
|
|
1412
|
-
const previous = existing.value;
|
|
1413
|
-
set(byIdMap, entry.request.payload, {
|
|
1414
|
-
...previous,
|
|
1415
|
-
completeUnsafe(exit) {
|
|
1416
|
-
previous.completeUnsafe(exit);
|
|
1417
|
-
entry.completeUnsafe(exit);
|
|
1418
|
-
}
|
|
1419
|
-
});
|
|
1420
|
-
} else set(byIdMap, entry.request.payload, entry);
|
|
1421
|
-
}
|
|
1422
|
-
const encode = encodeEffect(schema);
|
|
1423
|
-
for (const [, entry] of byIdMap) yield* provideContext(matchCauseEager(encode(entry.request.payload), {
|
|
1424
|
-
onFailure(cause) {
|
|
1425
|
-
entry.completeUnsafe(failCause(cause));
|
|
1426
|
-
},
|
|
1427
|
-
onSuccess(value) {
|
|
1428
|
-
inputs.push(value);
|
|
1429
|
-
}
|
|
1430
|
-
}), entry.context);
|
|
1431
|
-
return [inputs, byIdMap];
|
|
1432
|
-
};
|
|
1433
|
-
function transactionKey(entry) {
|
|
1434
|
-
const client = getOrUndefined(entry.context, SqlClient);
|
|
1435
|
-
const clientTransaction = client && getOrUndefined(entry.context, client.transactionService);
|
|
1436
|
-
const currentService = get$1(entry.context, CurrentTransactionService);
|
|
1437
|
-
const currentTransaction = currentService && getOrUndefined(entry.context, currentService);
|
|
1438
|
-
if (clientTransaction === void 0 || clientTransaction === currentTransaction) return currentTransaction && byReferenceUnsafe(currentTransaction);
|
|
1439
|
-
if (currentTransaction === void 0) return byReferenceUnsafe(clientTransaction);
|
|
1440
|
-
return [byReferenceUnsafe(clientTransaction), byReferenceUnsafe(currentTransaction)];
|
|
1441
|
-
}
|
|
1442
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/SqlSchema.js
|
|
1443
|
-
const findAll = (options) => {
|
|
1444
|
-
const encodeRequest = encodeEffect(options.Request);
|
|
1445
|
-
const decode = decodeUnknownEffect(mutable(ArraySchema(options.Result)));
|
|
1446
|
-
return (request) => flatMap(flatMap(encodeRequest(request), options.execute), decode);
|
|
1447
|
-
};
|
|
1448
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/SqlModel.js
|
|
1449
|
-
const makeResolvers = (Model, options) => gen(function* () {
|
|
1450
|
-
const sql = yield* SqlClient;
|
|
1451
|
-
const idSchema = Model.fields[options.idColumn];
|
|
1452
|
-
const idColumn = options.idColumn;
|
|
1453
|
-
const softDeleteColumn = options.softDeleteColumn;
|
|
1454
|
-
const withSoftDeleteFilter = (where) => softDeleteColumn === void 0 ? where : sql.and([where, sql`${sql(softDeleteColumn)} is null`]);
|
|
1455
|
-
const setSoftDeleted = softDeleteColumn === void 0 ? void 0 : sql`${sql(softDeleteColumn)} = CURRENT_TIMESTAMP`;
|
|
1456
|
-
return {
|
|
1457
|
-
insert: ordered({
|
|
1458
|
-
Request: Model.insert,
|
|
1459
|
-
Result: Model,
|
|
1460
|
-
execute: (request) => sql.onDialectOrElse({
|
|
1461
|
-
mysql: () => forEach(request, (request) => sql`insert into ${sql(options.tableName)} ${sql.insert(request)};
|
|
1462
|
-
select * from ${sql(options.tableName)} where ${withSoftDeleteFilter(sql`${sql(idColumn)} = LAST_INSERT_ID()`)};`.unprepared.pipe(map(([, results]) => results[0])), { concurrency: 10 }),
|
|
1463
|
-
orElse: () => sql`insert into ${sql(options.tableName)} ${sql.insert(request).returning("*")}`
|
|
1464
|
-
})
|
|
1465
|
-
}).pipe(withSpan$1(`${options.spanPrefix}.insertResolver`)),
|
|
1466
|
-
insertVoid: void_({
|
|
1467
|
-
Request: Model.insert,
|
|
1468
|
-
execute: (request) => sql`insert into ${sql(options.tableName)} ${sql.insert(request)}`
|
|
1469
|
-
}).pipe(withSpan$1(`${options.spanPrefix}.insertVoidResolver`)),
|
|
1470
|
-
findById: findById({
|
|
1471
|
-
Id: idSchema,
|
|
1472
|
-
Result: Model,
|
|
1473
|
-
ResultId(request) {
|
|
1474
|
-
return request[idColumn];
|
|
1475
|
-
},
|
|
1476
|
-
execute: (ids) => sql`select * from ${sql(options.tableName)} where ${withSoftDeleteFilter(sql.in(idColumn, ids))}`
|
|
1477
|
-
}).pipe(withSpan$1(`${options.spanPrefix}.findByIdResolver`)),
|
|
1478
|
-
delete: void_({
|
|
1479
|
-
Request: idSchema,
|
|
1480
|
-
execute: (ids) => softDeleteColumn === void 0 ? sql`delete from ${sql(options.tableName)} where ${sql.in(idColumn, ids)}` : sql`update ${sql(options.tableName)} set ${setSoftDeleted} where ${withSoftDeleteFilter(sql.in(idColumn, ids))}`
|
|
1481
|
-
}).pipe(withSpan$1(`${options.spanPrefix}.deleteResolver`))
|
|
1482
|
-
};
|
|
1483
|
-
});
|
|
1484
|
-
// src/ChunkRepo.ts
|
|
1485
|
-
const ChunkId = Number$1.pipe(brand("ChunkRepo/ChunkId"));
|
|
1486
|
-
const SyncId = String$1.pipe(brand("ChunkRepo/SyncId"));
|
|
1487
|
-
const Float32ArraySchema = instanceOf(Float32Array);
|
|
1488
|
-
const Float32ArrayFromArray = ArraySchema(Number$1).pipe(decodeTo(Float32ArraySchema, transform$1({
|
|
1489
|
-
decode: (arr) => new Float32Array(arr),
|
|
1490
|
-
encode: (array) => Array.from(array)
|
|
1491
|
-
})));
|
|
1492
|
-
const Float32ArrayField = Field({
|
|
1493
|
-
insert: Float32ArraySchema,
|
|
1494
|
-
update: Float32ArraySchema,
|
|
1495
|
-
jsonCreate: Float32ArrayFromArray,
|
|
1496
|
-
jsonUpdate: Float32ArrayFromArray
|
|
1497
|
-
});
|
|
1498
|
-
var Chunk = class extends Class("Chunk")({
|
|
1499
|
-
id: ChunkId.pipe(FieldExcept(["insert", "jsonCreate"])),
|
|
1500
|
-
path: String$1,
|
|
1501
|
-
content: String$1,
|
|
1502
|
-
hash: String$1,
|
|
1503
|
-
vector: Float32ArrayField,
|
|
1504
|
-
syncId: SyncId
|
|
1505
|
-
}) {};
|
|
1506
|
-
var ChunkRepo = class extends Service()("clanka/ChunkRepo") {};
|
|
1507
|
-
var ChunkRepoError = class extends TaggedError()("ChunkRepoError", { reason: Union$2([SqlError]) }) {
|
|
1508
|
-
cause = this.reason;
|
|
1509
|
-
message = this.reason.message;
|
|
1510
|
-
};
|
|
1511
|
-
const layer$4 = effect(ChunkRepo, gen(function* () {
|
|
1512
|
-
const sql = yield* SqlClient;
|
|
1513
|
-
const dimensions = yield* Dimensions;
|
|
1514
|
-
yield* gen(function* () {
|
|
1515
|
-
yield* sql`CREATE VIRTUAL TABLE IF NOT EXISTS chunk_vectors USING vec0(
|
|
1516
|
-
vector float[${sql.literal(String(dimensions))}]
|
|
1517
|
-
)`;
|
|
1518
|
-
yield* sql`CREATE TRIGGER IF NOT EXISTS chunks_vector_insert
|
|
1519
|
-
AFTER INSERT ON chunks
|
|
1520
|
-
BEGIN
|
|
1521
|
-
INSERT INTO chunk_vectors(rowid, vector) VALUES (new.id, new.vector);
|
|
1522
|
-
END`;
|
|
1523
|
-
yield* sql`CREATE TRIGGER IF NOT EXISTS chunks_vector_update
|
|
1524
|
-
AFTER UPDATE OF vector ON chunks
|
|
1525
|
-
BEGIN
|
|
1526
|
-
DELETE FROM chunk_vectors WHERE rowid = old.id;
|
|
1527
|
-
INSERT INTO chunk_vectors(rowid, vector) VALUES (new.id, new.vector);
|
|
1528
|
-
END`;
|
|
1529
|
-
yield* sql`CREATE TRIGGER IF NOT EXISTS chunks_vector_delete
|
|
1530
|
-
AFTER DELETE ON chunks
|
|
1531
|
-
BEGIN
|
|
1532
|
-
DELETE FROM chunk_vectors WHERE rowid = old.id;
|
|
1533
|
-
END`;
|
|
1534
|
-
yield* sql`DELETE FROM chunk_vectors
|
|
1535
|
-
WHERE rowid NOT IN (SELECT id FROM chunks)`;
|
|
1536
|
-
yield* sql`INSERT INTO chunk_vectors(rowid, vector)
|
|
1537
|
-
SELECT id, vector FROM chunks
|
|
1538
|
-
WHERE id NOT IN (SELECT rowid FROM chunk_vectors)`;
|
|
1539
|
-
}).pipe(sql.withTransaction);
|
|
1540
|
-
const loaders = yield* makeResolvers(Chunk, {
|
|
1541
|
-
tableName: "chunks",
|
|
1542
|
-
idColumn: "id",
|
|
1543
|
-
spanPrefix: "ChunkRepo"
|
|
1544
|
-
});
|
|
1545
|
-
const search = findAll({
|
|
1546
|
-
Request: Struct$2({
|
|
1547
|
-
vector: Float32ArraySchema,
|
|
1548
|
-
limit: Number$1
|
|
1549
|
-
}),
|
|
1550
|
-
Result: Chunk,
|
|
1551
|
-
execute: ({ vector, limit }) => sql`
|
|
1552
|
-
select chunks.id, chunks.path, chunks.content, chunks.hash, chunks.syncId
|
|
1553
|
-
from chunk_vectors
|
|
1554
|
-
JOIN chunks ON chunks.id = chunk_vectors.rowid
|
|
1555
|
-
WHERE chunk_vectors.vector MATCH ${vector}
|
|
1556
|
-
AND k = CAST(${limit} AS INTEGER)
|
|
1557
|
-
ORDER BY chunk_vectors.distance
|
|
1558
|
-
`
|
|
1559
|
-
});
|
|
1560
|
-
const exists = findById({
|
|
1561
|
-
Id: String$1,
|
|
1562
|
-
Result: Struct$2({
|
|
1563
|
-
id: ChunkId,
|
|
1564
|
-
hash: String$1
|
|
1565
|
-
}),
|
|
1566
|
-
ResultId(result) {
|
|
1567
|
-
return result.hash;
|
|
1568
|
-
},
|
|
1569
|
-
execute: (hashes) => sql`select id, hash from chunks where ${sql.in("hash", hashes)}`
|
|
1570
|
-
}).pipe(setDelay(5));
|
|
1571
|
-
const insertResolver = loaders.insert.pipe(setDelay(5));
|
|
1572
|
-
const findByIdResolver = loaders.findById.pipe(setDelay(5));
|
|
1573
|
-
return ChunkRepo.of({
|
|
1574
|
-
insert: (insert) => request(insert, insertResolver).pipe(catchTags({
|
|
1575
|
-
SchemaError: die,
|
|
1576
|
-
ResultLengthMismatch: die
|
|
1577
|
-
}, (reason) => fail(new ChunkRepoError({ reason })))),
|
|
1578
|
-
findById: (id) => request(id, findByIdResolver).pipe(catchTags({
|
|
1579
|
-
SchemaError: die,
|
|
1580
|
-
SqlError: (reason) => fail(new ChunkRepoError({ reason }))
|
|
1581
|
-
})),
|
|
1582
|
-
exists: (hash) => request(hash, exists).pipe(map((result) => result.id), catchNoSuchElement, catchTags({
|
|
1583
|
-
SqlError: (reason) => fail(new ChunkRepoError({ reason })),
|
|
1584
|
-
SchemaError: die
|
|
1585
|
-
})),
|
|
1586
|
-
search: fn("ChunkRepo.search")(function* (options) {
|
|
1587
|
-
return yield* search(options).pipe(catchTags({
|
|
1588
|
-
SqlError: (reason) => fail(new ChunkRepoError({ reason })),
|
|
1589
|
-
SchemaError: die
|
|
1590
|
-
}));
|
|
1591
|
-
}),
|
|
1592
|
-
quantize: void_$1,
|
|
1593
|
-
setSyncId: (chunkId, syncId) => sql`update chunks set syncId = ${syncId} where id = ${chunkId}`.pipe(mapError((reason) => new ChunkRepoError({ reason }))),
|
|
1594
|
-
deleteByPath: (path) => sql`delete from chunks where path = ${path}`.pipe(mapError((reason) => new ChunkRepoError({ reason }))),
|
|
1595
|
-
deleteForSyncId: (syncId) => sql`delete from chunks where syncId != ${syncId}`.pipe(mapError((reason) => new ChunkRepoError({ reason })))
|
|
1596
|
-
});
|
|
1597
|
-
}));
|
|
1598
|
-
// src/CodeChunker.ts
|
|
1599
|
-
var CodeChunker = class extends Service()("clanka/CodeChunker") {};
|
|
1600
|
-
const sourceExtensions = new Set([
|
|
1601
|
-
"c",
|
|
1602
|
-
"cc",
|
|
1603
|
-
"cpp",
|
|
1604
|
-
"cs",
|
|
1605
|
-
"css",
|
|
1606
|
-
"cts",
|
|
1607
|
-
"cxx",
|
|
1608
|
-
"go",
|
|
1609
|
-
"gql",
|
|
1610
|
-
"graphql",
|
|
1611
|
-
"h",
|
|
1612
|
-
"hpp",
|
|
1613
|
-
"html",
|
|
1614
|
-
"ini",
|
|
1615
|
-
"java",
|
|
1616
|
-
"js",
|
|
1617
|
-
"jsx",
|
|
1618
|
-
"kt",
|
|
1619
|
-
"kts",
|
|
1620
|
-
"less",
|
|
1621
|
-
"lua",
|
|
1622
|
-
"mjs",
|
|
1623
|
-
"mts",
|
|
1624
|
-
"php",
|
|
1625
|
-
"py",
|
|
1626
|
-
"rb",
|
|
1627
|
-
"rs",
|
|
1628
|
-
"sass",
|
|
1629
|
-
"scala",
|
|
1630
|
-
"scss",
|
|
1631
|
-
"sh",
|
|
1632
|
-
"sql",
|
|
1633
|
-
"svelte",
|
|
1634
|
-
"swift",
|
|
1635
|
-
"ts",
|
|
1636
|
-
"tsx",
|
|
1637
|
-
"vue",
|
|
1638
|
-
"xml",
|
|
1639
|
-
"zsh"
|
|
1640
|
-
]);
|
|
1641
|
-
const documentationExtensions = new Set([
|
|
1642
|
-
"adoc",
|
|
1643
|
-
"asciidoc",
|
|
1644
|
-
"md",
|
|
1645
|
-
"mdx",
|
|
1646
|
-
"rst",
|
|
1647
|
-
"txt"
|
|
1648
|
-
]);
|
|
1649
|
-
const ignoredDirectories = new Set([
|
|
1650
|
-
".git",
|
|
1651
|
-
".next",
|
|
1652
|
-
".nuxt",
|
|
1653
|
-
".svelte-kit",
|
|
1654
|
-
".turbo",
|
|
1655
|
-
"build",
|
|
1656
|
-
"coverage",
|
|
1657
|
-
"dist",
|
|
1658
|
-
"node_modules",
|
|
1659
|
-
"target"
|
|
1660
|
-
]);
|
|
1661
|
-
const normalizePath$1 = (path) => path.replace(/\\/g, "/");
|
|
1662
|
-
const normalizeText = (content) => content.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
1663
|
-
const meaningfulLinePattern = /[^\s\p{P}]/u;
|
|
1664
|
-
const isMeaningfulLine = (line) => meaningfulLinePattern.test(line);
|
|
1665
|
-
const languageByExtension = new Map([
|
|
1666
|
-
["js", JavaScript],
|
|
1667
|
-
["jsx", JavaScript],
|
|
1668
|
-
["ts", TreeSitterTypeScript.typescript],
|
|
1669
|
-
["tsx", TreeSitterTypeScript.tsx]
|
|
1670
|
-
]);
|
|
1671
|
-
const isProbablyMinified = (content) => {
|
|
1672
|
-
const normalized = normalizeText(content);
|
|
1673
|
-
if (normalized.length < 2e3) return false;
|
|
1674
|
-
const lines = normalized.split("\n");
|
|
1675
|
-
if (lines.length <= 2) return true;
|
|
1676
|
-
let longLines = 0;
|
|
1677
|
-
for (const line of lines) if (line.length >= 300) longLines++;
|
|
1678
|
-
return lines.length <= 20 && longLines / lines.length >= .8;
|
|
1679
|
-
};
|
|
1680
|
-
const isMeaningfulFile = (path) => {
|
|
1681
|
-
const parts = normalizePath$1(path).toLowerCase().split("/");
|
|
1682
|
-
const fileName = parts.at(-1);
|
|
1683
|
-
if (fileName === void 0 || fileName.length === 0) return false;
|
|
1684
|
-
if (parts.some((part) => ignoredDirectories.has(part))) return false;
|
|
1685
|
-
if (/\.min\.(?:css|js)$/i.test(fileName)) return false;
|
|
1686
|
-
const extensionIndex = fileName.lastIndexOf(".");
|
|
1687
|
-
if (extensionIndex === -1) return false;
|
|
1688
|
-
const extension = fileName.slice(extensionIndex + 1);
|
|
1689
|
-
return sourceExtensions.has(extension) || documentationExtensions.has(extension);
|
|
1690
|
-
};
|
|
1691
|
-
const resolveChunkSettings = (options) => {
|
|
1692
|
-
const chunkSize = Math.max(1, options.chunkSize);
|
|
1693
|
-
return {
|
|
1694
|
-
chunkSize,
|
|
1695
|
-
chunkOverlap: Math.max(0, Math.min(chunkSize - 1, options.chunkOverlap)),
|
|
1696
|
-
chunkMaxCharacters: options.chunkMaxCharacters !== void 0 && Number.isFinite(options.chunkMaxCharacters) ? Math.max(1, Math.floor(options.chunkMaxCharacters)) : Number.POSITIVE_INFINITY
|
|
1697
|
-
};
|
|
1698
|
-
};
|
|
1699
|
-
const getPathExtension = (path) => {
|
|
1700
|
-
const fileName = path.split("/").at(-1);
|
|
1701
|
-
if (fileName === void 0) return;
|
|
1702
|
-
const extensionIndex = fileName.lastIndexOf(".");
|
|
1703
|
-
if (extensionIndex === -1) return;
|
|
1704
|
-
return fileName.slice(extensionIndex + 1).toLowerCase();
|
|
1705
|
-
};
|
|
1706
|
-
const resolveAstLanguage = (path) => {
|
|
1707
|
-
const extension = getPathExtension(path);
|
|
1708
|
-
if (extension === void 0) return;
|
|
1709
|
-
return languageByExtension.get(extension);
|
|
1710
|
-
};
|
|
1711
|
-
const lineRangeFromNode = (node) => {
|
|
1712
|
-
const startLine = node.startPosition.row + 1;
|
|
1713
|
-
return {
|
|
1714
|
-
startLine,
|
|
1715
|
-
endLine: Math.max(startLine, node.endPosition.row + 1)
|
|
1716
|
-
};
|
|
1717
|
-
};
|
|
1718
|
-
const hasOnlyWhitespaceLines = (lines, startLine, endLine) => {
|
|
1719
|
-
if (startLine > endLine) return true;
|
|
1720
|
-
for (let lineIndex = startLine; lineIndex <= endLine; lineIndex++) if ((lines[lineIndex - 1] ?? "").trim().length > 0) return false;
|
|
1721
|
-
return true;
|
|
1722
|
-
};
|
|
1723
|
-
const lineRangeWithLeadingComments = (node, siblings, nodeIndex, lines) => {
|
|
1724
|
-
const baseRange = lineRangeFromNode(node);
|
|
1725
|
-
let startLine = baseRange.startLine;
|
|
1726
|
-
for (let index = nodeIndex - 1; index >= 0; index--) {
|
|
1727
|
-
const sibling = siblings[index];
|
|
1728
|
-
if (sibling.type !== "comment") break;
|
|
1729
|
-
const commentRange = lineRangeFromNode(sibling);
|
|
1730
|
-
if (!hasOnlyWhitespaceLines(lines, commentRange.endLine + 1, startLine - 1)) break;
|
|
1731
|
-
startLine = commentRange.startLine;
|
|
1732
|
-
}
|
|
1733
|
-
return {
|
|
1734
|
-
startLine,
|
|
1735
|
-
endLine: baseRange.endLine
|
|
1736
|
-
};
|
|
1737
|
-
};
|
|
1738
|
-
const normalizeLineRange = (range, lineCount) => {
|
|
1739
|
-
const startLine = Math.max(1, Math.min(lineCount, range.startLine));
|
|
1740
|
-
const endLine = Math.max(1, Math.min(lineCount, range.endLine));
|
|
1741
|
-
if (endLine < startLine) return;
|
|
1742
|
-
return {
|
|
1743
|
-
startLine,
|
|
1744
|
-
endLine
|
|
1745
|
-
};
|
|
1746
|
-
};
|
|
1747
|
-
const lineLengthPrefixSums = (lines) => {
|
|
1748
|
-
const sums = [0];
|
|
1749
|
-
for (let index = 0; index < lines.length; index++) sums.push(sums[index] + lines[index].length);
|
|
1750
|
-
return sums;
|
|
1751
|
-
};
|
|
1752
|
-
const lineRangeCharacterLength = (prefixSums, range) => prefixSums[range.endLine] - prefixSums[range.startLine - 1] + (range.endLine - range.startLine);
|
|
1753
|
-
const resolveSegmentEndLine = (options) => {
|
|
1754
|
-
if (options.settings.chunkMaxCharacters === Number.POSITIVE_INFINITY) return options.maxEndLine;
|
|
1755
|
-
let endLine = options.maxEndLine;
|
|
1756
|
-
while (endLine > options.startLine && lineRangeCharacterLength(options.prefixSums, {
|
|
1757
|
-
startLine: options.startLine,
|
|
1758
|
-
endLine
|
|
1759
|
-
}) > options.settings.chunkMaxCharacters) endLine--;
|
|
1760
|
-
return endLine;
|
|
1761
|
-
};
|
|
1762
|
-
const splitRange = (range, settings, prefixSums) => {
|
|
1763
|
-
if (range.endLine - range.startLine + 1 <= settings.chunkSize && lineRangeCharacterLength(prefixSums, range) <= settings.chunkMaxCharacters) return [range];
|
|
1764
|
-
const out = [];
|
|
1765
|
-
for (let startLine = range.startLine; startLine <= range.endLine;) {
|
|
1766
|
-
const maxEndLine = Math.min(range.endLine, startLine + settings.chunkSize - 1);
|
|
1767
|
-
const endLine = resolveSegmentEndLine({
|
|
1768
|
-
startLine,
|
|
1769
|
-
maxEndLine,
|
|
1770
|
-
settings,
|
|
1771
|
-
prefixSums
|
|
1772
|
-
});
|
|
1773
|
-
out.push({
|
|
1774
|
-
startLine,
|
|
1775
|
-
endLine
|
|
1776
|
-
});
|
|
1777
|
-
if (endLine >= range.endLine) break;
|
|
1778
|
-
startLine = Math.max(startLine + 1, endLine - settings.chunkOverlap + 1);
|
|
1779
|
-
}
|
|
1780
|
-
return out;
|
|
1781
|
-
};
|
|
1782
|
-
const nodeText = (node) => {
|
|
1783
|
-
if (node === null) return;
|
|
1784
|
-
const value = node.text.trim().replace(/\s+/g, " ");
|
|
1785
|
-
return value.length === 0 ? void 0 : value;
|
|
1786
|
-
};
|
|
1787
|
-
const nodeFieldText = (node, fieldName) => nodeText(node.childForFieldName(fieldName));
|
|
1788
|
-
const isNamespaceNode = (node) => node.type === "internal_module" || node.type === "module";
|
|
1789
|
-
const unwrapDeclarationNode = (node) => {
|
|
1790
|
-
let current = node;
|
|
1791
|
-
while (true) {
|
|
1792
|
-
if (current.type === "export_statement") {
|
|
1793
|
-
const declaration = current.childForFieldName("declaration") ?? current.namedChildren[0];
|
|
1794
|
-
if (declaration === void 0) return current;
|
|
1795
|
-
current = declaration;
|
|
1796
|
-
continue;
|
|
1797
|
-
}
|
|
1798
|
-
if (current.type === "ambient_declaration") {
|
|
1799
|
-
const declaration = current.namedChildren.find((child) => child.type.endsWith("_declaration") || isNamespaceNode(child));
|
|
1800
|
-
if (declaration === void 0) return current;
|
|
1801
|
-
current = declaration;
|
|
1802
|
-
continue;
|
|
1803
|
-
}
|
|
1804
|
-
return current;
|
|
1805
|
-
}
|
|
1806
|
-
};
|
|
1807
|
-
const variableDeclarators = (node) => node.namedChildren.filter((child) => child.type === "variable_declarator");
|
|
1808
|
-
const variableTypeFromDeclarator = (node) => {
|
|
1809
|
-
const value = node.childForFieldName("value");
|
|
1810
|
-
if (value !== null && value.type.includes("function")) return "function";
|
|
1811
|
-
return "variable";
|
|
1812
|
-
};
|
|
1813
|
-
const variableTypeFromDeclaration = (node) => {
|
|
1814
|
-
if (variableDeclarators(node).some((declarator) => variableTypeFromDeclarator(declarator) === "function")) return "function";
|
|
1815
|
-
return "variable";
|
|
1816
|
-
};
|
|
1817
|
-
const chunkTypeFromNode = (node) => {
|
|
1818
|
-
switch (node.type) {
|
|
1819
|
-
case "class_declaration": return "class";
|
|
1820
|
-
case "enum_declaration": return "enum";
|
|
1821
|
-
case "function_declaration":
|
|
1822
|
-
case "generator_function_declaration": return "function";
|
|
1823
|
-
case "internal_module":
|
|
1824
|
-
case "module": return "namespace";
|
|
1825
|
-
case "interface_declaration": return "interface";
|
|
1826
|
-
case "generator_method_definition":
|
|
1827
|
-
case "method_definition": return "method";
|
|
1828
|
-
case "type_alias_declaration": return "type-alias";
|
|
1829
|
-
case "lexical_declaration":
|
|
1830
|
-
case "variable_declaration": return variableTypeFromDeclaration(node);
|
|
1831
|
-
case "variable_declarator": return variableTypeFromDeclarator(node);
|
|
1832
|
-
default: return;
|
|
1833
|
-
}
|
|
1834
|
-
};
|
|
1835
|
-
const variableNamesFromDeclaration = (node) => {
|
|
1836
|
-
const names = variableDeclarators(node).map((declarator) => nodeFieldText(declarator, "name")).filter((name) => name !== void 0);
|
|
1837
|
-
if (names.length === 0) return;
|
|
1838
|
-
return names.join(", ");
|
|
1839
|
-
};
|
|
1840
|
-
const nameFromNode = (node) => {
|
|
1841
|
-
switch (node.type) {
|
|
1842
|
-
case "class_declaration":
|
|
1843
|
-
case "enum_declaration":
|
|
1844
|
-
case "function_declaration":
|
|
1845
|
-
case "generator_function_declaration":
|
|
1846
|
-
case "internal_module":
|
|
1847
|
-
case "interface_declaration":
|
|
1848
|
-
case "module":
|
|
1849
|
-
case "generator_method_definition":
|
|
1850
|
-
case "method_definition":
|
|
1851
|
-
case "type_alias_declaration":
|
|
1852
|
-
case "variable_declarator": return nodeFieldText(node, "name");
|
|
1853
|
-
case "lexical_declaration":
|
|
1854
|
-
case "variable_declaration": return variableNamesFromDeclaration(node);
|
|
1855
|
-
default: return;
|
|
1856
|
-
}
|
|
1857
|
-
};
|
|
1858
|
-
const formatParent = (type, name) => {
|
|
1859
|
-
if (type === void 0 && name === void 0) return;
|
|
1860
|
-
if (type === void 0) return name;
|
|
1861
|
-
if (name === void 0) return type;
|
|
1862
|
-
return type + " " + name;
|
|
1863
|
-
};
|
|
1864
|
-
const collectClassMethodRanges = (classNode, parent, lines) => {
|
|
1865
|
-
const body = classNode.childForFieldName("body");
|
|
1866
|
-
if (body === null) return [];
|
|
1867
|
-
const out = [];
|
|
1868
|
-
for (let index = 0; index < body.namedChildren.length; index++) {
|
|
1869
|
-
const child = body.namedChildren[index];
|
|
1870
|
-
if (!child.type.includes("method")) continue;
|
|
1871
|
-
out.push({
|
|
1872
|
-
...lineRangeWithLeadingComments(child, body.namedChildren, index, lines),
|
|
1873
|
-
name: nameFromNode(child),
|
|
1874
|
-
type: chunkTypeFromNode(child),
|
|
1875
|
-
parent
|
|
1876
|
-
});
|
|
1877
|
-
}
|
|
1878
|
-
return out;
|
|
1879
|
-
};
|
|
1880
|
-
const collectAstRanges = (path, content, lines) => {
|
|
1881
|
-
const language = resolveAstLanguage(path);
|
|
1882
|
-
if (language === void 0) return [];
|
|
1883
|
-
try {
|
|
1884
|
-
const parser = new TreeSitter();
|
|
1885
|
-
parser.setLanguage(language);
|
|
1886
|
-
const tree = parser.parse(content, void 0, { bufferSize: 1048576 });
|
|
1887
|
-
const collectDeclarationRanges = (siblings, parent) => {
|
|
1888
|
-
const out = [];
|
|
1889
|
-
for (let index = 0; index < siblings.length; index++) {
|
|
1890
|
-
const sibling = siblings[index];
|
|
1891
|
-
if (sibling.type === "comment" || sibling.type.includes("import")) continue;
|
|
1892
|
-
const declarationNode = unwrapDeclarationNode(sibling);
|
|
1893
|
-
const type = chunkTypeFromNode(declarationNode);
|
|
1894
|
-
const name = nameFromNode(declarationNode);
|
|
1895
|
-
if (type === void 0 && name === void 0) continue;
|
|
1896
|
-
out.push({
|
|
1897
|
-
...lineRangeWithLeadingComments(sibling, siblings, index, lines),
|
|
1898
|
-
name,
|
|
1899
|
-
type,
|
|
1900
|
-
parent
|
|
1901
|
-
});
|
|
1902
|
-
if (declarationNode.type === "class_declaration") out.push(...collectClassMethodRanges(declarationNode, formatParent(type, name), lines));
|
|
1903
|
-
if (isNamespaceNode(declarationNode)) {
|
|
1904
|
-
const body = declarationNode.childForFieldName("body");
|
|
1905
|
-
if (body !== null) out.push(...collectDeclarationRanges(body.namedChildren, formatParent(type, name)));
|
|
1906
|
-
}
|
|
1907
|
-
}
|
|
1908
|
-
return out;
|
|
1909
|
-
};
|
|
1910
|
-
return collectDeclarationRanges(tree.rootNode.namedChildren, void 0);
|
|
1911
|
-
} catch {
|
|
1912
|
-
return [];
|
|
1913
|
-
}
|
|
1914
|
-
};
|
|
1915
|
-
const chunksFromRanges = (path, lines, ranges, settings) => {
|
|
1916
|
-
const hasMethodChildRange = (classRange) => {
|
|
1917
|
-
const parent = formatParent("class", classRange.name);
|
|
1918
|
-
return ranges.some((range) => range.type === "method" && range.parent === parent && range.startLine >= classRange.startLine && range.endLine <= classRange.endLine);
|
|
1919
|
-
};
|
|
1920
|
-
const out = [];
|
|
1921
|
-
const seen = new Set();
|
|
1922
|
-
const prefixSums = lineLengthPrefixSums(lines);
|
|
1923
|
-
for (const range of ranges) {
|
|
1924
|
-
const normalizedRange = normalizeLineRange(range, lines.length);
|
|
1925
|
-
if (normalizedRange === void 0) continue;
|
|
1926
|
-
const allSegments = splitRange(normalizedRange, settings, prefixSums);
|
|
1927
|
-
const segments = range.type === "class" && allSegments.length > 1 && hasMethodChildRange({
|
|
1928
|
-
...normalizedRange,
|
|
1929
|
-
name: range.name
|
|
1930
|
-
}) ? [allSegments[0]] : allSegments;
|
|
1931
|
-
for (const segment of segments) {
|
|
1932
|
-
const key = String(segment.startLine) + ":" + String(segment.endLine) + ":" + (range.name ?? "") + ":" + (range.type ?? "") + ":" + (range.parent ?? "");
|
|
1933
|
-
if (seen.has(key)) continue;
|
|
1934
|
-
seen.add(key);
|
|
1935
|
-
const chunkLines = lines.slice(segment.startLine - 1, segment.endLine);
|
|
1936
|
-
if (!chunkLines.some(isMeaningfulLine)) continue;
|
|
1937
|
-
out.push({
|
|
1938
|
-
path,
|
|
1939
|
-
startLine: segment.startLine,
|
|
1940
|
-
endLine: segment.endLine,
|
|
1941
|
-
name: range.name,
|
|
1942
|
-
type: range.type,
|
|
1943
|
-
parent: range.parent,
|
|
1944
|
-
content: chunkLines.join("\n")
|
|
1945
|
-
});
|
|
1946
|
-
}
|
|
1947
|
-
}
|
|
1948
|
-
return out.toSorted((left, right) => left.startLine - right.startLine || left.endLine - right.endLine || (left.name ?? "").localeCompare(right.name ?? ""));
|
|
1949
|
-
};
|
|
1950
|
-
const chunkWithLineWindows = (path, lines, settings) => {
|
|
1951
|
-
const out = [];
|
|
1952
|
-
const prefixSums = lineLengthPrefixSums(lines);
|
|
1953
|
-
for (let index = 0; index < lines.length;) {
|
|
1954
|
-
if (!isMeaningfulLine(lines[index])) {
|
|
1955
|
-
index++;
|
|
1956
|
-
continue;
|
|
1957
|
-
}
|
|
1958
|
-
const startLine = index + 1;
|
|
1959
|
-
const maxEndLine = Math.min(lines.length, startLine + settings.chunkSize - 1);
|
|
1960
|
-
const endLine = resolveSegmentEndLine({
|
|
1961
|
-
startLine,
|
|
1962
|
-
maxEndLine,
|
|
1963
|
-
settings,
|
|
1964
|
-
prefixSums
|
|
1965
|
-
});
|
|
1966
|
-
const chunkLines = lines.slice(startLine - 1, endLine);
|
|
1967
|
-
out.push({
|
|
1968
|
-
path,
|
|
1969
|
-
startLine,
|
|
1970
|
-
endLine,
|
|
1971
|
-
name: void 0,
|
|
1972
|
-
type: void 0,
|
|
1973
|
-
parent: void 0,
|
|
1974
|
-
content: chunkLines.join("\n")
|
|
1975
|
-
});
|
|
1976
|
-
if (endLine >= lines.length) break;
|
|
1977
|
-
index = Math.max(startLine + 1, endLine - settings.chunkOverlap + 1) - 1;
|
|
1978
|
-
}
|
|
1979
|
-
return out;
|
|
1980
|
-
};
|
|
1981
|
-
const splitOversizedChunks = (chunks, maxCharacters) => chunks.flatMap((chunk) => {
|
|
1982
|
-
if (chunk.content.length <= maxCharacters) return [chunk];
|
|
1983
|
-
const pieces = [];
|
|
1984
|
-
for (let offset = 0; offset < chunk.content.length; offset += maxCharacters) pieces.push({
|
|
1985
|
-
...chunk,
|
|
1986
|
-
content: chunk.content.slice(offset, offset + maxCharacters)
|
|
1987
|
-
});
|
|
1988
|
-
return pieces;
|
|
1989
|
-
});
|
|
1990
|
-
const chunkFileContent = (path, content, options) => {
|
|
1991
|
-
if (content.trim().length === 0 || isProbablyMinified(content)) return [];
|
|
1992
|
-
const normalizedPath = normalizePath$1(path);
|
|
1993
|
-
const normalizedContent = normalizeText(content);
|
|
1994
|
-
const lines = normalizedContent.split("\n");
|
|
1995
|
-
if (lines.at(-1) === "") lines.pop();
|
|
1996
|
-
if (lines.length === 0) return [];
|
|
1997
|
-
const settings = resolveChunkSettings(options);
|
|
1998
|
-
const astRanges = collectAstRanges(normalizedPath, normalizedContent, lines);
|
|
1999
|
-
if (astRanges.length > 0) {
|
|
2000
|
-
const astChunks = chunksFromRanges(normalizedPath, lines, astRanges, settings);
|
|
2001
|
-
if (astChunks.length > 0) return splitOversizedChunks(astChunks, settings.chunkMaxCharacters);
|
|
2002
|
-
}
|
|
2003
|
-
return splitOversizedChunks(chunkWithLineWindows(normalizedPath, lines, settings), settings.chunkMaxCharacters);
|
|
2004
|
-
};
|
|
2005
|
-
const layer$3 = effect(CodeChunker, gen(function* () {
|
|
2006
|
-
const spawner = yield* ChildProcessSpawner;
|
|
2007
|
-
const fs = yield* FileSystem;
|
|
2008
|
-
const pathService = yield* Path;
|
|
2009
|
-
const listFiles = fn("CodeChunker.listFiles")(function* (options) {
|
|
2010
|
-
const root = pathService.resolve(options.root);
|
|
2011
|
-
const maxFileSize = options.maxFileSize ?? "1M";
|
|
2012
|
-
return yield* pipe(spawner.streamLines(make$11("rg", [
|
|
2013
|
-
"--files",
|
|
2014
|
-
"--hidden",
|
|
2015
|
-
"--max-filesize",
|
|
2016
|
-
maxFileSize,
|
|
2017
|
-
"--glob",
|
|
2018
|
-
"!.git"
|
|
2019
|
-
], {
|
|
2020
|
-
cwd: root,
|
|
2021
|
-
stdin: "ignore"
|
|
2022
|
-
})), runCollect, map(fromIterable), map((entries) => entries.map((entry) => normalizePath$1(entry.trim())).filter((entry) => entry.length > 0 && isMeaningfulFile(entry)).toSorted((left, right) => left.localeCompare(right))), orDie);
|
|
2023
|
-
});
|
|
2024
|
-
const chunkFile = fn("CodeChunker.chunkFile")(function* (options) {
|
|
2025
|
-
const root = pathService.resolve(options.root);
|
|
2026
|
-
const absolutePath = pathService.resolve(root, options.path);
|
|
2027
|
-
const path = normalizePath$1(pathService.relative(root, absolutePath));
|
|
2028
|
-
if (path.length === 0 || path === ".." || path.startsWith("../") || !isMeaningfulFile(path)) return [];
|
|
2029
|
-
return yield* pipe(fs.readFileString(absolutePath), map((content) => chunkFileContent(path, content, options)), orElseSucceed(() => []));
|
|
2030
|
-
});
|
|
2031
|
-
const chunkFiles = (options) => fromArray(options.paths).pipe(flatMap$1((path) => pipe(chunkFile({
|
|
2032
|
-
root: options.root,
|
|
2033
|
-
path,
|
|
2034
|
-
chunkSize: options.chunkSize,
|
|
2035
|
-
chunkOverlap: options.chunkOverlap,
|
|
2036
|
-
...options.chunkMaxCharacters === void 0 ? {} : { chunkMaxCharacters: options.chunkMaxCharacters }
|
|
2037
|
-
}), fromArrayEffect), { concurrency: 5 }));
|
|
2038
|
-
const chunkCodebase = fnUntraced(function* (options) {
|
|
2039
|
-
const root = pathService.resolve(options.root);
|
|
2040
|
-
const files = yield* listFiles({
|
|
2041
|
-
root,
|
|
2042
|
-
...options.maxFileSize === void 0 ? {} : { maxFileSize: options.maxFileSize }
|
|
2043
|
-
});
|
|
2044
|
-
return chunkFiles({
|
|
2045
|
-
root,
|
|
2046
|
-
paths: files,
|
|
2047
|
-
chunkSize: options.chunkSize,
|
|
2048
|
-
chunkOverlap: options.chunkOverlap,
|
|
2049
|
-
...options.chunkMaxCharacters === void 0 ? {} : { chunkMaxCharacters: options.chunkMaxCharacters }
|
|
2050
|
-
});
|
|
2051
|
-
}, unwrap);
|
|
2052
|
-
return CodeChunker.of({
|
|
2053
|
-
listFiles,
|
|
2054
|
-
chunkFile,
|
|
2055
|
-
chunkFiles,
|
|
2056
|
-
chunkCodebase
|
|
2057
|
-
});
|
|
2058
|
-
}));
|
|
2059
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/FiberHandle.js
|
|
2060
|
-
const TypeId$1 = "~effect/FiberHandle";
|
|
2061
|
-
const isFiberHandle = (u) => hasProperty(u, TypeId$1);
|
|
2062
|
-
const Proto = {
|
|
2063
|
-
[TypeId$1]: TypeId$1,
|
|
2064
|
-
...PipeInspectableProto,
|
|
2065
|
-
toJSON() {
|
|
2066
|
-
return {
|
|
2067
|
-
_id: "FiberHandle",
|
|
2068
|
-
state: this.state
|
|
2069
|
-
};
|
|
2070
|
-
}
|
|
2071
|
-
};
|
|
2072
|
-
const makeUnsafe = () => {
|
|
2073
|
-
const self = Object.create(Proto);
|
|
2074
|
-
self.state = {
|
|
2075
|
-
_tag: "Open",
|
|
2076
|
-
fiber: void 0,
|
|
2077
|
-
fibers: new Set()
|
|
2078
|
-
};
|
|
2079
|
-
self.deferred = makeUnsafe$2();
|
|
2080
|
-
return self;
|
|
2081
|
-
};
|
|
2082
|
-
const make$2 = () => acquireRelease(sync(() => makeUnsafe()), (handle) => {
|
|
2083
|
-
const state = handle.state;
|
|
2084
|
-
if (state._tag === "Closed") return void_$1;
|
|
2085
|
-
handle.state = { _tag: "Closed" };
|
|
2086
|
-
return into(interruptAllAs(state.fibers, internalFiberId), handle.deferred);
|
|
2087
|
-
});
|
|
2088
|
-
const internalFiberId = -1;
|
|
2089
|
-
const isInternalInterruption = toPredicate(compose(filterInterruptors, has(internalFiberId)));
|
|
2090
|
-
const setUnsafe = dual((args) => isFiberHandle(args[0]), (self, fiber, options) => {
|
|
2091
|
-
if (self.state._tag === "Closed") {
|
|
2092
|
-
fiber.interruptUnsafe(internalFiberId);
|
|
2093
|
-
return;
|
|
2094
|
-
}
|
|
2095
|
-
const previous = self.state.fiber;
|
|
2096
|
-
if (previous !== void 0) {
|
|
2097
|
-
if (previous === fiber) return;
|
|
2098
|
-
else if (options?.onlyIfMissing === true) {
|
|
2099
|
-
fiber.interruptUnsafe(internalFiberId);
|
|
2100
|
-
return;
|
|
2101
|
-
}
|
|
2102
|
-
}
|
|
2103
|
-
self.state.fiber = fiber;
|
|
2104
|
-
self.state.fibers.add(fiber);
|
|
2105
|
-
previous?.interruptUnsafe(internalFiberId);
|
|
2106
|
-
fiber.addObserver((exit) => {
|
|
2107
|
-
if (self.state._tag === "Open") {
|
|
2108
|
-
self.state.fibers.delete(fiber);
|
|
2109
|
-
if (fiber === self.state.fiber) self.state.fiber = void 0;
|
|
2110
|
-
}
|
|
2111
|
-
if (isFailure(exit) && (options?.propagateInterruption === true ? !isInternalInterruption(exit.cause) : !hasInterruptsOnly(exit.cause))) doneUnsafe(self.deferred, exit);
|
|
2112
|
-
});
|
|
2113
|
-
});
|
|
2114
|
-
const constInterruptedFiber = function() {
|
|
2115
|
-
let fiber = void 0;
|
|
2116
|
-
return () => {
|
|
2117
|
-
if (fiber === void 0) fiber = runFork(interrupt);
|
|
2118
|
-
return fiber;
|
|
2119
|
-
};
|
|
2120
|
-
}();
|
|
2121
|
-
const run$1 = function() {
|
|
2122
|
-
const self = arguments[0];
|
|
2123
|
-
if (isEffect(arguments[1])) return runImpl(self, arguments[1], arguments[2]);
|
|
2124
|
-
const options = arguments[1];
|
|
2125
|
-
return (effect) => runImpl(self, effect, options);
|
|
2126
|
-
};
|
|
2127
|
-
const runImpl = (self, effect, options) => withFiber((parent) => {
|
|
2128
|
-
if (self.state._tag === "Closed") return interrupt;
|
|
2129
|
-
else if (self.state.fiber !== void 0 && options?.onlyIfMissing === true) return sync(constInterruptedFiber);
|
|
2130
|
-
const fiber = forkUnsafe(parent, effect, options?.startImmediately ?? true, true);
|
|
2131
|
-
setUnsafe(self, fiber, options);
|
|
2132
|
-
return succeed(fiber);
|
|
2133
|
-
});
|
|
2134
|
-
// node_modules/.pnpm/@effect+sql-sqlite-node@4.1.3_effect@4.1.3/node_modules/@effect/sql-sqlite-node/dist/SqliteClient.js
|
|
2135
|
-
const ATTR_DB_SYSTEM_NAME = "db.system.name";
|
|
2136
|
-
const MAX_BUSY_TIMEOUT = 2147483647;
|
|
2137
|
-
const NANOS_PER_MILLI = BigInt(1e6);
|
|
2138
|
-
const TypeId = "~@effect/sql-sqlite-node/SqliteClient";
|
|
2139
|
-
const SqliteClient = Service("@effect/sql-sqlite-node/SqliteClient");
|
|
2140
|
-
const make$1 = (options) => gen(function* () {
|
|
2141
|
-
const compiler = makeCompilerSqlite(options.transformQueryNames);
|
|
2142
|
-
const transformRows = options.transformResultNames ? defaultTransforms(options.transformResultNames).array : void 0;
|
|
2143
|
-
const connection = yield* gen(function* () {
|
|
2144
|
-
const db = yield* acquireRelease(try_({
|
|
2145
|
-
try: () => new DatabaseSync(options.filename, {
|
|
2146
|
-
readOnly: options.readonly ?? false,
|
|
2147
|
-
allowExtension: true
|
|
2148
|
-
}),
|
|
2149
|
-
catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to open database", "connect") })
|
|
2150
|
-
}), (db) => sync(() => db.close()));
|
|
2151
|
-
setLoadExtensionEnabled(db, false);
|
|
2152
|
-
const busyTimeout = Math.min(MAX_BUSY_TIMEOUT, Math.max(0, Math.round(toMillis(options.busyTimeout ?? seconds(5)))));
|
|
2153
|
-
const exec = (sql) => try_({
|
|
2154
|
-
try: () => db.exec(sql),
|
|
2155
|
-
catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to configure database", "connect") })
|
|
2156
|
-
});
|
|
2157
|
-
yield* exec(`PRAGMA busy_timeout = ${busyTimeout}`);
|
|
2158
|
-
if (options.disableWAL !== true && !options.readonly) {
|
|
2159
|
-
const enableWAL = try_({
|
|
2160
|
-
try: () => db.prepare("PRAGMA journal_mode = WAL").get(),
|
|
2161
|
-
catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to configure database", "connect") })
|
|
2162
|
-
});
|
|
2163
|
-
const deadline = (yield* monotonicTimeNanos) + BigInt(busyTimeout) * NANOS_PER_MILLI;
|
|
2164
|
-
const remainingMillis = map(monotonicTimeNanos, (now) => Math.max(0, Number((deadline - now) / NANOS_PER_MILLI)));
|
|
2165
|
-
yield* remainingMillis.pipe(flatMap((remaining) => exec(`PRAGMA busy_timeout = ${remaining}`)), andThen(enableWAL), retry({
|
|
2166
|
-
while: (error) => error.reason._tag === "LockTimeoutError" && map(remainingMillis, (remaining) => remaining > 0),
|
|
2167
|
-
schedule: spaced("10 millis")
|
|
2168
|
-
}));
|
|
2169
|
-
yield* exec(`PRAGMA busy_timeout = ${busyTimeout}`);
|
|
2170
|
-
}
|
|
2171
|
-
const prepare = (sql) => try_({
|
|
2172
|
-
try: () => db.prepare(sql),
|
|
2173
|
-
catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to prepare statement", "prepare") })
|
|
2174
|
-
});
|
|
2175
|
-
const prepareCacheTTL = options.prepareCacheTTL ?? minutes(10);
|
|
2176
|
-
const prepareCache = yield* makeWith(prepare, {
|
|
2177
|
-
capacity: options.prepareCacheSize ?? 200,
|
|
2178
|
-
timeToLive: (exit) => isSuccess(exit) ? prepareCacheTTL : zero
|
|
2179
|
-
});
|
|
2180
|
-
const runStatement = (statement, params, raw) => withFiber((fiber) => {
|
|
2181
|
-
const useSafeIntegers = get$1(fiber.context, SafeIntegers);
|
|
2182
|
-
return try_({
|
|
2183
|
-
try: () => {
|
|
2184
|
-
statement.setReadBigInts(useSafeIntegers);
|
|
2185
|
-
if (!raw || statement.columns().length > 0) return statement.all(...params);
|
|
2186
|
-
const result = statement.run(...params);
|
|
2187
|
-
return {
|
|
2188
|
-
changes: result.changes,
|
|
2189
|
-
lastInsertRowid: result.lastInsertRowid
|
|
2190
|
-
};
|
|
2191
|
-
},
|
|
2192
|
-
catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
|
|
2193
|
-
});
|
|
2194
|
-
});
|
|
2195
|
-
const runStatementValues = (statement, params) => withFiber((fiber) => {
|
|
2196
|
-
const useSafeIntegers = get$1(fiber.context, SafeIntegers);
|
|
2197
|
-
return try_({
|
|
2198
|
-
try: () => {
|
|
2199
|
-
statement.setReadBigInts(useSafeIntegers);
|
|
2200
|
-
return statement.all(...params);
|
|
2201
|
-
},
|
|
2202
|
-
catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
|
|
2203
|
-
});
|
|
2204
|
-
});
|
|
2205
|
-
const runStatementValuesUnprepared = (statement, params) => withFiber((fiber) => {
|
|
2206
|
-
const useSafeIntegers = get$1(fiber.context, SafeIntegers);
|
|
2207
|
-
return try_({
|
|
2208
|
-
try: () => {
|
|
2209
|
-
statement.setReadBigInts(useSafeIntegers);
|
|
2210
|
-
statement.setReturnArrays(true);
|
|
2211
|
-
return statement.all(...params);
|
|
2212
|
-
},
|
|
2213
|
-
catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
|
|
2214
|
-
});
|
|
2215
|
-
});
|
|
2216
|
-
const run = (sql, params, raw = false) => flatMap(get(prepareCache, sql), (s) => runStatement(s, params, raw));
|
|
2217
|
-
const runValues = (sql, params) => acquireUseRelease(get(prepareCache, sql), (statement) => {
|
|
2218
|
-
statement.setReturnArrays(true);
|
|
2219
|
-
return runStatementValues(statement, params);
|
|
2220
|
-
}, (statement) => sync(() => statement.setReturnArrays(false)));
|
|
2221
|
-
const runValuesUnprepared = (sql, params) => flatMap(prepare(sql), (statement) => runStatementValuesUnprepared(statement, params));
|
|
2222
|
-
return identity({
|
|
2223
|
-
isTransaction: () => db.isTransaction,
|
|
2224
|
-
execute(sql, params, transformRows) {
|
|
2225
|
-
return transformRows ? map(run(sql, params), transformRows) : run(sql, params);
|
|
2226
|
-
},
|
|
2227
|
-
executeRaw(sql, params) {
|
|
2228
|
-
return run(sql, params, true);
|
|
2229
|
-
},
|
|
2230
|
-
executeValues(sql, params) {
|
|
2231
|
-
return runValues(sql, params);
|
|
2232
|
-
},
|
|
2233
|
-
executeValuesUnprepared(sql, params) {
|
|
2234
|
-
return runValuesUnprepared(sql, params);
|
|
2235
|
-
},
|
|
2236
|
-
executeUnprepared(sql, params, transformRows) {
|
|
2237
|
-
const effect = flatMap(prepare(sql), (statement) => runStatement(statement, params ?? [], false));
|
|
2238
|
-
return transformRows ? map(effect, transformRows) : effect;
|
|
2239
|
-
},
|
|
2240
|
-
executeStream(_sql, _params) {
|
|
2241
|
-
return die$1("executeStream not implemented");
|
|
2242
|
-
},
|
|
2243
|
-
backup(destination) {
|
|
2244
|
-
return suspend(() => {
|
|
2245
|
-
let totalPages = 0;
|
|
2246
|
-
return tryPromise({
|
|
2247
|
-
try: () => backup(db, destination, { progress: (progress) => {
|
|
2248
|
-
totalPages = progress.totalPages;
|
|
2249
|
-
} }).then((pages) => ({
|
|
2250
|
-
totalPages: totalPages || pages,
|
|
2251
|
-
remainingPages: 0
|
|
2252
|
-
})),
|
|
2253
|
-
catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to backup database", "backup") })
|
|
2254
|
-
});
|
|
2255
|
-
});
|
|
2256
|
-
},
|
|
2257
|
-
loadExtension(path) {
|
|
2258
|
-
return acquireUseRelease(sync(() => setLoadExtensionEnabled(db, true)), () => try_({
|
|
2259
|
-
try: () => db.loadExtension(path),
|
|
2260
|
-
catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to load extension", "loadExtension") })
|
|
2261
|
-
}), () => sync(() => setLoadExtensionEnabled(db, false)));
|
|
2262
|
-
}
|
|
2263
|
-
});
|
|
2264
|
-
});
|
|
2265
|
-
const { acquirer, borrower, isTransaction, onCommitFailure, transactionAcquirer } = makeSqliteAcquirers({
|
|
2266
|
-
connection: succeed(connection),
|
|
2267
|
-
semaphore: yield* make$13(1),
|
|
2268
|
-
isTransaction: (conn) => conn.isTransaction()
|
|
2269
|
-
});
|
|
2270
|
-
return Object.assign(yield* make$4({
|
|
2271
|
-
driver: "sqlite-node",
|
|
2272
|
-
acquirer,
|
|
2273
|
-
borrower,
|
|
2274
|
-
compiler,
|
|
2275
|
-
transactionAcquirer,
|
|
2276
|
-
onCommitFailure,
|
|
2277
|
-
isTransaction,
|
|
2278
|
-
releaseSavepoint: (name) => `RELEASE SAVEPOINT ${name}`,
|
|
2279
|
-
beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
|
|
2280
|
-
spanAttributes: [...options.spanAttributes ? Object.entries(options.spanAttributes) : [], [ATTR_DB_SYSTEM_NAME, "sqlite"]],
|
|
2281
|
-
transformRows
|
|
2282
|
-
}), {
|
|
2283
|
-
[TypeId]: TypeId,
|
|
2284
|
-
config: options,
|
|
2285
|
-
backup: (destination) => scoped(flatMap(acquirer, (_) => _.backup(destination))),
|
|
2286
|
-
loadExtension: (path) => scoped(flatMap(acquirer, (_) => _.loadExtension(path)))
|
|
2287
|
-
});
|
|
2288
|
-
});
|
|
2289
|
-
const layer$2 = (config) => effectContext(map(make$1(config), (client) => make$9(SqliteClient, client).pipe(add(SqlClient, client)))).pipe(provide$1(layer$5));
|
|
2290
|
-
const classifyError = (cause, message, operation) => classifySqliteError(sqliteCauseWithErrno(cause), {
|
|
2291
|
-
message,
|
|
2292
|
-
operation
|
|
2293
|
-
});
|
|
2294
|
-
const sqliteCauseWithErrno = (cause) => {
|
|
2295
|
-
if (typeof cause !== "object" || cause === null || !("errcode" in cause) || "errno" in cause) return cause;
|
|
2296
|
-
const errcode = cause.errcode;
|
|
2297
|
-
if (typeof errcode !== "number") return cause;
|
|
2298
|
-
return Object.assign(cause, { errno: errcode });
|
|
2299
|
-
};
|
|
2300
|
-
const setLoadExtensionEnabled = (db, enabled) => {
|
|
2301
|
-
if (typeof db.enableLoadExtension === "function") db.enableLoadExtension(enabled);
|
|
2302
|
-
};
|
|
2303
|
-
// node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/Migrator.js
|
|
2304
|
-
var MigrationError = class extends TaggedError$1("MigrationError") {};
|
|
2305
|
-
const make = ({ transformWrites = identity, dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, table = "effect_sql_migrations" }) => gen(function* () {
|
|
2306
|
-
const sql = yield* SqlClient;
|
|
2307
|
-
const createMigrationsTable = transformWrites(sql.onDialectOrElse({
|
|
2308
|
-
mssql: () => sql`IF OBJECT_ID(N'${sql.literal(table)}', N'U') IS NULL
|
|
2309
|
-
CREATE TABLE ${sql(table)} (
|
|
2310
|
-
migration_id INT NOT NULL PRIMARY KEY,
|
|
2311
|
-
name VARCHAR(255) NOT NULL,
|
|
2312
|
-
created_at DATETIME NOT NULL DEFAULT GETDATE()
|
|
2313
|
-
)`,
|
|
2314
|
-
mysql: () => sql`CREATE TABLE IF NOT EXISTS ${sql(table)} (
|
|
2315
|
-
migration_id INTEGER UNSIGNED NOT NULL,
|
|
2316
|
-
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
2317
|
-
name VARCHAR(255) NOT NULL,
|
|
2318
|
-
PRIMARY KEY (migration_id)
|
|
2319
|
-
)`,
|
|
2320
|
-
clickhouse: () => sql`CREATE TABLE IF NOT EXISTS ${sql(table)} (
|
|
2321
|
-
migration_id Int32,
|
|
2322
|
-
created_at DateTime DEFAULT now(),
|
|
2323
|
-
name String
|
|
2324
|
-
) ENGINE = MergeTree
|
|
2325
|
-
ORDER BY migration_id`,
|
|
2326
|
-
pg: () => sql`CREATE TABLE ${sql(table)} (
|
|
2327
|
-
migration_id integer primary key,
|
|
2328
|
-
created_at timestamp with time zone not null default now(),
|
|
2329
|
-
name text not null
|
|
2330
|
-
)`,
|
|
2331
|
-
orElse: () => sql`CREATE TABLE IF NOT EXISTS ${sql(table)} (
|
|
2332
|
-
migration_id integer PRIMARY KEY NOT NULL,
|
|
2333
|
-
created_at datetime NOT NULL DEFAULT current_timestamp,
|
|
2334
|
-
name VARCHAR(255) NOT NULL
|
|
2335
|
-
)`
|
|
2336
|
-
}));
|
|
2337
|
-
const ensureMigrationsTable = sql.onDialectOrElse({
|
|
2338
|
-
pg: () => flatMap(migrationsTableExists(sql, table), (exists) => exists ? void_$1 : asVoid(createMigrationsTable).pipe(catch_((error) => flatMap(migrationsTableExists(sql, table), (exists) => exists ? void_$1 : fail(error))))),
|
|
2339
|
-
orElse: () => createMigrationsTable
|
|
2340
|
-
});
|
|
2341
|
-
const insertMigrations = (rows) => transformWrites(sql`INSERT INTO ${sql(table)} ${sql.insert(map$2(rows, ([migration_id, name]) => ({
|
|
2342
|
-
migration_id,
|
|
2343
|
-
name
|
|
2344
|
-
})))}`.withoutTransform);
|
|
2345
|
-
const latestMigration = map(sql`SELECT migration_id, name, created_at FROM ${sql(table)} ORDER BY migration_id DESC`.withoutTransform, (_) => map$3(fromNullishOr(_[0]), ({ created_at, migration_id, name }) => ({
|
|
2346
|
-
id: migration_id,
|
|
2347
|
-
name,
|
|
2348
|
-
createdAt: created_at
|
|
2349
|
-
})));
|
|
2350
|
-
const loadMigration = ([id, name, load]) => catchDefect(load, (_) => fail(new MigrationError({
|
|
2351
|
-
kind: "ImportError",
|
|
2352
|
-
message: `Could not import migration "${id}_${name}"\n\n${_}`
|
|
2353
|
-
}))).pipe(flatMap((_) => isEffect(_) ? succeed(_) : _.default ? succeed(_.default?.default ?? _.default) : fail(new MigrationError({
|
|
2354
|
-
kind: "ImportError",
|
|
2355
|
-
message: `Default export not found for migration "${id}_${name}"`
|
|
2356
|
-
}))), filterOrFail((_) => isEffect(_), () => new MigrationError({
|
|
2357
|
-
kind: "ImportError",
|
|
2358
|
-
message: `Default export was not an Effect for migration "${id}_${name}"`
|
|
2359
|
-
})));
|
|
2360
|
-
const runMigration = (id, name, effect) => mapError(effect, (error) => new MigrationError({
|
|
2361
|
-
cause: error,
|
|
2362
|
-
kind: "Failed",
|
|
2363
|
-
message: `Migration "${id}_${name}" failed`
|
|
2364
|
-
}));
|
|
2365
|
-
const transactional = sql.onDialectOrElse({
|
|
2366
|
-
clickhouse: () => false,
|
|
2367
|
-
orElse: () => true
|
|
2368
|
-
});
|
|
2369
|
-
const run = gen(function* () {
|
|
2370
|
-
yield* sql.onDialectOrElse({
|
|
2371
|
-
pg: () => sql`LOCK TABLE ${sql(table)} IN ACCESS EXCLUSIVE MODE`,
|
|
2372
|
-
orElse: () => void_$1
|
|
2373
|
-
});
|
|
2374
|
-
const [latestMigrationId, current] = yield* all([map(latestMigration, match({
|
|
2375
|
-
onNone: () => 0,
|
|
2376
|
-
onSome: (_) => _.id
|
|
2377
|
-
})), loader]);
|
|
2378
|
-
if (new Set(current.map(([id]) => id)).size !== current.length) return yield* new MigrationError({
|
|
2379
|
-
kind: "Duplicates",
|
|
2380
|
-
message: "Found duplicate migration id's"
|
|
2381
|
-
});
|
|
2382
|
-
const required = [];
|
|
2383
|
-
for (const resolved of current) {
|
|
2384
|
-
const [currentId, currentName] = resolved;
|
|
2385
|
-
if (currentId <= latestMigrationId) continue;
|
|
2386
|
-
required.push([
|
|
2387
|
-
currentId,
|
|
2388
|
-
currentName,
|
|
2389
|
-
yield* loadMigration(resolved)
|
|
2390
|
-
]);
|
|
2391
|
-
}
|
|
2392
|
-
if (transactional && isArrayNonEmpty(required)) yield* pipe(insertMigrations(map$2(required, ([id, name]) => [id, name])), mapError((error) => isConstraintConflict(error) ? new MigrationError({
|
|
2393
|
-
kind: "Locked",
|
|
2394
|
-
message: "Migrations already running"
|
|
2395
|
-
}) : error));
|
|
2396
|
-
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 });
|
|
2397
|
-
yield* pipe(latestMigration, flatMap(match({
|
|
2398
|
-
onNone: () => logDebug(`Migrations complete`),
|
|
2399
|
-
onSome: (_) => logDebug(`Migrations complete`).pipe(annotateLogs("latest_migration_id", _.id.toString()), annotateLogs("latest_migration_name", _.name))
|
|
2400
|
-
})));
|
|
2401
|
-
return required.map(([id, name]) => [id, name]);
|
|
2402
|
-
});
|
|
2403
|
-
yield* ensureMigrationsTable;
|
|
2404
|
-
const completed = yield* pipe(transactional ? sql.withTransaction(run) : run, catchTag("MigrationError", (_) => _.kind === "Locked" ? as(logDebug(_.message), []) : fail(_)));
|
|
2405
|
-
if (schemaDirectory && completed.length > 0) yield* dumpSchema(`${schemaDirectory}/_schema.sql`, table).pipe(catchCause((cause) => logInfo("Could not dump schema", cause)));
|
|
2406
|
-
return completed;
|
|
2407
|
-
});
|
|
2408
|
-
const migrationsTableExists = (sql, table) => {
|
|
2409
|
-
const quotedTable = sql`${sql(table)}`.compile(true)[0];
|
|
2410
|
-
return map(sql`SELECT 1 AS found WHERE to_regclass(${quotedTable}) IS NOT NULL`.withoutTransform, (rows) => rows.length > 0);
|
|
2411
|
-
};
|
|
2412
|
-
const migrationOrder = make$10(([a], [b]) => Number$2(a, b));
|
|
2413
|
-
const isConstraintConflict = (error) => error.reason._tag === "ConstraintError" || error.reason._tag === "UniqueViolation";
|
|
2414
|
-
const fromRecord = (migrations) => pipe(Object.keys(migrations), flatMapNullishOr((_) => _.match(/^(\d+)_(.+)$/)), map$2(([key, id, name]) => [
|
|
2415
|
-
Number(id),
|
|
2416
|
-
name,
|
|
2417
|
-
succeed(migrations[key])
|
|
2418
|
-
]), sort(migrationOrder), succeed);
|
|
2419
|
-
// node_modules/.pnpm/@effect+sql-sqlite-node@4.1.3_effect@4.1.3/node_modules/@effect/sql-sqlite-node/dist/SqliteMigrator.js
|
|
2420
|
-
const run = make({});
|
|
2421
|
-
const layer$1 = (options) => effectDiscard(run(options));
|
|
2422
|
-
// src/Sqlite.ts
|
|
2423
|
-
const SqliteLayer = (database) => layer$1({ loader: fromRecord({ "0001_create_chunks": gen(function* () {
|
|
2424
|
-
const sql = yield* SqlClient;
|
|
2425
|
-
yield* sql`CREATE TABLE IF NOT EXISTS chunks (
|
|
2426
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2427
|
-
path TEXT NOT NULL,
|
|
2428
|
-
content TEXT NOT NULL,
|
|
2429
|
-
hash TEXT NOT NULL,
|
|
2430
|
-
vector BLOB NOT NULL,
|
|
2431
|
-
syncId TEXT NOT NULL
|
|
2432
|
-
)`;
|
|
2433
|
-
yield* sql`CREATE INDEX IF NOT EXISTS idx_chunks_hash ON chunks (hash)`;
|
|
2434
|
-
}) }) }).pipe(provide$1(effectDiscard(gen(function* () {
|
|
2435
|
-
yield* (yield* SqliteClient).loadExtension(getLoadablePath());
|
|
2436
|
-
}))), provideMerge(layer$2({ filename: database })), provide$1(effectDiscard(gen(function* () {
|
|
2437
|
-
const fs = yield* FileSystem;
|
|
2438
|
-
const directory = (yield* Path).dirname(database);
|
|
2439
|
-
if (directory === ".") return;
|
|
2440
|
-
yield* fs.makeDirectory(directory, { recursive: true });
|
|
2441
|
-
}))));
|
|
2442
|
-
// src/SemanticSearch.ts
|
|
2443
|
-
const normalizePath = (path) => path.replace(/\\/g, "/");
|
|
2444
|
-
const resolveChunkConfig = (options) => ({
|
|
2445
|
-
chunkSize: 30,
|
|
2446
|
-
chunkOverlap: 0,
|
|
2447
|
-
chunkMaxCharacters: options.chunkMaxCharacters ?? 15e3
|
|
2448
|
-
});
|
|
2449
|
-
const makeEmbeddingResolver = (resolver, options) => resolver.pipe(setDelay(options.embeddingRequestDelay ?? millis(50)), batchN(options.embeddingBatchSize ?? 100));
|
|
2450
|
-
const chunkEmbeddingInput = (chunk) => {
|
|
2451
|
-
const headerLines = ["---", "file: " + chunk.path];
|
|
2452
|
-
if (chunk.name !== void 0) headerLines.push("name: " + chunk.name);
|
|
2453
|
-
if (chunk.type !== void 0) headerLines.push("type: " + chunk.type);
|
|
2454
|
-
if (chunk.parent !== void 0) headerLines.push("parent: " + chunk.parent);
|
|
2455
|
-
headerLines.push("---");
|
|
2456
|
-
const contentLines = chunk.content.split("\n");
|
|
2457
|
-
let contentWithLines = "";
|
|
2458
|
-
for (let i = 0; i < contentLines.length; i++) {
|
|
2459
|
-
if (i > 0) contentWithLines += "\n";
|
|
2460
|
-
contentWithLines += `${chunk.startLine + i}: ${contentLines[i]}`;
|
|
2461
|
-
}
|
|
2462
|
-
return headerLines.join("\n") + "\n\n" + contentWithLines;
|
|
2463
|
-
};
|
|
2464
|
-
const hashChunkInput = (input) => createHash("sha256").update(input).digest("hex");
|
|
2465
|
-
const layer = (options) => effect(SemanticSearch, gen(function* () {
|
|
2466
|
-
const chunker = yield* CodeChunker;
|
|
2467
|
-
const repo = yield* ChunkRepo;
|
|
2468
|
-
const embeddings = yield* EmbeddingModel;
|
|
2469
|
-
const pathService = yield* Path;
|
|
2470
|
-
const root = pathService.resolve(options.directory);
|
|
2471
|
-
const resolver = makeEmbeddingResolver(embeddings.resolver, options);
|
|
2472
|
-
const concurrency = options.concurrency ?? 2e3;
|
|
2473
|
-
const chunkConfig = resolveChunkConfig(options);
|
|
2474
|
-
const indexHandle = yield* make$2();
|
|
2475
|
-
const console = yield* Console;
|
|
2476
|
-
const resolveIndexedPath = (path) => {
|
|
2477
|
-
const absolutePath = pathService.resolve(root, path);
|
|
2478
|
-
const relativePath = normalizePath(pathService.relative(root, absolutePath));
|
|
2479
|
-
if (relativePath.length === 0 || relativePath === ".." || relativePath.startsWith("../")) return none();
|
|
2480
|
-
return some(relativePath);
|
|
2481
|
-
};
|
|
2482
|
-
const processChunk = fnUntraced(function* (options) {
|
|
2483
|
-
const input = chunkEmbeddingInput(options.chunk);
|
|
2484
|
-
const hash = hashChunkInput(input);
|
|
2485
|
-
if (options.checkExisting) {
|
|
2486
|
-
const id = yield* repo.exists(hash);
|
|
2487
|
-
if (isSome(id)) {
|
|
2488
|
-
yield* repo.setSyncId(id.value, options.syncId);
|
|
2489
|
-
return;
|
|
2490
|
-
}
|
|
2491
|
-
}
|
|
2492
|
-
const result = yield* request$1(new EmbeddingRequest({ input }), resolver);
|
|
2493
|
-
const vector = new Float32Array(result.vector);
|
|
2494
|
-
yield* repo.insert(Chunk.insert.make({
|
|
2495
|
-
path: options.chunk.path,
|
|
2496
|
-
hash,
|
|
2497
|
-
content: input,
|
|
2498
|
-
vector,
|
|
2499
|
-
syncId: options.syncId
|
|
2500
|
-
}));
|
|
2501
|
-
}, ignore({
|
|
2502
|
-
log: "Warn",
|
|
2503
|
-
message: "Failed to process chunk for embedding"
|
|
2504
|
-
}), (effect, options) => annotateLogs(effect, { chunk: `${options.chunk.path}/${options.chunk.startLine}` }));
|
|
2505
|
-
const index = gen(function* () {
|
|
2506
|
-
const syncId = SyncId.make(crypto.randomUUID());
|
|
2507
|
-
yield* logInfo("Starting SemanticSearch index");
|
|
2508
|
-
yield* pipe(chunker.chunkCodebase({
|
|
2509
|
-
root,
|
|
2510
|
-
...chunkConfig
|
|
2511
|
-
}), tap$1((chunk) => processChunk({
|
|
2512
|
-
chunk,
|
|
2513
|
-
syncId,
|
|
2514
|
-
checkExisting: true
|
|
2515
|
-
}), { concurrency }), runDrain);
|
|
2516
|
-
yield* repo.deleteForSyncId(syncId);
|
|
2517
|
-
yield* logInfo("Finished SemanticSearch index");
|
|
2518
|
-
}).pipe(withSpan("SemanticSearch.index"), withLogSpan("SemanticSearch.index"), provideService(Console, console));
|
|
2519
|
-
const runIndex = run$1(indexHandle, index, { onlyIfMissing: true });
|
|
2520
|
-
const initialIndex = yield* runIndex;
|
|
2521
|
-
yield* runIndex.pipe(delay(minutes(3)), forever, forkScoped);
|
|
2522
|
-
return SemanticSearch.of({
|
|
2523
|
-
search: fn("SemanticSearch.search")(function* (options) {
|
|
2524
|
-
yield* join$1(initialIndex);
|
|
2525
|
-
yield* annotateCurrentSpan(options);
|
|
2526
|
-
const { vector } = yield* embeddings.embed(options.query);
|
|
2527
|
-
return (yield* repo.search({
|
|
2528
|
-
vector: new Float32Array(vector),
|
|
2529
|
-
limit: options.limit
|
|
2530
|
-
})).map((r) => r.content).join("\n\n");
|
|
2531
|
-
}, orDie),
|
|
2532
|
-
updateFile: fn("SemanticSearch.updateFile")(function* (path) {
|
|
2533
|
-
yield* join$1(initialIndex);
|
|
2534
|
-
const indexedPath = resolveIndexedPath(path);
|
|
2535
|
-
if (isNone(indexedPath)) return;
|
|
2536
|
-
yield* repo.deleteByPath(indexedPath.value);
|
|
2537
|
-
const chunks = yield* chunker.chunkFile({
|
|
2538
|
-
root,
|
|
2539
|
-
path: indexedPath.value,
|
|
2540
|
-
...chunkConfig
|
|
2541
|
-
});
|
|
2542
|
-
if (chunks.length === 0) return;
|
|
2543
|
-
const syncId = SyncId.make(crypto.randomUUID());
|
|
2544
|
-
yield* pipe(fromArray(chunks), tap$1((chunk) => processChunk({
|
|
2545
|
-
chunk,
|
|
2546
|
-
syncId,
|
|
2547
|
-
checkExisting: false
|
|
2548
|
-
}), { concurrency }), runDrain);
|
|
2549
|
-
}, orDie),
|
|
2550
|
-
removeFile: fn("SemanticSearch.removeFile")(function* (path) {
|
|
2551
|
-
yield* join$1(initialIndex);
|
|
2552
|
-
const indexedPath = resolveIndexedPath(path);
|
|
2553
|
-
if (isNone(indexedPath)) return;
|
|
2554
|
-
yield* repo.deleteByPath(indexedPath.value);
|
|
2555
|
-
}, orDie)
|
|
2556
|
-
});
|
|
2557
|
-
})).pipe(provide$1([layer$3, layer$4.pipe(provide$1(SqliteLayer(options.database ?? ".clanka/search.sqlite")))]));
|
|
2558
|
-
export { SemanticSearch, chunkEmbeddingInput, layer, makeEmbeddingResolver, maybeRemoveFile, maybeUpdateFile };
|