@yangda611/dsh-scriptor 8.4.1 → 8.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/README.md +10 -11
  2. package/THIRD_PARTY_NOTICES.md +1 -0
  3. package/cordis.patch.yml +8 -0
  4. package/lib/cli.js +3975 -553
  5. package/lib/client.js +141 -80
  6. package/lib/graph.js +1090 -0
  7. package/lib/index.js +9023 -4570
  8. package/lib/reranking.js +1155 -0
  9. package/lib/retrieval.js +1368 -0
  10. package/lib/scenes.js +1157 -0
  11. package/licenses/deepseek-ai__dsh-credentials--0.2.2-rc.1.txt +26 -0
  12. package/package.json +18 -4
  13. package/skills/novel-design/SKILL.md +14 -4
  14. package/skills/novel-director/SKILL.md +2 -0
  15. package/skills/novel-export/SKILL.md +11 -0
  16. package/skills/novel-export/scripts//345/211/247/346/234/254/345/257/274/345/207/272.mjs +22 -0
  17. package/skills/novel-inspiration/SKILL.md +12 -2
  18. package/skills/novel-screenplay/SKILL.md +93 -0
  19. package/skills/novel-screenplay/scripts//345/211/247/346/234/254/346/240/274/345/274/217/346/243/200/346/237/245.mjs +28 -0
  20. package/skills/novel-screenplay//345/272/225/346/234/254//345/205/250/351/207/217/345/256/241/350/257/273.md +40 -0
  21. package/skills/novel-screenplay//345/272/225/346/234/254//345/211/247/346/234/254/345/234/272/346/254/241/345/256/214/346/225/264/346/200/247/345/256/241/350/257/273.md +52 -0
  22. package/skills/novel-screenplay//345/272/225/346/234/254//345/211/247/346/234/254/345/257/271/347/231/275/345/256/241/350/257/273.md +54 -0
  23. package/skills/novel-screenplay//345/272/225/346/234/254//345/211/247/346/234/254/350/212/202/345/245/217/345/256/241/350/257/273.md +51 -0
  24. package/skills/novel-shortdrama/SKILL.md +69 -0
  25. package/skills/novel-shortdrama//345/267/245/345/272/217//345/210/206/351/233/206/345/244/247/347/272/262.md +32 -0
  26. package/skills/novel-shortdrama//345/267/245/345/272/217//345/215/225/351/233/206/345/211/247/346/234/254.md +31 -0
  27. package/skills/novel-shortdrama//345/272/225/346/234/254//347/237/255/345/211/247/345/256/241/350/257/273.md +68 -0
@@ -0,0 +1,1368 @@
1
+ import { createRequire as __createRequire } from 'node:module'
2
+ const require = __createRequire(import.meta.url)
3
+
4
+ // ../embedding-provider/src/index.ts
5
+ import { Service as Service2 } from "@deepseek-ai/cordis";
6
+
7
+ // ../../node_modules/.pnpm/@deepseek-ai+dsh-credentials@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-credentials/lib/index.js
8
+ import { Service } from "@deepseek-ai/cordis";
9
+
10
+ // ../../node_modules/.pnpm/@deepseek-ai+dsh-brand@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-brand/lib/index.js
11
+ function brandString(value) {
12
+ return value;
13
+ }
14
+
15
+ // ../../node_modules/.pnpm/@deepseek-ai+dsh-credentials@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-credentials/lib/index.js
16
+ var REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
17
+ function credentialRef(value) {
18
+ if (!isCredentialRefName(value)) throw new TypeError(`credential ref "${value}" must match ${String(REF_PATTERN)}`);
19
+ return brandString(value);
20
+ }
21
+ function isCredentialRefName(value) {
22
+ return REF_PATTERN.test(value);
23
+ }
24
+
25
+ // ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.9.0/node_modules/@deepseek-ai/cosmokit/lib/index.js
26
+ function isNullable(value) {
27
+ return value === null || value === void 0;
28
+ }
29
+ function isPlainObject(data) {
30
+ return data && typeof data === "object" && !Array.isArray(data);
31
+ }
32
+ function filterKeys(object2, filter) {
33
+ return Object.fromEntries(Object.entries(object2).filter(([key, value]) => filter(key, value)));
34
+ }
35
+ function mapValues(object2, transform) {
36
+ return Object.fromEntries(Object.entries(object2).map(([key, value]) => [key, transform(value, key)]));
37
+ }
38
+ function pick(source, keys, forced) {
39
+ if (!keys) return { ...source };
40
+ const result = {};
41
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
42
+ return result;
43
+ }
44
+ var write = /* @__PURE__ */ Symbol.for("cosmokit.volatile.write");
45
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
46
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
47
+ if (value === null || typeof value !== "object") return value;
48
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
49
+ ancestors.add(value);
50
+ try {
51
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
52
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
53
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
54
+ } finally {
55
+ ancestors.delete(value);
56
+ }
57
+ }
58
+ function createVolatile(value) {
59
+ let current = snapshot(value);
60
+ return Object.freeze({
61
+ get: () => current,
62
+ [write]: (value2) => {
63
+ current = value2;
64
+ }
65
+ });
66
+ }
67
+ function isVolatile(value) {
68
+ return typeof value === "object" && value !== null && write in value;
69
+ }
70
+ function is(type, value) {
71
+ if (arguments.length === 1) return (value2) => is(type, value2);
72
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
73
+ }
74
+ function isArrayBufferLike(value) {
75
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
76
+ }
77
+ function isArrayBufferSource(value) {
78
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
79
+ }
80
+ var Binary;
81
+ (function(Binary2) {
82
+ Binary2.is = isArrayBufferLike;
83
+ Binary2.isSource = isArrayBufferSource;
84
+ function fromSource(source) {
85
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
86
+ else return source;
87
+ }
88
+ Binary2.fromSource = fromSource;
89
+ function toBase64(source) {
90
+ source = fromSource(source);
91
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
92
+ let binary = "";
93
+ const bytes = new Uint8Array(source);
94
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
95
+ return btoa(binary);
96
+ }
97
+ Binary2.toBase64 = toBase64;
98
+ function fromBase64(source) {
99
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
100
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
101
+ }
102
+ Binary2.fromBase64 = fromBase64;
103
+ function toHex(source) {
104
+ source = fromSource(source);
105
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
106
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
107
+ }
108
+ Binary2.toHex = toHex;
109
+ function fromHex(source) {
110
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
111
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
112
+ const buffer = [];
113
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
114
+ return Uint8Array.from(buffer).buffer;
115
+ }
116
+ Binary2.fromHex = fromHex;
117
+ })(Binary || (Binary = {}));
118
+ var base64ToArrayBuffer = Binary.fromBase64;
119
+ var arrayBufferToBase64 = Binary.toBase64;
120
+ var hexToArrayBuffer = Binary.fromHex;
121
+ var arrayBufferToHex = Binary.toHex;
122
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
123
+ if (!source || typeof source !== "object") return source;
124
+ if (is("Date", source)) return new Date(source.valueOf());
125
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
126
+ if (isArrayBufferLike(source)) return source.slice(0);
127
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
128
+ const cached = refs.get(source);
129
+ if (cached) return cached;
130
+ if (Array.isArray(source)) {
131
+ const result2 = [];
132
+ refs.set(source, result2);
133
+ source.forEach((value, index) => {
134
+ result2[index] = Reflect.apply(clone, null, [value, refs]);
135
+ });
136
+ return result2;
137
+ }
138
+ const result = Object.create(Object.getPrototypeOf(source));
139
+ refs.set(source, result);
140
+ for (const key of Reflect.ownKeys(source)) {
141
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
142
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
143
+ Reflect.defineProperty(result, key, descriptor);
144
+ }
145
+ return result;
146
+ }
147
+ function deepEqual(a, b, strict) {
148
+ const ancestors = /* @__PURE__ */ new Set();
149
+ function compare(a2, b2) {
150
+ if (a2 === b2) return true;
151
+ if (isVolatile(a2) || isVolatile(b2)) return isVolatile(a2) && isVolatile(b2);
152
+ if (!strict && isNullable(a2) && isNullable(b2)) return true;
153
+ if (typeof a2 !== typeof b2 || typeof a2 !== "object" || !a2 || !b2) return false;
154
+ if (ancestors.has(a2)) return false;
155
+ function check(test, then) {
156
+ return test(a2) ? test(b2) ? then(a2, b2) : false : test(b2) ? false : void 0;
157
+ }
158
+ ancestors.add(a2);
159
+ try {
160
+ return check(Array.isArray, (a3, b3) => {
161
+ if (a3.length !== b3.length) return false;
162
+ for (let index = 0; index < a3.length; index++) if (!compare(a3[index], b3[index])) return false;
163
+ return true;
164
+ }) ?? check(is("Date"), (a3, b3) => a3.valueOf() === b3.valueOf()) ?? check(is("URL"), (a3, b3) => a3.href === b3.href) ?? check(is("RegExp"), (a3, b3) => a3.source === b3.source && a3.flags === b3.flags) ?? check(isArrayBufferLike, (a3, b3) => {
165
+ if (a3.byteLength !== b3.byteLength) return false;
166
+ const viewA = new Uint8Array(a3);
167
+ const viewB = new Uint8Array(b3);
168
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
169
+ return true;
170
+ }) ?? ((!strict || [a2, b2].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
171
+ ...a2,
172
+ ...b2
173
+ }).every((key) => compare(a2[key], b2[key])));
174
+ } finally {
175
+ ancestors.delete(a2);
176
+ }
177
+ }
178
+ return compare(a, b);
179
+ }
180
+ var Time;
181
+ (function(Time2) {
182
+ Time2.millisecond = 1;
183
+ Time2.second = 1e3;
184
+ Time2.minute = Time2.second * 60;
185
+ Time2.hour = Time2.minute * 60;
186
+ Time2.day = Time2.hour * 24;
187
+ Time2.week = Time2.day * 7;
188
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
189
+ function setTimezoneOffset(offset) {
190
+ timezoneOffset = offset;
191
+ }
192
+ Time2.setTimezoneOffset = setTimezoneOffset;
193
+ function getTimezoneOffset() {
194
+ return timezoneOffset;
195
+ }
196
+ Time2.getTimezoneOffset = getTimezoneOffset;
197
+ function getDateNumber(date2 = /* @__PURE__ */ new Date(), offset) {
198
+ if (typeof date2 === "number") date2 = new Date(date2);
199
+ if (offset === void 0) offset = timezoneOffset;
200
+ return Math.floor((date2.valueOf() / Time2.minute - offset) / 1440);
201
+ }
202
+ Time2.getDateNumber = getDateNumber;
203
+ function fromDateNumber(value, offset) {
204
+ const date2 = new Date(value * Time2.day);
205
+ if (offset === void 0) offset = timezoneOffset;
206
+ return new Date(+date2 + offset * Time2.minute);
207
+ }
208
+ Time2.fromDateNumber = fromDateNumber;
209
+ const numeric = /\d+(?:\.\d+)?/.source;
210
+ const timeRegExp = new RegExp(`^${[
211
+ "w(?:eek(?:s)?)?",
212
+ "d(?:ay(?:s)?)?",
213
+ "h(?:our(?:s)?)?",
214
+ "m(?:in(?:ute)?(?:s)?)?",
215
+ "s(?:ec(?:ond)?(?:s)?)?"
216
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
217
+ function parseTime(source) {
218
+ const capture = timeRegExp.exec(source);
219
+ if (!capture) return 0;
220
+ return (parseFloat(capture[1]) * Time2.week || 0) + (parseFloat(capture[2]) * Time2.day || 0) + (parseFloat(capture[3]) * Time2.hour || 0) + (parseFloat(capture[4]) * Time2.minute || 0) + (parseFloat(capture[5]) * Time2.second || 0);
221
+ }
222
+ Time2.parseTime = parseTime;
223
+ function parseDate(date2) {
224
+ const parsed = parseTime(date2);
225
+ if (parsed) date2 = Date.now() + parsed;
226
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date2}`;
227
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date2}`;
228
+ return date2 ? new Date(date2) : /* @__PURE__ */ new Date();
229
+ }
230
+ Time2.parseDate = parseDate;
231
+ function format(ms) {
232
+ const abs = Math.abs(ms);
233
+ if (abs >= Time2.day - Time2.hour / 2) return Math.round(ms / Time2.day) + "d";
234
+ else if (abs >= Time2.hour - Time2.minute / 2) return Math.round(ms / Time2.hour) + "h";
235
+ else if (abs >= Time2.minute - Time2.second / 2) return Math.round(ms / Time2.minute) + "m";
236
+ else if (abs >= Time2.second) return Math.round(ms / Time2.second) + "s";
237
+ return ms + "ms";
238
+ }
239
+ Time2.format = format;
240
+ function toDigits(source, length = 2) {
241
+ return source.toString().padStart(length, "0");
242
+ }
243
+ Time2.toDigits = toDigits;
244
+ function template(template2, time = /* @__PURE__ */ new Date()) {
245
+ return template2.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
246
+ }
247
+ Time2.template = template;
248
+ })(Time || (Time = {}));
249
+
250
+ // ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.19.0/node_modules/@deepseek-ai/schemastery/lib/index.mjs
251
+ var kSchema = /* @__PURE__ */ Symbol.for("schemastery");
252
+ var kValidationError = /* @__PURE__ */ Symbol.for("ValidationError");
253
+ globalThis.__schemastery_index__ ??= 0;
254
+ globalThis.__schemastery_refs__ = void 0;
255
+ var ValidationError = class extends TypeError {
256
+ options;
257
+ name = "ValidationError";
258
+ constructor(message, options) {
259
+ let prefix = "$";
260
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
261
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
262
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
263
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
264
+ super((prefix === "$" ? "" : `${prefix} `) + message);
265
+ this.options = options;
266
+ }
267
+ static is(error) {
268
+ return !!error?.[kValidationError];
269
+ }
270
+ };
271
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
272
+ var Schema = function(options) {
273
+ const schema = function(data, options2 = {}) {
274
+ return Schema.resolve(data, schema, options2)[0];
275
+ };
276
+ if (options.refs) {
277
+ const refs = mapValues(options.refs, (options2) => new Schema(options2));
278
+ const getRef = (uid) => refs[uid];
279
+ for (const key in refs) {
280
+ const options2 = refs[key];
281
+ options2.sKey = getRef(options2.sKey);
282
+ options2.inner = getRef(options2.inner);
283
+ options2.list = options2.list && options2.list.map(getRef);
284
+ options2.dict = options2.dict && mapValues(options2.dict, getRef);
285
+ }
286
+ return refs[options.uid];
287
+ }
288
+ Object.assign(schema, options);
289
+ if (typeof schema.callback === "string") try {
290
+ schema.callback = new Function("return " + schema.callback)();
291
+ } catch {
292
+ }
293
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
294
+ Object.setPrototypeOf(schema, Schema.prototype);
295
+ schema.meta ||= {};
296
+ schema.toString = schema.toString.bind(schema);
297
+ return schema;
298
+ };
299
+ Schema.prototype = Object.create(Function.prototype);
300
+ Schema.prototype[kSchema] = true;
301
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
302
+ return {
303
+ version: 1,
304
+ vendor: "schemastery",
305
+ validate: (value) => {
306
+ try {
307
+ return { value: Schema.resolve(value, this, {})[0] };
308
+ } catch (error) {
309
+ if (ValidationError.is(error)) return { issues: [{
310
+ message: error.message,
311
+ path: error.options.path
312
+ }] };
313
+ throw error;
314
+ }
315
+ }
316
+ };
317
+ } });
318
+ Schema.ValidationError = ValidationError;
319
+ Schema.prototype.toJSON = function toJSON() {
320
+ if (globalThis.__schemastery_refs__) {
321
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
322
+ return this.uid;
323
+ }
324
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
325
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
326
+ const result = {
327
+ uid: this.uid,
328
+ refs: globalThis.__schemastery_refs__
329
+ };
330
+ globalThis.__schemastery_refs__ = void 0;
331
+ return result;
332
+ };
333
+ Schema.prototype.set = function set(key, value) {
334
+ this.dict[key] = value;
335
+ return this;
336
+ };
337
+ Schema.prototype.push = function push(value) {
338
+ this.list.push(value);
339
+ return this;
340
+ };
341
+ function mergeDesc(original, messages) {
342
+ const result = typeof original === "string" ? { "": original } : { ...original };
343
+ for (const locale in messages) {
344
+ const value = messages[locale];
345
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
346
+ else if (typeof value === "string") result[locale] = value;
347
+ }
348
+ return result;
349
+ }
350
+ function getInner(value) {
351
+ return value?.$value ?? value?.$inner;
352
+ }
353
+ function extractKeys(data) {
354
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
355
+ }
356
+ Schema.prototype.i18n = function i18n(messages) {
357
+ const schema = Schema(this);
358
+ const desc = mergeDesc(schema.meta.description, messages);
359
+ if (Object.keys(desc).length) schema.meta.description = desc;
360
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
361
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
362
+ });
363
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
364
+ return inner.i18n(mapValues(messages, (data = {}) => {
365
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
366
+ if (Array.isArray(data)) return data[index];
367
+ return extractKeys(data);
368
+ }));
369
+ });
370
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
371
+ if (getInner(data)) return getInner(data);
372
+ return extractKeys(data);
373
+ }));
374
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
375
+ return schema;
376
+ };
377
+ Schema.prototype.extra = function extra(key, value) {
378
+ const schema = Schema(this);
379
+ schema.meta = {
380
+ ...schema.meta,
381
+ [key]: value
382
+ };
383
+ return schema;
384
+ };
385
+ for (const key of [
386
+ "required",
387
+ "disabled",
388
+ "collapse",
389
+ "hidden",
390
+ "loose"
391
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
392
+ const schema = Schema(this);
393
+ schema.meta = {
394
+ ...schema.meta,
395
+ [key]: value
396
+ };
397
+ return schema;
398
+ } });
399
+ Schema.prototype.deprecated = function deprecated() {
400
+ const schema = Schema(this);
401
+ schema.meta.badges ||= [];
402
+ schema.meta.badges.push({
403
+ text: "deprecated",
404
+ type: "danger"
405
+ });
406
+ return schema;
407
+ };
408
+ Schema.prototype.experimental = function experimental() {
409
+ const schema = Schema(this);
410
+ schema.meta.badges ||= [];
411
+ schema.meta.badges.push({
412
+ text: "experimental",
413
+ type: "warning"
414
+ });
415
+ return schema;
416
+ };
417
+ Schema.prototype.pattern = function pattern(regexp) {
418
+ const schema = Schema(this);
419
+ const pattern2 = pick(regexp, ["source", "flags"]);
420
+ schema.meta = {
421
+ ...schema.meta,
422
+ pattern: pattern2
423
+ };
424
+ return schema;
425
+ };
426
+ Schema.prototype.simplify = function simplify(value) {
427
+ if (isVolatile(value)) value = value.get();
428
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
429
+ if (isNullable(value)) return value;
430
+ if (this.type === "object" || this.type === "dict") {
431
+ const result = {};
432
+ for (const key in value) {
433
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
434
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
435
+ }
436
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
437
+ return result;
438
+ } else if (this.type === "array" || this.type === "tuple") {
439
+ const result = [];
440
+ value.forEach((value2, index) => {
441
+ const schema = this.type === "array" ? this.inner : this.list[index];
442
+ const item = schema ? schema.simplify(value2) : value2;
443
+ result.push(item);
444
+ });
445
+ return result;
446
+ } else if (this.type === "intersect") {
447
+ const result = {};
448
+ for (const item of this.list) Object.assign(result, item.simplify(value));
449
+ return result;
450
+ } else if (this.type === "union") for (const schema of this.list) try {
451
+ Schema.resolve(value, schema, {});
452
+ return schema.simplify(value);
453
+ } catch {
454
+ }
455
+ return value;
456
+ };
457
+ Schema.prototype.toString = function toString(inline) {
458
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
459
+ };
460
+ Schema.prototype.role = function role(role, extra2) {
461
+ const schema = Schema(this);
462
+ schema.meta = {
463
+ ...schema.meta,
464
+ role,
465
+ extra: extra2
466
+ };
467
+ return schema;
468
+ };
469
+ for (const key of [
470
+ "default",
471
+ "link",
472
+ "comment",
473
+ "description",
474
+ "max",
475
+ "min",
476
+ "step"
477
+ ]) Object.assign(Schema.prototype, { [key](value) {
478
+ const schema = Schema(this);
479
+ schema.meta = {
480
+ ...schema.meta,
481
+ [key]: value
482
+ };
483
+ return schema;
484
+ } });
485
+ Schema.prototype.volatile = function volatile() {
486
+ if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
487
+ return this.extra("volatile", true);
488
+ };
489
+ var resolvers = {};
490
+ var checkedVolatile = /* @__PURE__ */ Symbol("checked-volatile-schema");
491
+ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
492
+ const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
493
+ if (states.has(blocked)) return;
494
+ states.add(blocked);
495
+ seen.set(schema, states);
496
+ if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
497
+ const nested = blocked || !!schema.meta?.volatile;
498
+ if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
499
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
500
+ if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
501
+ if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
502
+ }
503
+ Schema.extend = function extend(type, resolve2) {
504
+ resolvers[type] = resolve2;
505
+ };
506
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
507
+ if (!schema) return [data];
508
+ if (!options[checkedVolatile]) {
509
+ validateVolatileSchema(schema, options.path);
510
+ options = {
511
+ ...options,
512
+ [checkedVolatile]: true
513
+ };
514
+ }
515
+ if (schema.meta?.volatile) {
516
+ const inner = Schema(schema);
517
+ inner.meta = {
518
+ ...schema.meta,
519
+ volatile: false
520
+ };
521
+ const [value, adapted] = Schema.resolve(data, inner, options, strict);
522
+ try {
523
+ return [createVolatile(value), adapted];
524
+ } catch (error) {
525
+ throw new ValidationError(error instanceof Error ? error.message : String(error), options);
526
+ }
527
+ }
528
+ if (options.ignore?.(data, schema)) return [data];
529
+ if (isNullable(data) && schema.type !== "lazy") {
530
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
531
+ let current = schema;
532
+ let fallback = schema.meta.default;
533
+ while (current?.type === "intersect" && isNullable(fallback)) {
534
+ current = current.list[0];
535
+ fallback = current?.meta.default;
536
+ }
537
+ if (isNullable(fallback)) return [data];
538
+ data = clone(fallback);
539
+ }
540
+ const callback = resolvers[schema.type];
541
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
542
+ try {
543
+ return callback(data, schema, options, strict);
544
+ } catch (error) {
545
+ if (!schema.meta.loose) throw error;
546
+ return [schema.meta.default];
547
+ }
548
+ };
549
+ Schema.from = function from(source) {
550
+ if (isNullable(source)) return Schema.any();
551
+ else if ([
552
+ "string",
553
+ "number",
554
+ "boolean"
555
+ ].includes(typeof source)) return Schema.const(source).required();
556
+ else if (source[kSchema]) return source;
557
+ else if (typeof source === "function") switch (source) {
558
+ case String:
559
+ return Schema.string().required();
560
+ case Number:
561
+ return Schema.number().required();
562
+ case Boolean:
563
+ return Schema.boolean().required();
564
+ case Function:
565
+ return Schema.function().required();
566
+ default:
567
+ return Schema.is(source).required();
568
+ }
569
+ else throw new TypeError(`cannot infer schema from ${source}`);
570
+ };
571
+ Schema.lazy = function lazy(builder) {
572
+ const toJSON2 = () => {
573
+ if (!schema.inner[kSchema]) {
574
+ schema.inner = schema.builder();
575
+ schema.inner.meta = {
576
+ ...schema.meta,
577
+ ...schema.inner.meta
578
+ };
579
+ }
580
+ return schema.inner.toJSON();
581
+ };
582
+ const schema = new Schema({
583
+ type: "lazy",
584
+ builder,
585
+ inner: { toJSON: toJSON2 }
586
+ });
587
+ return schema;
588
+ };
589
+ Schema.natural = function natural() {
590
+ return Schema.number().step(1).min(0);
591
+ };
592
+ Schema.percent = function percent() {
593
+ return Schema.number().step(0.01).min(0).max(1).role("slider");
594
+ };
595
+ Schema.date = function date() {
596
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
597
+ const date2 = new Date(value);
598
+ if (isNaN(+date2)) throw new ValidationError(`invalid date "${value}"`, options);
599
+ return date2;
600
+ }, true)]);
601
+ };
602
+ Schema.regExp = function regExp(flag = "") {
603
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
604
+ try {
605
+ return new RegExp(value, flag);
606
+ } catch (e) {
607
+ throw new ValidationError(e.message, options);
608
+ }
609
+ }, true)]);
610
+ };
611
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
612
+ return Schema.union([
613
+ Schema.is(ArrayBuffer),
614
+ Schema.is(SharedArrayBuffer),
615
+ Schema.transform(Schema.any(), (value, options) => {
616
+ if (Binary.isSource(value)) return Binary.fromSource(value);
617
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
618
+ }, true),
619
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
620
+ try {
621
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
622
+ } catch (e) {
623
+ throw new ValidationError(e.message, options);
624
+ }
625
+ }, true)] : []
626
+ ]);
627
+ };
628
+ Schema.extend("lazy", (data, schema, options, strict) => {
629
+ if (!schema.inner[kSchema]) {
630
+ schema.inner = schema.builder();
631
+ schema.inner.meta = {
632
+ ...schema.meta,
633
+ ...schema.inner.meta
634
+ };
635
+ validateVolatileSchema(schema.inner, options.path, true);
636
+ }
637
+ return Schema.resolve(data, schema.inner, options, strict);
638
+ });
639
+ Schema.extend("any", (data) => {
640
+ return [data];
641
+ });
642
+ Schema.extend("never", (data, _, options) => {
643
+ throw new ValidationError(`expected nullable but got ${data}`, options);
644
+ });
645
+ Schema.extend("const", (data, { value }, options) => {
646
+ if (deepEqual(data, value)) return [value];
647
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
648
+ });
649
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
650
+ const { max = Infinity, min = -Infinity } = meta;
651
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
652
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
653
+ }
654
+ Schema.extend("string", (data, { meta }, options) => {
655
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
656
+ if (meta.pattern) {
657
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
658
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
659
+ }
660
+ checkWithinRange(data.length, meta, "string length", options);
661
+ return [data];
662
+ });
663
+ function decimalShift(data, digits) {
664
+ const str = data.toString();
665
+ if (str.includes("e")) return data * Math.pow(10, digits);
666
+ const index = str.indexOf(".");
667
+ if (index === -1) return data * Math.pow(10, digits);
668
+ const frac = str.slice(index + 1);
669
+ const integer = str.slice(0, index);
670
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
671
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
672
+ }
673
+ function isMultipleOf(data, min, step) {
674
+ step = Math.abs(step);
675
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
676
+ const index = step.toString().indexOf(".");
677
+ const digits = step.toString().slice(index + 1).length;
678
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
679
+ }
680
+ Schema.extend("number", (data, { meta }, options) => {
681
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
682
+ checkWithinRange(data, meta, "number", options);
683
+ const { step } = meta;
684
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
685
+ return [data];
686
+ });
687
+ Schema.extend("boolean", (data, _, options) => {
688
+ if (typeof data === "boolean") return [data];
689
+ throw new ValidationError(`expected boolean but got ${data}`, options);
690
+ });
691
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
692
+ let value = 0, keys = [];
693
+ if (typeof data === "number") {
694
+ value = data;
695
+ for (const key in bits) if (data & bits[key]) keys.push(key);
696
+ } else if (Array.isArray(data)) {
697
+ keys = data;
698
+ for (const key of keys) {
699
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
700
+ if (key in bits) value |= bits[key];
701
+ }
702
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
703
+ if (value === meta.default) return [value];
704
+ return [value, keys];
705
+ });
706
+ Schema.extend("function", (data, _, options) => {
707
+ if (typeof data === "function") return [data];
708
+ throw new ValidationError(`expected function but got ${data}`, options);
709
+ });
710
+ Schema.extend("is", (data, { constructor }, options) => {
711
+ if (typeof constructor === "function") {
712
+ if (data instanceof constructor) return [data];
713
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
714
+ } else {
715
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
716
+ let prototype = Object.getPrototypeOf(data);
717
+ while (prototype) {
718
+ if (prototype.constructor?.name === constructor) return [data];
719
+ prototype = Object.getPrototypeOf(prototype);
720
+ }
721
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
722
+ }
723
+ });
724
+ function property(data, key, schema, options) {
725
+ try {
726
+ const [value, adapted] = Schema.resolve(data[key], schema, {
727
+ ...options,
728
+ path: [...options.path || [], key]
729
+ });
730
+ if (adapted !== void 0) data[key] = adapted;
731
+ return value;
732
+ } catch (e) {
733
+ if (!options?.autofix) throw e;
734
+ delete data[key];
735
+ return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
736
+ }
737
+ }
738
+ Schema.extend("array", (data, { inner, meta }, options) => {
739
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
740
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
741
+ return [data.map((_, index) => property(data, index, inner, options))];
742
+ });
743
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
744
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
745
+ const result = {};
746
+ for (const key in data) {
747
+ let rKey;
748
+ try {
749
+ rKey = Schema.resolve(key, sKey, options)[0];
750
+ } catch (error) {
751
+ if (strict) continue;
752
+ throw error;
753
+ }
754
+ result[rKey] = property(data, key, inner, options);
755
+ data[rKey] = data[key];
756
+ if (key !== rKey) delete data[key];
757
+ }
758
+ return [result];
759
+ });
760
+ Schema.extend("tuple", (data, { list }, options, strict) => {
761
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
762
+ const result = list.map((inner, index) => property(data, index, inner, options));
763
+ if (strict) return [result];
764
+ result.push(...data.slice(list.length));
765
+ return [result];
766
+ });
767
+ function merge(result, data) {
768
+ for (const key in data) {
769
+ if (key in result) continue;
770
+ result[key] = data[key];
771
+ }
772
+ }
773
+ Schema.extend("object", (data, { dict }, options, strict) => {
774
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
775
+ const result = {};
776
+ for (const key in dict) {
777
+ const value = property(data, key, dict[key], options);
778
+ if (!isNullable(value) || key in data) result[key] = value;
779
+ }
780
+ if (!strict) merge(result, data);
781
+ return [result];
782
+ });
783
+ Schema.extend("union", (data, { list, toString: toString2 }, options, strict) => {
784
+ const messages = [];
785
+ for (const inner of list) try {
786
+ return Schema.resolve(data, inner, options, strict);
787
+ } catch (error) {
788
+ messages.push(error);
789
+ }
790
+ throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
791
+ });
792
+ Schema.extend("intersect", (data, { list, toString: toString2 }, options, strict) => {
793
+ if (!list.length) return [data];
794
+ let result;
795
+ for (const inner of list) {
796
+ const value = Schema.resolve(data, inner, options, true)[0];
797
+ if (isNullable(value)) continue;
798
+ if (isNullable(result)) result = value;
799
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
800
+ else if (typeof value === "object") merge(result ??= {}, value);
801
+ else if (result !== value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
802
+ }
803
+ if (!strict && isPlainObject(data)) merge(result, data);
804
+ return [result];
805
+ });
806
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
807
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
808
+ if (preserve) return [callback(result)];
809
+ else return [callback(result), callback(adapted)];
810
+ });
811
+ var formatters = {};
812
+ function defineMethod(name2, keys, format) {
813
+ formatters[name2] = format;
814
+ Object.assign(Schema, { [name2](...args) {
815
+ const schema = new Schema({ type: name2 });
816
+ keys.forEach((key, index) => {
817
+ switch (key) {
818
+ case "sKey":
819
+ schema.sKey = args[index] ?? Schema.string();
820
+ break;
821
+ case "inner":
822
+ schema.inner = Schema.from(args[index]);
823
+ break;
824
+ case "list":
825
+ schema.list = args[index].map(Schema.from);
826
+ break;
827
+ case "dict":
828
+ schema.dict = mapValues(args[index], Schema.from);
829
+ break;
830
+ case "bits":
831
+ schema.bits = {};
832
+ for (const key2 in args[index]) {
833
+ if (typeof args[index][key2] !== "number") continue;
834
+ schema.bits[key2] = args[index][key2];
835
+ }
836
+ break;
837
+ case "callback": {
838
+ const callback = schema.callback = args[index];
839
+ callback["toJSON"] ||= () => callback.toString();
840
+ break;
841
+ }
842
+ case "constructor": {
843
+ const constructor = schema.constructor = args[index];
844
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
845
+ break;
846
+ }
847
+ default:
848
+ schema[key] = args[index];
849
+ }
850
+ });
851
+ if (name2 === "object" || name2 === "dict") schema.meta.default = {};
852
+ else if (name2 === "array" || name2 === "tuple") schema.meta.default = [];
853
+ else if (name2 === "bitset") schema.meta.default = 0;
854
+ return schema;
855
+ } });
856
+ }
857
+ defineMethod("is", ["constructor"], ({ constructor }) => {
858
+ if (typeof constructor === "function") return constructor.name;
859
+ else return constructor;
860
+ });
861
+ defineMethod("any", [], () => "any");
862
+ defineMethod("never", [], () => "never");
863
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
864
+ defineMethod("string", [], () => "string");
865
+ defineMethod("number", [], () => "number");
866
+ defineMethod("boolean", [], () => "boolean");
867
+ defineMethod("bitset", ["bits"], () => "bitset");
868
+ defineMethod("function", [], () => "function");
869
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
870
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
871
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
872
+ defineMethod("object", ["dict"], ({ dict }) => {
873
+ if (Object.keys(dict).length === 0) return "{}";
874
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
875
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
876
+ }).join(", ")} }`;
877
+ });
878
+ defineMethod("union", ["list"], ({ list }, inline) => {
879
+ const result = list.map(({ toString: format }) => format()).join(" | ");
880
+ return inline ? `(${result})` : result;
881
+ });
882
+ defineMethod("intersect", ["list"], ({ list }) => {
883
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
884
+ });
885
+ defineMethod("transform", [
886
+ "inner",
887
+ "callback",
888
+ "preserve"
889
+ ], ({ inner }, isInner) => inner.toString(isInner));
890
+
891
+ // ../embedding-provider/src/config.ts
892
+ var DEFAULT_CREDENTIAL = "WEBNOVEL_EMBEDDING_API_KEY";
893
+ var Config = Schema.object({
894
+ enabled: Schema.boolean().default(false).description("\u542F\u7528\u8BED\u4E49\u68C0\u7D22\uFF1B\u540E\u53F0\u7D22\u5F15\u5411\u6240\u914D\u7F6E\u670D\u52A1\u53D1\u9001\u5DF2\u542F\u7528\u4E66\u4ED3\u7684\u5B9A\u7A3F\u7247\u6BB5\uFF0C\u68C0\u7D22\u65F6\u53D1\u9001\u67E5\u8BE2"),
895
+ protocol: Schema.union(["openai-compatible", "gemini-native"]).default("openai-compatible").description("\u5D4C\u5165 API \u534F\u8BAE"),
896
+ baseURL: Schema.string().description("API \u57FA\u7840\u5730\u5740"),
897
+ model: Schema.string().description("\u5411\u91CF\u6A21\u578B\u540D\u79F0"),
898
+ dimensions: Schema.number().step(1).min(1).max(65536).description("\u5411\u91CF\u7EF4\u5EA6\uFF0C\u542F\u7528\u524D\u5FC5\u586B\uFF1B\u7528\u4E8E\u8BF7\u6C42\u548C\u54CD\u5E94\u6821\u9A8C"),
899
+ apiKeyEnv: Schema.string().role("credential-ref").default(DEFAULT_CREDENTIAL),
900
+ batchSize: Schema.number().step(1).min(1).max(128).default(32),
901
+ timeoutMs: Schema.number().step(1).min(100).max(12e4).default(3e4),
902
+ maxRetries: Schema.number().step(1).min(0).max(3).default(2),
903
+ sendDimensions: Schema.boolean().default(true).description("\u5C06\u914D\u7F6E\u7EF4\u5EA6\u53D1\u9001\u7ED9 API\uFF1B\u56FA\u5B9A\u7EF4\u5EA6\u63A5\u53E3\u53EF\u5173\u95ED\uFF0C\u54CD\u5E94\u4ECD\u4E25\u683C\u6821\u9A8C"),
904
+ documentPrefix: Schema.string().default(""),
905
+ queryPrefix: Schema.string().default(""),
906
+ geminiTaskMode: Schema.union(["native", "instruction"]).default("native")
907
+ });
908
+ function resolveSettings(input) {
909
+ if (!input.enabled) return void 0;
910
+ if (!input.baseURL?.trim() || !input.model?.trim()) throw new Error("\u542F\u7528\u524D\u8BF7\u586B\u5199 API \u5730\u5740\u548C\u5411\u91CF\u6A21\u578B");
911
+ let url;
912
+ try {
913
+ url = new URL(input.baseURL);
914
+ } catch {
915
+ throw new Error("\u5D4C\u5165 API \u5730\u5740\u65E0\u6548");
916
+ }
917
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
918
+ throw new Error("\u5D4C\u5165 API \u5730\u5740\u987B\u4E3A\u4E0D\u542B\u5BC6\u94A5\u3001\u67E5\u8BE2\u53C2\u6570\u6216\u7247\u6BB5\u7684 HTTP(S) \u5730\u5740");
919
+ }
920
+ if (url.protocol !== "https:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {
921
+ throw new Error("\u5916\u90E8\u5D4C\u5165\u670D\u52A1\u987B\u4F7F\u7528 HTTPS\uFF0C\u672C\u673A\u670D\u52A1\u53EF\u4F7F\u7528 HTTP");
922
+ }
923
+ const integer = (value, fallback, min, max, label) => {
924
+ const resolved = value ?? fallback;
925
+ if (!Number.isInteger(resolved) || resolved < min || resolved > max) throw new Error(`${label}\u987B\u4E3A ${min}\u2013${max} \u7684\u6574\u6570`);
926
+ return resolved;
927
+ };
928
+ const dimensions = integer(input.dimensions, 0, 1, 65536, "\u5411\u91CF\u7EF4\u5EA6");
929
+ const protocol = input.protocol ?? "openai-compatible";
930
+ if (protocol !== "openai-compatible" && protocol !== "gemini-native") throw new Error("\u4E0D\u652F\u6301\u7684\u5D4C\u5165 API \u534F\u8BAE");
931
+ const model = protocol === "gemini-native" ? input.model.trim().replace(/^models\//, "") : input.model.trim();
932
+ if (model.length > 200 || /[\r\n\0]/.test(model) || protocol === "gemini-native" && !/^[A-Za-z0-9._-]+$/.test(model)) {
933
+ throw new Error("\u5411\u91CF\u6A21\u578B\u540D\u79F0\u65E0\u6548");
934
+ }
935
+ const apiKeyEnv = input.apiKeyEnv ?? DEFAULT_CREDENTIAL;
936
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(apiKeyEnv)) throw new Error("\u51ED\u636E\u5F15\u7528\u540D\u79F0\u65E0\u6548");
937
+ if ((input.documentPrefix?.length ?? 0) > 4096 || (input.queryPrefix?.length ?? 0) > 4096) throw new Error("\u5D4C\u5165\u6307\u4EE4\u524D\u7F00\u8FC7\u957F");
938
+ if (input.geminiTaskMode !== void 0 && input.geminiTaskMode !== "native" && input.geminiTaskMode !== "instruction") throw new Error("Gemini \u89D2\u8272\u914D\u7F6E\u65E0\u6548");
939
+ return {
940
+ protocol,
941
+ baseURL: url.href.replace(/\/+$/, ""),
942
+ model,
943
+ dimensions,
944
+ apiKeyEnv,
945
+ batchSize: integer(input.batchSize, 32, 1, 128, "\u6279\u91CF\u5927\u5C0F"),
946
+ timeoutMs: integer(input.timeoutMs, 3e4, 100, 12e4, "\u8BF7\u6C42\u8D85\u65F6"),
947
+ maxRetries: integer(input.maxRetries, 2, 0, 3, "\u91CD\u8BD5\u6B21\u6570"),
948
+ sendDimensions: input.sendDimensions ?? true,
949
+ documentPrefix: input.documentPrefix ?? "",
950
+ queryPrefix: input.queryPrefix ?? "",
951
+ geminiTaskMode: input.geminiTaskMode ?? "native"
952
+ };
953
+ }
954
+
955
+ // ../embedding-provider/src/http.ts
956
+ import { createHash } from "node:crypto";
957
+ var EmbeddingError = class extends Error {
958
+ constructor(code, message, httpStatus, retryAfterMs) {
959
+ super(message);
960
+ this.code = code;
961
+ this.httpStatus = httpStatus;
962
+ this.retryAfterMs = retryAfterMs;
963
+ this.name = "EmbeddingError";
964
+ }
965
+ code;
966
+ httpStatus;
967
+ retryAfterMs;
968
+ };
969
+ function parseRetryAfter(value, now = Date.now()) {
970
+ if (!value?.trim()) return void 0;
971
+ const trimmed = value.trim();
972
+ const milliseconds = /^\d+(?:\.\d+)?$/.test(trimmed) ? Number(trimmed) * 1e3 : Date.parse(trimmed) - now;
973
+ return Number.isFinite(milliseconds) ? Math.max(0, Math.ceil(milliseconds)) : void 0;
974
+ }
975
+ var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
976
+ var MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
977
+ function abortable(promise, signal) {
978
+ return new Promise((resolve2, reject) => {
979
+ const abort = () => {
980
+ signal.removeEventListener("abort", abort);
981
+ reject(signal.reason);
982
+ };
983
+ signal.addEventListener("abort", abort, { once: true });
984
+ promise.then((value) => {
985
+ signal.removeEventListener("abort", abort);
986
+ resolve2(value);
987
+ }, (error) => {
988
+ signal.removeEventListener("abort", abort);
989
+ reject(error);
990
+ });
991
+ if (signal.aborted) abort();
992
+ });
993
+ }
994
+ var HttpEmbeddingProvider = class {
995
+ constructor(config, key) {
996
+ this.key = key;
997
+ this.config = Object.freeze({ ...config });
998
+ this.metadata = Object.freeze({
999
+ provider: config.protocol,
1000
+ model: config.model,
1001
+ dimensions: config.dimensions,
1002
+ batchSize: config.batchSize,
1003
+ revision: createHash("sha256").update(JSON.stringify([
1004
+ "embedding-protocol-v1",
1005
+ config.protocol,
1006
+ config.baseURL,
1007
+ config.model,
1008
+ config.dimensions,
1009
+ config.documentPrefix,
1010
+ config.queryPrefix,
1011
+ config.geminiTaskMode,
1012
+ config.sendDimensions
1013
+ ])).digest("hex")
1014
+ });
1015
+ }
1016
+ key;
1017
+ metadata;
1018
+ config;
1019
+ lifetime = new AbortController();
1020
+ pending = /* @__PURE__ */ new Set();
1021
+ async close() {
1022
+ this.lifetime.abort(new EmbeddingError("provider-changed", "\u5D4C\u5165\u63D0\u4F9B\u65B9\u5DF2\u505C\u7528\u6216\u914D\u7F6E\u5DF2\u53D8\u66F4"));
1023
+ await Promise.allSettled([...this.pending]);
1024
+ }
1025
+ embed(inputs, role2, signal) {
1026
+ const combined = AbortSignal.any([this.lifetime.signal, ...signal ? [signal] : []]);
1027
+ return this.track(this.run(inputs, role2, combined));
1028
+ }
1029
+ embedBatch(inputs, role2, signal) {
1030
+ const combined = AbortSignal.any([this.lifetime.signal, ...signal ? [signal] : []]);
1031
+ if (inputs.length > this.config.batchSize) return Promise.reject(new EmbeddingError("invalid-input", "\u5355\u6B21\u5D4C\u5165\u6279\u91CF\u8D85\u8FC7\u63D0\u4F9B\u65B9\u914D\u7F6E"));
1032
+ return this.track(this.run(inputs, role2, combined, 0));
1033
+ }
1034
+ track(operation) {
1035
+ this.pending.add(operation);
1036
+ void operation.then(() => this.pending.delete(operation), () => this.pending.delete(operation));
1037
+ return operation;
1038
+ }
1039
+ probeDimensions(signal) {
1040
+ const combined = AbortSignal.any([this.lifetime.signal, ...signal ? [signal] : []]);
1041
+ return this.track((async () => {
1042
+ const response = await this.request([{ text: "Embedding dimension check." }], "query", combined, true);
1043
+ return this.parse(response, 1, null)[0].length;
1044
+ })());
1045
+ }
1046
+ listModels(signal) {
1047
+ const combined = AbortSignal.any([this.lifetime.signal, ...signal ? [signal] : []]);
1048
+ return this.track((async () => {
1049
+ const models = /* @__PURE__ */ new Map();
1050
+ const cursors = /* @__PURE__ */ new Set();
1051
+ let cursor;
1052
+ for (let page = 0; page < 20; page++) {
1053
+ const url = new URL(this.config.baseURL.replace(/\/embeddings$/, "") + "/models");
1054
+ if (this.config.protocol === "gemini-native") {
1055
+ url.searchParams.set("pageSize", "1000");
1056
+ if (cursor) url.searchParams.set("pageToken", cursor);
1057
+ }
1058
+ const data = object(await this.send(url.href, "GET", void 0, this.config.protocol === "gemini-native" ? "x-goog-api-key" : "Authorization", combined));
1059
+ const raw = data?.data ?? data?.models;
1060
+ const rows = Array.isArray(raw) ? raw : object(raw) ? Object.entries(raw).map(([id, value]) => ({ ...object(value), id })) : void 0;
1061
+ if (!rows) throw new EmbeddingError("invalid-response", "\u670D\u52A1\u672A\u8FD4\u56DE\u53EF\u8BC6\u522B\u7684\u6A21\u578B\u5217\u8868\uFF0C\u53EF\u624B\u52A8\u586B\u5199\u6A21\u578B");
1062
+ for (const entry of rows) {
1063
+ const row = object(entry);
1064
+ if (!row) continue;
1065
+ const methods = row.supportedGenerationMethods;
1066
+ if (this.config.protocol === "gemini-native" && Array.isArray(methods) && !methods.some((method) => method === "embedContent" || method === "batchEmbedContents")) continue;
1067
+ const name2 = row.displayName ?? row.name;
1068
+ const rawId = row.id ?? row.name;
1069
+ if (typeof rawId !== "string" || !rawId || rawId.length > 200) continue;
1070
+ const id = this.config.protocol === "gemini-native" ? rawId.replace(/^models\//, "") : rawId;
1071
+ const validDimension = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65536;
1072
+ const declared = row.supported_dimensions ?? row.supportedDimensions ?? row.embedding_dimensions;
1073
+ const dimensions = Array.isArray(declared) && declared.length <= 64 && declared.every(validDimension) ? [...new Set(declared)] : void 0;
1074
+ const defaultValue = row.default_dimension ?? row.embedding_dimension ?? row.dimensions;
1075
+ models.set(id, { id, ...typeof name2 === "string" ? { name: name2 } : {}, ...dimensions?.length ? { dimensions } : {}, ...validDimension(defaultValue) ? { defaultDimension: defaultValue } : {} });
1076
+ if (models.size >= 5e3) return { models: [...models.values()], limited: true };
1077
+ }
1078
+ const next = data?.nextPageToken;
1079
+ if (this.config.protocol !== "gemini-native" || !next) return { models: [...models.values()], limited: data?.has_more === true };
1080
+ if (typeof next !== "string" || next.length > 2048 || cursors.has(next)) throw new EmbeddingError("invalid-response", "\u6A21\u578B\u5217\u8868\u5206\u9875\u6E38\u6807\u65E0\u6548\u6216\u91CD\u590D");
1081
+ cursors.add(next);
1082
+ cursor = next;
1083
+ }
1084
+ return { models: [...models.values()], limited: true };
1085
+ })());
1086
+ }
1087
+ async run(inputs, role2, signal, maxRetries = this.config.maxRetries) {
1088
+ signal.throwIfAborted();
1089
+ if (role2 !== "document" && role2 !== "query") throw new EmbeddingError("invalid-input", "\u5D4C\u5165\u89D2\u8272\u65E0\u6548");
1090
+ if (inputs.some((input) => typeof input.text !== "string" || !input.text.trim() || input.text.length > 32e3)) {
1091
+ throw new EmbeddingError("invalid-input", "\u5D4C\u5165\u8F93\u5165\u987B\u4E3A\u975E\u7A7A\u4E14\u957F\u5EA6\u53D7\u652F\u6301\u7684\u6587\u672C\uFF1B\u672A\u8FC7\u6EE4\u6216\u622A\u65AD\u8F93\u5165");
1092
+ }
1093
+ const result = [];
1094
+ for (let offset = 0; offset < inputs.length; offset += this.config.batchSize) {
1095
+ signal.throwIfAborted();
1096
+ const batch = inputs.slice(offset, offset + this.config.batchSize);
1097
+ const response = await this.request(batch, role2, signal, false, maxRetries);
1098
+ result.push(...this.parse(response, batch.length));
1099
+ }
1100
+ signal.throwIfAborted();
1101
+ return result;
1102
+ }
1103
+ payload(inputs, role2, omitDimensions) {
1104
+ const c = this.config;
1105
+ const prefix = role2 === "document" ? c.documentPrefix : c.queryPrefix;
1106
+ const nativeTasks = c.protocol === "gemini-native" && c.geminiTaskMode === "native";
1107
+ const text = (input) => [prefix, ...!nativeTasks && role2 === "document" && input.title ? [input.title] : [], input.text].filter(Boolean).join("\n");
1108
+ if (c.protocol === "openai-compatible") return {
1109
+ endpoint: c.baseURL.endsWith("/embeddings") ? c.baseURL : `${c.baseURL}/embeddings`,
1110
+ keyHeader: "Authorization",
1111
+ body: { model: c.model, input: inputs.map(text), encoding_format: "float", ...c.sendDimensions && !omitDimensions ? { dimensions: c.dimensions } : {} }
1112
+ };
1113
+ return {
1114
+ endpoint: `${c.baseURL}/models/${encodeURIComponent(c.model)}:batchEmbedContents`,
1115
+ keyHeader: "x-goog-api-key",
1116
+ body: { requests: inputs.map((input) => ({
1117
+ model: `models/${c.model}`,
1118
+ content: { parts: [{ text: text(input) }] },
1119
+ embedContentConfig: {
1120
+ autoTruncate: false,
1121
+ ...c.sendDimensions && !omitDimensions ? { outputDimensionality: c.dimensions } : {},
1122
+ ...nativeTasks ? { taskType: role2 === "document" ? "RETRIEVAL_DOCUMENT" : "RETRIEVAL_QUERY" } : {},
1123
+ ...nativeTasks && role2 === "document" && input.title ? { title: input.title } : {}
1124
+ }
1125
+ })) }
1126
+ };
1127
+ }
1128
+ request(inputs, role2, signal, omitDimensions = false, maxRetries = this.config.maxRetries) {
1129
+ const payload = this.payload(inputs, role2, omitDimensions);
1130
+ return this.send(payload.endpoint, "POST", payload.body, payload.keyHeader, signal, maxRetries);
1131
+ }
1132
+ async send(endpoint, method, body, keyHeader, signal, maxRetries = this.config.maxRetries) {
1133
+ for (let attempt = 0; ; attempt++) {
1134
+ signal.throwIfAborted();
1135
+ let credential;
1136
+ try {
1137
+ credential = await abortable(this.key(), signal);
1138
+ } catch {
1139
+ signal.throwIfAborted();
1140
+ throw new EmbeddingError("credential-error", "\u65E0\u6CD5\u8BFB\u53D6\u5D4C\u5165\u51ED\u636E");
1141
+ }
1142
+ signal.throwIfAborted();
1143
+ if (!credential) throw new EmbeddingError("credential-missing", "\u5D4C\u5165 API Key \u5C1A\u672A\u914D\u7F6E");
1144
+ const timeout = AbortSignal.timeout(this.config.timeoutMs);
1145
+ const requestSignal = AbortSignal.any([signal, timeout]);
1146
+ let response;
1147
+ try {
1148
+ response = await fetch(endpoint, {
1149
+ method,
1150
+ redirect: "error",
1151
+ signal: requestSignal,
1152
+ headers: { "content-type": "application/json", [keyHeader]: keyHeader === "Authorization" ? `Bearer ${credential}` : credential },
1153
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
1154
+ });
1155
+ } catch {
1156
+ signal.throwIfAborted();
1157
+ if (attempt < maxRetries) {
1158
+ await this.retryDelay(attempt, signal);
1159
+ continue;
1160
+ }
1161
+ throw new EmbeddingError(timeout.aborted ? "timeout" : "transport", timeout.aborted ? "\u5D4C\u5165\u8BF7\u6C42\u8D85\u65F6" : "\u5D4C\u5165\u8BF7\u6C42\u65E0\u6CD5\u5B8C\u6210\uFF0C\u8BF7\u68C0\u67E5\u63A5\u53E3\u5730\u5740\u4E0E\u7F51\u7EDC");
1162
+ }
1163
+ if (!response.ok) {
1164
+ await response.body?.cancel();
1165
+ const retryAfterMs = parseRetryAfter(response.headers.get("retry-after"));
1166
+ if ((response.status === 429 || [500, 502, 503, 504].includes(response.status)) && attempt < maxRetries && (retryAfterMs ?? 0) <= this.config.timeoutMs) {
1167
+ await this.retryDelay(attempt, signal, retryAfterMs);
1168
+ continue;
1169
+ }
1170
+ throw new EmbeddingError("http-error", `\u5D4C\u5165\u670D\u52A1\u8FD4\u56DE HTTP ${response.status}`, response.status, retryAfterMs);
1171
+ }
1172
+ try {
1173
+ const reader = response.body?.getReader();
1174
+ if (!reader) throw new Error("empty body");
1175
+ const parts = [];
1176
+ let length = 0;
1177
+ try {
1178
+ for (; ; ) {
1179
+ const { done, value } = await reader.read();
1180
+ if (done) break;
1181
+ length += value.length;
1182
+ if (length > MAX_RESPONSE_BYTES) {
1183
+ await reader.cancel();
1184
+ throw new Error("oversize response");
1185
+ }
1186
+ parts.push(value);
1187
+ }
1188
+ } finally {
1189
+ reader.releaseLock();
1190
+ }
1191
+ signal.throwIfAborted();
1192
+ return JSON.parse(Buffer.concat(parts).toString("utf8"));
1193
+ } catch {
1194
+ signal.throwIfAborted();
1195
+ if (timeout.aborted) {
1196
+ if (attempt < maxRetries) {
1197
+ await this.retryDelay(attempt, signal);
1198
+ continue;
1199
+ }
1200
+ throw new EmbeddingError("timeout", "\u5D4C\u5165\u54CD\u5E94\u8BFB\u53D6\u8D85\u65F6");
1201
+ }
1202
+ throw new EmbeddingError("invalid-response", "\u5D4C\u5165\u54CD\u5E94\u4E0D\u662F\u53D7\u652F\u6301\u7684 JSON \u6216\u8D85\u8FC7\u5927\u5C0F\u9650\u5236");
1203
+ }
1204
+ }
1205
+ }
1206
+ retryDelay(attempt, signal, minimumMs = 0) {
1207
+ const delay = Math.max(Number.isFinite(minimumMs) ? minimumMs : 0, 100 * 2 ** attempt);
1208
+ return new Promise((resolve2, reject) => {
1209
+ const timer = setTimeout(() => {
1210
+ signal.removeEventListener("abort", abort);
1211
+ resolve2();
1212
+ }, delay);
1213
+ const abort = () => {
1214
+ clearTimeout(timer);
1215
+ signal.removeEventListener("abort", abort);
1216
+ reject(signal.reason);
1217
+ };
1218
+ signal.addEventListener("abort", abort, { once: true });
1219
+ if (signal.aborted) abort();
1220
+ });
1221
+ }
1222
+ parse(response, count, expectedDimensions = this.config.dimensions) {
1223
+ const data = object(response);
1224
+ const rows = this.config.protocol === "openai-compatible" ? data?.data : data?.embeddings;
1225
+ if (!Array.isArray(rows) || rows.length !== count) throw new EmbeddingError("invalid-response", "\u5D4C\u5165\u54CD\u5E94\u6570\u91CF\u4E0E\u8F93\u5165\u4E0D\u4E00\u81F4");
1226
+ const result = new Array(count);
1227
+ for (let position = 0; position < rows.length; position++) {
1228
+ const row = object(rows[position]);
1229
+ const index = this.config.protocol === "openai-compatible" ? row?.index : position;
1230
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= count || result[index] !== void 0) {
1231
+ throw new EmbeddingError("invalid-response", "\u5D4C\u5165\u54CD\u5E94\u7D22\u5F15\u91CD\u590D\u6216\u8D8A\u754C");
1232
+ }
1233
+ const vector = this.config.protocol === "openai-compatible" ? row?.embedding : row?.values;
1234
+ if (!Array.isArray(vector) || vector.length === 0 || vector.length > 65536 || expectedDimensions !== null && vector.length !== expectedDimensions || vector.some((value) => typeof value !== "number" || !Number.isFinite(value)) || vector.every((value) => value === 0)) {
1235
+ throw new EmbeddingError("invalid-response", "\u5D4C\u5165\u54CD\u5E94\u5411\u91CF\u4E0E\u914D\u7F6E\u7EF4\u5EA6\u4E0D\u4E00\u81F4\u6216\u5305\u542B\u65E0\u6548\u6570\u503C");
1236
+ }
1237
+ result[index] = vector;
1238
+ }
1239
+ return result;
1240
+ }
1241
+ };
1242
+
1243
+ // ../embedding-provider/src/discovery.ts
1244
+ function attachDiscovery(ctx) {
1245
+ ctx.inject(["connection"], (scope) => {
1246
+ const clients = /* @__PURE__ */ new Set();
1247
+ scope.effect(() => () => Promise.allSettled([...clients].map((client) => client.close())), "webnovel embeddings: discovery requests");
1248
+ scope.connection.fetch.register({
1249
+ path: "/api/webnovel/embeddings",
1250
+ methods: ["POST"],
1251
+ requestBody: "buffered",
1252
+ fetch: async (request) => {
1253
+ let client;
1254
+ try {
1255
+ const text = await request.text();
1256
+ if (text.length > 32768) throw new EmbeddingError("invalid-input", "\u914D\u7F6E\u8BF7\u6C42\u8FC7\u5927");
1257
+ const value = JSON.parse(text);
1258
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new EmbeddingError("invalid-input", "\u914D\u7F6E\u8BF7\u6C42\u683C\u5F0F\u4E0D\u6B63\u786E");
1259
+ const input = value;
1260
+ if (input.action !== "models" && input.action !== "dimensions") throw new EmbeddingError("invalid-input", "\u672A\u77E5\u914D\u7F6E\u64CD\u4F5C");
1261
+ if (typeof input.baseURL !== "string" || typeof input.protocol !== "string") throw new EmbeddingError("invalid-input", "\u8BF7\u5148\u586B\u5199\u63A5\u53E3\u5730\u5740\u548C\u534F\u8BAE");
1262
+ if (input.action === "dimensions" && (typeof input.model !== "string" || !input.model.trim())) throw new EmbeddingError("invalid-input", "\u8BF7\u5148\u9009\u62E9\u6216\u586B\u5199\u5411\u91CF\u6A21\u578B");
1263
+ const config = resolveSettings({
1264
+ enabled: true,
1265
+ protocol: input.protocol,
1266
+ baseURL: input.baseURL,
1267
+ model: typeof input.model === "string" && input.model ? input.model : "discovery",
1268
+ dimensions: 1,
1269
+ apiKeyEnv: typeof input.apiKeyEnv === "string" ? input.apiKeyEnv : DEFAULT_CREDENTIAL,
1270
+ sendDimensions: false,
1271
+ maxRetries: 1
1272
+ });
1273
+ const key = typeof input.apiKey === "string" && input.apiKey.trim() ? input.apiKey.trim() : void 0;
1274
+ if (key && !/^[\x21-\x7e]+$/.test(key)) throw new EmbeddingError("invalid-input", "API Key \u683C\u5F0F\u65E0\u6548");
1275
+ client = new HttpEmbeddingProvider(config, async () => {
1276
+ try {
1277
+ return key ?? (await ctx.credentials.resolve(credentialRef(config.apiKeyEnv)))?.value;
1278
+ } catch {
1279
+ throw new EmbeddingError("credential-error", "\u65E0\u6CD5\u8BFB\u53D6 API \u51ED\u636E\uFF0C\u8BF7\u68C0\u67E5 DSH \u51ED\u636E\u8BBE\u7F6E");
1280
+ }
1281
+ });
1282
+ clients.add(client);
1283
+ const result = input.action === "models" ? await client.listModels(request.signal) : { dimensions: await client.probeDimensions(request.signal) };
1284
+ return Response.json({ ok: true, value: result }, { headers: { "cache-control": "no-store" } });
1285
+ } catch (error) {
1286
+ const message = error instanceof SyntaxError ? "\u914D\u7F6E\u8BF7\u6C42\u4E0D\u662F\u6709\u6548 JSON" : error instanceof Error ? error.message : "\u63A5\u53E3\u67E5\u8BE2\u5931\u8D25";
1287
+ return Response.json({ ok: false, error: message }, { status: 400, headers: { "cache-control": "no-store" } });
1288
+ } finally {
1289
+ if (client) {
1290
+ clients.delete(client);
1291
+ await client.close();
1292
+ }
1293
+ }
1294
+ }
1295
+ });
1296
+ });
1297
+ }
1298
+
1299
+ // ../embedding-provider/src/live-settings.ts
1300
+ function attachLiveSettings(ctx, validate, refresh) {
1301
+ ctx.on("internal/config", (fiber, next) => {
1302
+ const raw = next();
1303
+ if (fiber === ctx.fiber) validate(raw);
1304
+ return raw;
1305
+ });
1306
+ ctx.on("loader/volatile-update", refresh);
1307
+ ctx.inject(["settings"], (scope) => {
1308
+ scope.effect(() => scope.settings.configure({ auto: false }, ctx.fiber));
1309
+ });
1310
+ }
1311
+
1312
+ // ../embedding-provider/src/index.ts
1313
+ var Config2 = Config.volatile();
1314
+ var name = "webnovel-embedding-provider";
1315
+ var inject = ["credentials"];
1316
+ var EmbeddingService = class extends Service2 {
1317
+ constructor(ctx, source) {
1318
+ super(ctx, "embeddings");
1319
+ this.source = source;
1320
+ }
1321
+ source;
1322
+ currentClient;
1323
+ closing = /* @__PURE__ */ new Set();
1324
+ current() {
1325
+ const configuration = resolveSettings(this.source());
1326
+ if (!configuration) {
1327
+ this.retire();
1328
+ return void 0;
1329
+ }
1330
+ if (!this.currentClient || JSON.stringify(configuration) !== JSON.stringify(this.currentClient.config)) {
1331
+ this.retire();
1332
+ this.currentClient = new HttpEmbeddingProvider(configuration, async () => {
1333
+ const credentials = this.ctx.get("credentials");
1334
+ return credentials ? (await credentials.resolve(credentialRef(configuration.apiKeyEnv)))?.value : void 0;
1335
+ });
1336
+ }
1337
+ return this.currentClient;
1338
+ }
1339
+ refresh() {
1340
+ this.retire();
1341
+ }
1342
+ retire() {
1343
+ if (!this.currentClient) return;
1344
+ const task = this.currentClient.close();
1345
+ this.currentClient = void 0;
1346
+ this.closing.add(task);
1347
+ void task.then(() => this.closing.delete(task), () => this.closing.delete(task));
1348
+ }
1349
+ async close() {
1350
+ this.retire();
1351
+ await Promise.allSettled([...this.closing]);
1352
+ }
1353
+ };
1354
+ function apply(ctx, entry) {
1355
+ const current = () => entry.get() ?? {};
1356
+ resolveSettings(current());
1357
+ const service = new EmbeddingService(ctx, current);
1358
+ attachDiscovery(ctx);
1359
+ ctx.effect(() => () => service.close(), "webnovel embeddings: cancel pending requests");
1360
+ attachLiveSettings(ctx, resolveSettings, () => service.refresh());
1361
+ }
1362
+ export {
1363
+ Config2 as Config,
1364
+ EmbeddingService,
1365
+ apply,
1366
+ inject,
1367
+ name
1368
+ };