@arabold/docs-mcp-server 3.2.1 → 3.4.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.
Files changed (38) hide show
  1. package/README.md +67 -114
  2. package/db/migrations/017-add-library-display-name.sql +76 -0
  3. package/db/migrations/018-store-embeddings-as-blobs.sql +56 -0
  4. package/db/migrations/019-tune-indexes.sql +30 -0
  5. package/dist/{HtmlDefuddleMiddleware-Cm0vQDqD.js → HtmlDefuddleMiddleware-DxjoyIFY.js} +4 -7
  6. package/dist/HtmlDefuddleMiddleware-DxjoyIFY.js.map +1 -0
  7. package/{public/assets/index-BHI6XhAh.css → dist/assets/index-BG8UJbPA.css} +1 -1
  8. package/dist/assets/index-DR-3PGgZ.js +70 -0
  9. package/dist/assets/index-DR-3PGgZ.js.map +1 -0
  10. package/dist/{env-DONvEfR5.js → env-DAfCMXx2.js} +2 -3
  11. package/dist/{env-DONvEfR5.js.map → env-DAfCMXx2.js.map} +1 -1
  12. package/dist/index.html +3 -3
  13. package/dist/index.js +4 -5
  14. package/dist/{logger-BBxstTD7.js → logger-DtB7mX3u.js} +2 -3
  15. package/dist/{logger-BBxstTD7.js.map → logger-DtB7mX3u.js.map} +1 -1
  16. package/dist/{main-BjEbd9LZ.js → main-BTCYUUTU.js} +16047 -15005
  17. package/dist/main-BTCYUUTU.js.map +1 -0
  18. package/dist/manifest.json +7 -7
  19. package/dist/string-n2Z12tl6.js +43 -0
  20. package/dist/string-n2Z12tl6.js.map +1 -0
  21. package/dist/utils-1UoDzw8s.js +1 -0
  22. package/dist/utils-7a9aMv8E.js +1866 -0
  23. package/dist/utils-7a9aMv8E.js.map +1 -0
  24. package/package.json +66 -62
  25. package/{dist/assets/index-BHI6XhAh.css → public/assets/index-BG8UJbPA.css} +1 -1
  26. package/public/assets/index-DR-3PGgZ.js +70 -0
  27. package/public/assets/index-DR-3PGgZ.js.map +1 -0
  28. package/public/index.html +3 -3
  29. package/public/manifest.json +7 -7
  30. package/dist/HtmlDefuddleMiddleware-Cm0vQDqD.js.map +0 -1
  31. package/dist/assets/index-CHvUVvbT.js +0 -70
  32. package/dist/assets/index-CHvUVvbT.js.map +0 -1
  33. package/dist/main-BjEbd9LZ.js.map +0 -1
  34. package/dist/utils-BP4qIXx8.js +0 -2
  35. package/dist/utils-uCqhR-rj.js +0 -1158
  36. package/dist/utils-uCqhR-rj.js.map +0 -1
  37. package/public/assets/index-CHvUVvbT.js +0 -70
  38. package/public/assets/index-CHvUVvbT.js.map +0 -1
@@ -1,1158 +0,0 @@
1
- import { t as normalizeEnvValue } from "./env-DONvEfR5.js";
2
- import { r as logger } from "./logger-BBxstTD7.js";
3
- import { randomUUID } from "node:crypto";
4
- import fs, { existsSync } from "node:fs";
5
- import path from "node:path";
6
- import { fileURLToPath } from "node:url";
7
- import envPaths from "env-paths";
8
- import { PostHog } from "posthog-node";
9
- import EventEmitter from "node:events";
10
- import { chromium } from "playwright";
11
- import { execSync } from "node:child_process";
12
- import { createInterface } from "node:readline";
13
- //#region src/store/embeddings/EmbeddingConfig.ts
14
- /**
15
- * Shared embedding model configuration service.
16
- * Provides synchronous parsing of embedding model configuration and known dimensions lookup.
17
- * Eliminates code duplication between DocumentStore and telemetry systems.
18
- *
19
- * All model lookups are case-insensitive to handle variations in model name capitalization.
20
- * Uses class-based approach to avoid mutable global state and improve testability.
21
- */
22
- /**
23
- * The complete set of provider prefixes recognized in a model specification.
24
- * Anything else before the first colon is part of the model name itself.
25
- *
26
- * This list is normative rather than descriptive: it decides which prefixes claim
27
- * the provider slot, so adding an entry changes how existing specifications parse.
28
- * A model literally named `<new-provider>:<tag>` served by an OpenAI-compatible
29
- * endpoint would start resolving to the new provider, breaking that configuration
30
- * on upgrade. Call provider additions out in the release notes.
31
- *
32
- * `EmbeddingProvider` is derived from this array so the two cannot drift apart.
33
- */
34
- var SUPPORTED_PROVIDERS = [
35
- "openai",
36
- "vertex",
37
- "gemini",
38
- "aws",
39
- "microsoft"
40
- ];
41
- /**
42
- * Split a model specification into its provider prefix and model name.
43
- *
44
- * Only a prefix that names a supported provider is treated as a provider, matched
45
- * case-insensitively and resolved to its canonical lowercase form. Every other
46
- * specification is an OpenAI-compatible model name, which keeps names that carry a
47
- * tag or quantization suffix intact (e.g. "nomic-embed-text:latest" or
48
- * "second-state/jina-embeddings-v3-GGUF:Q4_K_M").
49
- *
50
- * @param spec The full model specification.
51
- * @returns The resolved provider and model name.
52
- */
53
- function splitModelSpec(spec) {
54
- const colonIndex = spec.indexOf(":");
55
- const prefix = spec.substring(0, colonIndex).toLowerCase();
56
- const provider = colonIndex === -1 ? void 0 : SUPPORTED_PROVIDERS.find((name) => name === prefix);
57
- return provider ? {
58
- provider,
59
- model: spec.substring(colonIndex + 1)
60
- } : {
61
- provider: "openai",
62
- model: spec
63
- };
64
- }
65
- /**
66
- * Embedding configuration manager that handles model parsing and dimension caching.
67
- * Encapsulates state to avoid global variable issues and improve testability.
68
- */
69
- var EmbeddingConfig = class EmbeddingConfig {
70
- static instance = null;
71
- /**
72
- * Get the singleton instance of EmbeddingConfig.
73
- * Creates the instance if it doesn't exist.
74
- */
75
- static getInstance() {
76
- if (EmbeddingConfig.instance === null) EmbeddingConfig.instance = new EmbeddingConfig();
77
- return EmbeddingConfig.instance;
78
- }
79
- /**
80
- * Reset the singleton instance (useful for testing).
81
- */
82
- static resetInstance() {
83
- EmbeddingConfig.instance = null;
84
- }
85
- /**
86
- * Known dimensions for common embedding models.
87
- * This avoids expensive API calls for dimension detection in telemetry.
88
- *
89
- * Note: The "openai" provider also supports OpenAI-compatible APIs like:
90
- * - Ollama (local models)
91
- * - LMStudio (local models)
92
- * - Any service implementing OpenAI's embedding API
93
- */
94
- knownModelDimensions = {
95
- "text-embedding-3-small": 1536,
96
- "text-embedding-3-large": 3072,
97
- "text-embedding-ada-002": 1536,
98
- "text-embedding-004": 768,
99
- "text-embedding-005": 768,
100
- "textembedding-gecko@003": 768,
101
- "textembedding-gecko@002": 768,
102
- "textembedding-gecko@001": 768,
103
- "text-embedding-preview-0409": 768,
104
- "embedding-001": 768,
105
- "gemini-embedding-2-preview": 3072,
106
- "amazon.titan-embed-text-v1": 1536,
107
- "amazon.titan-embed-text-v2:0": 1024,
108
- "amazon.titan-embed-image-v1": 1024,
109
- "cohere.embed-english-v3": 1024,
110
- "cohere.embed-multilingual-v3": 1024,
111
- "Cohere/Cohere-embed-v4.0": 1536,
112
- "embed-v4.0": 1536,
113
- "intfloat/multilingual-e5-large": 1024,
114
- "multilingual-e5-large": 1024,
115
- "text-embedding-multilingual-e5-large": 1024,
116
- "sentence-transformers/all-MiniLM-L6-v2": 384,
117
- "gemini-embedding-001": 3072,
118
- "Qwen/Qwen3-Embedding-8B": 4096,
119
- "Qwen/Qwen3-Embedding-4B": 2560,
120
- "Qwen/Qwen3-Embedding-0.6B": 1024,
121
- "Linq-AI-Research/Linq-Embed-Mistral": 4096,
122
- "Alibaba-NLP/gte-Qwen2-7B-instruct": 3584,
123
- "intfloat/multilingual-e5-large-instruct": 1024,
124
- "Salesforce/SFR-Embedding-Mistral": 4096,
125
- "text-multilingual-embedding-002": 768,
126
- "GritLM/GritLM-7B": 4096,
127
- "GritLM/GritLM-8x7B": 4096,
128
- "intfloat/e5-mistral-7b-instruct": 4096,
129
- "Cohere/Cohere-embed-multilingual-v3.0": 1024,
130
- "Alibaba-NLP/gte-Qwen2-1.5B-instruct": 8960,
131
- "Lajavaness/bilingual-embedding-large": 1024,
132
- "Salesforce/SFR-Embedding-2_R": 4096,
133
- "NovaSearch/stella_en_1.5B_v5": 8960,
134
- "NovaSearch/jasper_en_vision_language_v1": 8960,
135
- "nvidia/NV-Embed-v2": 4096,
136
- "OrdalieTech/Solon-embeddings-large-0.1": 1024,
137
- "BAAI/bge-m3": 1024,
138
- "HIT-TMG/KaLM-embedding-multilingual-mini-v1": 896,
139
- "jinaai/jina-embeddings-v3": 1024,
140
- "Alibaba-NLP/gte-multilingual-base": 768,
141
- "Lajavaness/bilingual-embedding-base": 768,
142
- "HIT-TMG/KaLM-embedding-multilingual-mini-instruct-v1": 896,
143
- "nvidia/NV-Embed-v1": 4096,
144
- "Cohere/Cohere-embed-multilingual-light-v3.0": 384,
145
- "manu/bge-m3-custom-fr": 1024,
146
- "Lajavaness/bilingual-embedding-small": 384,
147
- "Snowflake/snowflake-arctic-embed-l-v2.0": 1024,
148
- "intfloat/multilingual-e5-base": 768,
149
- "voyage-3-lite": 512,
150
- "voyage-3": 1024,
151
- "voyage-3-large": 1024,
152
- "voyage-3.5": 1024,
153
- "voyage-4": 1024,
154
- "voyage-4-large": 1024,
155
- "voyage-4-lite": 1024,
156
- "voyage-code-3": 1024,
157
- "intfloat/multilingual-e5-small": 384,
158
- "Alibaba-NLP/gte-Qwen1.5-7B-instruct": 4096,
159
- "Snowflake/snowflake-arctic-embed-m-v2.0": 768,
160
- "deepvk/USER-bge-m3": 1024,
161
- "Cohere/Cohere-embed-english-v3.0": 1024,
162
- "Omartificial-Intelligence-Space/Arabic-labse-Matryoshka": 768,
163
- "ibm-granite/granite-embedding-278m-multilingual": 768,
164
- "NovaSearch/stella_en_400M_v5": 4096,
165
- "omarelshehy/arabic-english-sts-matryoshka": 1024,
166
- "sentence-transformers/paraphrase-multilingual-mpnet-base-v2": 768,
167
- "Omartificial-Intelligence-Space/Arabic-all-nli-triplet-Matryoshka": 768,
168
- "Haon-Chen/speed-embedding-7b-instruct": 4096,
169
- "sentence-transformers/LaBSE": 768,
170
- "WhereIsAI/UAE-Large-V1": 1024,
171
- "ibm-granite/granite-embedding-107m-multilingual": 384,
172
- "mixedbread-ai/mxbai-embed-large-v1": 1024,
173
- "intfloat/e5-large-v2": 1024,
174
- "avsolatorio/GIST-large-Embedding-v0": 1024,
175
- "sdadas/mmlw-e5-large": 1024,
176
- "nomic-ai/nomic-embed-text-v1": 768,
177
- "nomic-embed-text-v1": 768,
178
- "nomic-ai/nomic-embed-text-v1-ablated": 768,
179
- "nomic-ai/nomic-embed-text-v2-moe": 768,
180
- "nomic-ai/modernbert-embed-base": 768,
181
- "nomic-ai/nomic-embed-code": 3584,
182
- "intfloat/e5-base-v2": 768,
183
- "BAAI/bge-large-en-v1.5": 1024,
184
- "intfloat/e5-large": 1024,
185
- "Omartificial-Intelligence-Space/Arabic-MiniLM-L12-v2-all-nli-triplet": 384,
186
- "Cohere/Cohere-embed-english-light-v3.0": 384,
187
- "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2": 768,
188
- "Gameselo/STS-multilingual-mpnet-base-v2": 768,
189
- "thenlper/gte-large": 1024,
190
- "avsolatorio/GIST-Embedding-v0": 768,
191
- "nomic-ai/nomic-embed-text-v1-unsupervised": 768,
192
- "infgrad/stella-base-en-v2": 768,
193
- "avsolatorio/NoInstruct-small-Embedding-v0": 384,
194
- "dwzhu/e5-base-4k": 768,
195
- "sdadas/mmlw-e5-base": 768,
196
- "voyage-multilingual-2": 1024,
197
- "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-supervised": 4096,
198
- "BAAI/bge-base-en-v1.5": 768,
199
- "avsolatorio/GIST-small-Embedding-v0": 384,
200
- "sdadas/mmlw-roberta-large": 1024,
201
- "nomic-ai/nomic-embed-text-v1.5": 768,
202
- "nomic-embed-text-v1.5": 768,
203
- "text-embedding-nomic-embed-text-v1.5": 768,
204
- "minishlab/potion-multilingual-128M": 256,
205
- "shibing624/text2vec-base-multilingual": 384,
206
- "thenlper/gte-base": 768,
207
- "intfloat/e5-small-v2": 384,
208
- "intfloat/e5-base": 768,
209
- "sentence-transformers/static-similarity-mrl-multilingual-v1": 1024,
210
- "manu/sentence_croissant_alpha_v0.3": 2048,
211
- "BAAI/bge-small-en-v1.5": 512,
212
- "thenlper/gte-small": 384,
213
- "sdadas/mmlw-e5-small": 384,
214
- "manu/sentence_croissant_alpha_v0.4": 2048,
215
- "manu/sentence_croissant_alpha_v0.2": 2048,
216
- "abhinand/MedEmbed-small-v0.1": 384,
217
- "ibm-granite/granite-embedding-125m-english": 768,
218
- "intfloat/e5-small": 384,
219
- "voyage-large-2-instruct": 1024,
220
- "sdadas/mmlw-roberta-base": 768,
221
- "Snowflake/snowflake-arctic-embed-l": 1024,
222
- "Mihaiii/Ivysaur": 384,
223
- "Snowflake/snowflake-arctic-embed-m-long": 768,
224
- "bigscience/sgpt-bloom-7b1-msmarco": 4096,
225
- "avsolatorio/GIST-all-MiniLM-L6-v2": 384,
226
- "sergeyzh/LaBSE-ru-turbo": 768,
227
- "sentence-transformers/all-mpnet-base-v2": 768,
228
- "Snowflake/snowflake-arctic-embed-m": 768,
229
- "Snowflake/snowflake-arctic-embed-s": 384,
230
- "sentence-transformers/all-MiniLM-L12-v2": 384,
231
- "Mihaiii/gte-micro-v4": 384,
232
- "Snowflake/snowflake-arctic-embed-m-v1.5": 768,
233
- "cointegrated/LaBSE-en-ru": 768,
234
- "Mihaiii/Bulbasaur": 384,
235
- "ibm-granite/granite-embedding-30m-english": 384,
236
- "deepfile/embedder-100p": 768,
237
- "Jaume/gemma-2b-embeddings": 2048,
238
- "OrlikB/KartonBERT-USE-base-v1": 768,
239
- "izhx/udever-bloom-7b1": 4096,
240
- "izhx/udever-bloom-1b1": 1024,
241
- "brahmairesearch/slx-v0.1": 384,
242
- "Mihaiii/Wartortle": 384,
243
- "izhx/udever-bloom-3b": 2048,
244
- "deepvk/USER-base": 768,
245
- "ai-forever/ru-en-RoSBERTa": 1024,
246
- "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-unsup-simcse": 4096,
247
- "Mihaiii/Venusaur": 384,
248
- "Snowflake/snowflake-arctic-embed-xs": 384,
249
- "jinaai/jina-embedding-b-en-v1": 768,
250
- "Mihaiii/gte-micro": 384,
251
- "aari1995/German_Semantic_STS_V2": 1024,
252
- "Mihaiii/Squirtle": 384,
253
- "OrlikB/st-polish-kartonberta-base-alpha-v1": 768,
254
- "sergeyzh/rubert-tiny-turbo": 312,
255
- "minishlab/potion-base-8M": 256,
256
- "minishlab/M2V_base_glove_subword": 256,
257
- "jinaai/jina-embedding-s-en-v1": 512,
258
- "minishlab/potion-base-4M": 128,
259
- "minishlab/M2V_base_output": 256,
260
- "DeepPavlov/rubert-base-cased-sentence": 768,
261
- "jinaai/jina-embeddings-v2-small-en": 512,
262
- "cointegrated/rubert-tiny2": 312,
263
- "minishlab/M2V_base_glove": 256,
264
- "cointegrated/rubert-tiny": 312,
265
- "silma-ai/silma-embeddding-matryoshka-v0.1": 768,
266
- "DeepPavlov/rubert-base-cased": 768,
267
- "Omartificial-Intelligence-Space/Arabic-mpnet-base-all-nli-triplet": 768,
268
- "izhx/udever-bloom-560m": 1024,
269
- "minishlab/potion-base-2M": 64,
270
- "DeepPavlov/distilrubert-small-cased-conversational": 768,
271
- "consciousAI/cai-lunaris-text-embeddings": 1024,
272
- "deepvk/deberta-v1-base": 768,
273
- "Omartificial-Intelligence-Space/Arabert-all-nli-triplet-Matryoshka": 768,
274
- "Omartificial-Intelligence-Space/Marbert-all-nli-triplet-Matryoshka": 768,
275
- "ai-forever/sbert_large_mt_nlu_ru": 1024,
276
- "ai-forever/sbert_large_nlu_ru": 1024,
277
- "malenia1/ternary-weight-embedding": 1024,
278
- "jinaai/jina-embeddings-v2-base-en": 768,
279
- "VPLabs/SearchMap_Preview": 4096,
280
- "Hum-Works/lodestone-base-4096-v1": 768,
281
- "jinaai/jina-embeddings-v4": 2048
282
- };
283
- runtimeDetectedDimensionModels = /* @__PURE__ */ new Set([
284
- "novasearch/stella_en_1.5b_v5",
285
- "stella_en_1.5b_v5",
286
- "novasearch/stella_en_400m_v5",
287
- "dunzhang/stella_en_400m_v5",
288
- "stella_en_400m_v5",
289
- "novasearch/jasper_en_vision_language_v1",
290
- "jasper_en_vision_language_v1"
291
- ]);
292
- /**
293
- * Lowercase lookup map for case-insensitive model dimension queries.
294
- * Built lazily from knownModelDimensions to ensure consistency.
295
- */
296
- modelLookup;
297
- constructor() {
298
- this.modelLookup = /* @__PURE__ */ new Map();
299
- for (const [model, dimensions] of Object.entries(this.knownModelDimensions)) this.modelLookup.set(model.toLowerCase(), dimensions);
300
- }
301
- /**
302
- * Build the lookup keys to try for a model name, most specific first:
303
- * the name itself, then with the namespace dropped, the tag dropped, and both.
304
- *
305
- * Dropping a trailing tag lets a quantized or tagged variant reuse the base
306
- * model's dimensions (e.g. "nomic-ai/nomic-embed-text-v2-moe:latest"), which
307
- * quantization does not change. Exact matches are tried first, so names whose
308
- * own identifier contains a colon (e.g. "amazon.titan-embed-text-v2:0") still
309
- * resolve to their own entry.
310
- */
311
- dimensionLookupKeys(normalized) {
312
- const slashIndex = normalized.lastIndexOf("/");
313
- const withoutNamespace = slashIndex > -1 ? normalized.substring(slashIndex + 1) : void 0;
314
- const bases = withoutNamespace ? [normalized, withoutNamespace] : [normalized];
315
- const withoutTag = (key) => {
316
- const colonIndex = key.lastIndexOf(":");
317
- return colonIndex > 0 ? [key.substring(0, colonIndex)] : [];
318
- };
319
- return [...bases, ...bases.flatMap(withoutTag)];
320
- }
321
- findKnownDimension(model) {
322
- for (const key of this.dimensionLookupKeys(model.toLowerCase())) {
323
- if (this.runtimeDetectedDimensionModels.has(key)) return null;
324
- const dimensions = this.modelLookup?.get(key);
325
- if (dimensions !== void 0) return dimensions;
326
- }
327
- return null;
328
- }
329
- /**
330
- * Parse embedding model configuration from a provided model specification.
331
- * This is a synchronous operation that extracts provider, model, and known dimensions.
332
- *
333
- * Supports various providers:
334
- * - openai: OpenAI models and OpenAI-compatible APIs (Ollama, LMStudio, etc.)
335
- * - vertex: Google Cloud Vertex AI
336
- * - gemini: Google Generative AI
337
- * - aws: AWS Bedrock models
338
- * - microsoft: Azure OpenAI
339
- *
340
- * @param modelSpec Model specification (e.g., "openai:text-embedding-3-small"), defaults to "text-embedding-3-small"
341
- * @returns Parsed embedding model configuration
342
- */
343
- parse(modelSpec) {
344
- const spec = normalizeEnvValue(modelSpec || "text-embedding-3-small");
345
- const { provider, model } = splitModelSpec(spec);
346
- return {
347
- provider,
348
- model,
349
- dimensions: this.findKnownDimension(model),
350
- modelSpec: spec
351
- };
352
- }
353
- /**
354
- * Get the known dimensions for a specific model.
355
- * Returns null if the model dimensions are not known.
356
- * Uses case-insensitive lookup.
357
- *
358
- * @param model The model name (e.g., "text-embedding-3-small")
359
- * @returns Known dimensions or null
360
- */
361
- getKnownDimensions(model) {
362
- return this.findKnownDimension(model);
363
- }
364
- /**
365
- * Add or update known dimensions for a model.
366
- * This can be used to cache discovered dimensions.
367
- * Stores both original case and lowercase for consistent lookup.
368
- *
369
- * @param model The model name
370
- * @param dimensions The dimensions to cache
371
- */
372
- setKnownDimensions(model, dimensions) {
373
- this.knownModelDimensions[model] = dimensions;
374
- if (this.modelLookup) this.modelLookup.set(model.toLowerCase(), dimensions);
375
- }
376
- /**
377
- * Static method to parse embedding model configuration using the singleton instance.
378
- * This maintains backward compatibility while using the class-based approach.
379
- */
380
- static parseEmbeddingConfig(modelSpec) {
381
- return EmbeddingConfig.getInstance().parse(modelSpec);
382
- }
383
- /**
384
- * Static method to get known model dimensions using the singleton instance.
385
- * This maintains backward compatibility while using the class-based approach.
386
- */
387
- static getKnownModelDimensions(model) {
388
- return EmbeddingConfig.getInstance().getKnownDimensions(model);
389
- }
390
- /**
391
- * Static method to set known model dimensions using the singleton instance.
392
- * This maintains backward compatibility while using the class-based approach.
393
- */
394
- static setKnownModelDimensions(model, dimensions) {
395
- EmbeddingConfig.getInstance().setKnownDimensions(model, dimensions);
396
- }
397
- };
398
- //#endregion
399
- //#region src/utils/paths.ts
400
- var projectRoot = null;
401
- /**
402
- * Finds the project root directory by searching upwards from the current file
403
- * for a directory containing 'package.json'. Caches the result.
404
- *
405
- * @returns {string} The absolute path to the project root.
406
- * @throws {Error} If package.json cannot be found.
407
- */
408
- function getProjectRoot() {
409
- if (projectRoot) return projectRoot;
410
- const currentFilePath = fileURLToPath(import.meta.url);
411
- let currentDir = path.dirname(currentFilePath);
412
- while (true) {
413
- const packageJsonPath = path.join(currentDir, "package.json");
414
- if (fs.existsSync(packageJsonPath)) {
415
- projectRoot = currentDir;
416
- return currentDir;
417
- }
418
- const parentDir = path.dirname(currentDir);
419
- if (parentDir === currentDir) throw new Error("Could not find project root containing package.json.");
420
- currentDir = parentDir;
421
- }
422
- }
423
- /**
424
- * Resolves the data storage path using the following priority:
425
- * 1. Provided storePath parameter
426
- * 2. Legacy .store directory in project root (if exists)
427
- * 3. Standard system data directory using env-paths
428
- *
429
- * @param storePath Optional custom storage path
430
- * @returns Resolved absolute path for data storage
431
- */
432
- function resolveStorePath(storePath) {
433
- let dbDir;
434
- if (storePath) dbDir = path.resolve(storePath);
435
- else {
436
- const projectRoot = getProjectRoot();
437
- const oldDbDir = path.join(projectRoot, ".store");
438
- const oldDbPath = path.join(oldDbDir, "documents.db");
439
- if (fs.existsSync(oldDbPath)) dbDir = oldDbDir;
440
- else dbDir = envPaths("docs-mcp-server", { suffix: "" }).data;
441
- }
442
- try {
443
- fs.mkdirSync(dbDir, { recursive: true });
444
- } catch (error) {
445
- logger.warn(`⚠️ Failed to create database directory ${dbDir}: ${error}`);
446
- }
447
- return dbDir;
448
- }
449
- //#endregion
450
- //#region src/telemetry/TelemetryConfig.ts
451
- /**
452
- * Telemetry configuration management for enabling/disabling analytics collection.
453
- * Handles CLI flags, environment variables, and default settings.
454
- */
455
- var TelemetryConfig = class TelemetryConfig {
456
- static instance;
457
- enabled = true;
458
- constructor() {}
459
- isEnabled() {
460
- return this.enabled;
461
- }
462
- setEnabled(enabled) {
463
- this.enabled = enabled;
464
- }
465
- static getInstance() {
466
- if (!TelemetryConfig.instance) TelemetryConfig.instance = new TelemetryConfig();
467
- return TelemetryConfig.instance;
468
- }
469
- };
470
- /**
471
- * Generate or retrieve a persistent installation identifier.
472
- * Creates a UUID and stores it in a file in the user data directory.
473
- * Supports custom store path override for Docker deployments.
474
- * This ensures truly unique identification that persists across runs.
475
- */
476
- function generateInstallationId(storePath) {
477
- try {
478
- const dataDir = resolveStorePath(storePath);
479
- const installationIdPath = path.join(dataDir, "installation.id");
480
- if (fs.existsSync(installationIdPath)) {
481
- const existingId = fs.readFileSync(installationIdPath, "utf8").trim();
482
- if (existingId) return existingId;
483
- }
484
- const newId = randomUUID();
485
- fs.mkdirSync(dataDir, { recursive: true });
486
- fs.writeFileSync(installationIdPath, newId, "utf8");
487
- return newId;
488
- } catch {
489
- return randomUUID();
490
- }
491
- }
492
- /**
493
- * Check if telemetry should be enabled based on environment and CLI flags.
494
- */
495
- function shouldEnableTelemetry() {
496
- return TelemetryConfig.getInstance().isEnabled();
497
- }
498
- //#endregion
499
- //#region src/events/types.ts
500
- /**
501
- * Event type enum used by the EventBusService.
502
- * These are the internal event identifiers.
503
- */
504
- var EventType = /* @__PURE__ */ function(EventType) {
505
- EventType["JOB_STATUS_CHANGE"] = "JOB_STATUS_CHANGE";
506
- EventType["JOB_PROGRESS"] = "JOB_PROGRESS";
507
- EventType["LIBRARY_CHANGE"] = "LIBRARY_CHANGE";
508
- EventType["JOB_LIST_CHANGE"] = "JOB_LIST_CHANGE";
509
- return EventType;
510
- }({});
511
- //#endregion
512
- //#region src/pipeline/types.ts
513
- /**
514
- * Represents the possible states of a pipeline job.
515
- */
516
- var PipelineJobStatus = /* @__PURE__ */ function(PipelineJobStatus) {
517
- PipelineJobStatus["QUEUED"] = "queued";
518
- PipelineJobStatus["RUNNING"] = "running";
519
- PipelineJobStatus["COMPLETED"] = "completed";
520
- PipelineJobStatus["FAILED"] = "failed";
521
- PipelineJobStatus["CANCELLING"] = "cancelling";
522
- PipelineJobStatus["CANCELLED"] = "cancelled";
523
- return PipelineJobStatus;
524
- }({});
525
- //#endregion
526
- //#region src/telemetry/postHogClient.ts
527
- /**
528
- * PostHog client wrapper for telemetry events.
529
- * Handles PostHog SDK integration and event capture with privacy-first configuration.
530
- * Automatically converts camelCase property names to snake_case for PostHog compatibility.
531
- */
532
- /**
533
- * Convert camelCase string to snake_case
534
- * Specifically designed for PostHog property name conversion
535
- */
536
- function camelToSnakeCase(str) {
537
- return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
538
- }
539
- /**
540
- * Recursively convert object keys from camelCase to snake_case
541
- * Handles nested objects and arrays while preserving values
542
- */
543
- function convertPropertiesToSnakeCase(obj) {
544
- const result = {};
545
- for (const [key, value] of Object.entries(obj)) {
546
- const snakeKey = camelToSnakeCase(key);
547
- if (value && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date)) result[snakeKey] = convertPropertiesToSnakeCase(value);
548
- else if (Array.isArray(value)) result[snakeKey] = value.map((item) => item && typeof item === "object" && !(item instanceof Date) ? convertPropertiesToSnakeCase(item) : item);
549
- else result[snakeKey] = value;
550
- }
551
- return result;
552
- }
553
- /**
554
- * Add PostHog standard properties and remove duplicates
555
- * Maps our properties to PostHog's expected property names
556
- */
557
- function addPostHogStandardProperties(properties) {
558
- const result = { ...properties };
559
- if (properties.sessionId) {
560
- result.$session_id = properties.sessionId;
561
- delete result.sessionId;
562
- }
563
- if (properties.startTime) {
564
- result.$start_timestamp = properties.startTime.toISOString();
565
- delete result.startTime;
566
- }
567
- if (properties.appVersion) {
568
- result.$app_version = properties.appVersion;
569
- delete result.appVersion;
570
- }
571
- return result;
572
- }
573
- /**
574
- * PostHog client wrapper for telemetry events
575
- */
576
- var PostHogClient = class PostHogClient {
577
- client;
578
- enabled;
579
- static CONFIG = {
580
- host: "https://app.posthog.com",
581
- flushAt: 20,
582
- flushInterval: 1e4,
583
- disableGeoip: true,
584
- disableSessionRecording: true,
585
- disableSurveys: true,
586
- persistence: "memory"
587
- };
588
- constructor(enabled) {
589
- this.enabled = enabled;
590
- if (!this.enabled) return;
591
- try {
592
- this.client = new PostHog("phc_g7pXZZdUiAQXdnwUANjloQWMvO0amEDTBaeDSWgXgrQ", {
593
- host: PostHogClient.CONFIG.host,
594
- flushAt: PostHogClient.CONFIG.flushAt,
595
- flushInterval: PostHogClient.CONFIG.flushInterval,
596
- disableGeoip: PostHogClient.CONFIG.disableGeoip
597
- });
598
- logger.debug("PostHog client initialized");
599
- } catch (error) {
600
- logger.debug(`PostHog initialization failed: ${error instanceof Error ? error.message : "Unknown error"}`);
601
- this.enabled = false;
602
- }
603
- }
604
- /**
605
- * Send event to PostHog
606
- */
607
- capture(distinctId, event, properties) {
608
- if (!this.enabled || !this.client) return;
609
- try {
610
- const snakeCaseProperties = convertPropertiesToSnakeCase(addPostHogStandardProperties(properties));
611
- this.client.capture({
612
- distinctId,
613
- event,
614
- properties: snakeCaseProperties
615
- });
616
- logger.debug(`PostHog event captured: ${event}`);
617
- } catch (error) {
618
- logger.debug(`PostHog capture error: ${error instanceof Error ? error.message : "Unknown error"}`);
619
- }
620
- }
621
- /**
622
- * Capture exception using PostHog's native error tracking
623
- */
624
- captureException(distinctId, error, properties) {
625
- if (!this.enabled || !this.client) return;
626
- try {
627
- const snakeCaseProperties = convertPropertiesToSnakeCase(addPostHogStandardProperties(properties || {}));
628
- this.client.captureException({
629
- error,
630
- distinctId,
631
- properties: snakeCaseProperties
632
- });
633
- logger.debug(`PostHog exception captured: ${error.constructor.name}`);
634
- } catch (captureError) {
635
- logger.debug(`PostHog captureException error: ${captureError instanceof Error ? captureError.message : "Unknown error"}`);
636
- }
637
- }
638
- /**
639
- * Graceful shutdown with event flushing
640
- */
641
- async shutdown() {
642
- if (this.client) try {
643
- await this.client.shutdown();
644
- logger.debug("PostHog client shutdown complete");
645
- } catch (error) {
646
- logger.debug(`PostHog shutdown error: ${error instanceof Error ? error.message : "Unknown error"}`);
647
- }
648
- }
649
- /**
650
- * Check if client is enabled and ready
651
- */
652
- isEnabled() {
653
- return this.enabled && !!this.client;
654
- }
655
- };
656
- //#endregion
657
- //#region src/telemetry/telemetry.ts
658
- /**
659
- * Telemtry wrapper for privacy-first telemetry using PostHog.
660
- * Provides global context and automatic data sanitization.
661
- *
662
- * Architecture:
663
- * - PostHogClient: Handles PostHog SDK integration and event capture
664
- * - Telemtry: High-level coordinator providing public API with global context
665
- */
666
- /**
667
- * Event types for structured telemetry tracking
668
- */
669
- var TelemetryEvent = /* @__PURE__ */ function(TelemetryEvent) {
670
- TelemetryEvent["APP_STARTED"] = "app_started";
671
- TelemetryEvent["APP_SHUTDOWN"] = "app_shutdown";
672
- TelemetryEvent["CLI_COMMAND"] = "cli_command";
673
- TelemetryEvent["TOOL_USED"] = "tool_used";
674
- TelemetryEvent["PIPELINE_JOB_STARTED"] = "pipeline_job_started";
675
- TelemetryEvent["PIPELINE_JOB_COMPLETED"] = "pipeline_job_completed";
676
- TelemetryEvent["PIPELINE_JOB_FAILED"] = "pipeline_job_failed";
677
- return TelemetryEvent;
678
- }({});
679
- /**
680
- * Main telemetry class providing privacy-first telemetry
681
- */
682
- var Telemetry = class Telemetry {
683
- postHogClient;
684
- enabled;
685
- distinctId;
686
- globalContext = {};
687
- /**
688
- * Create a new Telemetry instance with proper initialization
689
- * This is the recommended way to create Telemetry instances
690
- */
691
- static create() {
692
- const config = TelemetryConfig.getInstance();
693
- const shouldEnable = config.isEnabled() && true;
694
- const telemetry = new Telemetry(shouldEnable);
695
- if (telemetry.isEnabled()) logger.debug("Telemetry enabled");
696
- else if (!config.isEnabled()) logger.debug("Telemetry disabled (user preference)");
697
- else logger.debug("Telemetry disabled");
698
- return telemetry;
699
- }
700
- /**
701
- * Private constructor - use Telemetry.create() instead
702
- */
703
- constructor(enabled = true) {
704
- this.enabled = enabled;
705
- this.distinctId = generateInstallationId();
706
- this.postHogClient = new PostHogClient(this.enabled);
707
- }
708
- /**
709
- * Set global application context that will be included in all events
710
- */
711
- setGlobalContext(context) {
712
- this.globalContext = { ...context };
713
- }
714
- /**
715
- * Get current global context
716
- */
717
- getGlobalContext() {
718
- return { ...this.globalContext };
719
- }
720
- track(event, properties = {}) {
721
- if (!this.enabled) return;
722
- const enrichedProperties = {
723
- ...this.globalContext,
724
- ...properties,
725
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
726
- };
727
- logger.debug(`Tracking event: ${event}`);
728
- this.postHogClient.capture(this.distinctId, event, enrichedProperties);
729
- }
730
- /**
731
- * Capture exception using PostHog's native error tracking with global context
732
- */
733
- captureException(error, properties = {}) {
734
- if (!this.enabled) return;
735
- const enrichedProperties = {
736
- ...this.globalContext,
737
- ...properties,
738
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
739
- };
740
- logger.debug(`Capturing exception: ${error instanceof Error ? error.message : String(error)}`);
741
- this.postHogClient.captureException(this.distinctId, error instanceof Error ? error : new Error(String(error)), enrichedProperties);
742
- }
743
- /**
744
- * Graceful shutdown with event flushing
745
- */
746
- async shutdown() {
747
- if (!this.enabled) return;
748
- await this.postHogClient.shutdown();
749
- }
750
- /**
751
- * Check if telemetry is enabled
752
- */
753
- isEnabled() {
754
- return this.enabled;
755
- }
756
- };
757
- /**
758
- * Global telemetry instance - initialized lazily
759
- */
760
- var telemetryInstance = null;
761
- /**
762
- * Get the global telemetry instance, initializing it if needed
763
- */
764
- function getTelemetryInstance() {
765
- if (!telemetryInstance) telemetryInstance = Telemetry.create();
766
- return telemetryInstance;
767
- }
768
- /**
769
- * Initialize telemetry system with proper configuration.
770
- * This should be called once at application startup.
771
- */
772
- function initTelemetry(options) {
773
- TelemetryConfig.getInstance().setEnabled(options.enabled);
774
- generateInstallationId(options.storePath);
775
- telemetryInstance = Telemetry.create();
776
- }
777
- var telemetry = new Proxy({}, { get(_target, prop) {
778
- const instance = getTelemetryInstance();
779
- const value = instance[prop];
780
- if (typeof value === "function") return value.bind(instance);
781
- return value;
782
- } });
783
- //#endregion
784
- //#region src/telemetry/TelemetryService.ts
785
- var TelemetryService = class {
786
- eventBus;
787
- unsubscribers = [];
788
- constructor(eventBus) {
789
- this.eventBus = eventBus;
790
- this.setupEventListeners();
791
- }
792
- /**
793
- * Sets up event listeners for pipeline events.
794
- */
795
- setupEventListeners() {
796
- const unsubStatusChange = this.eventBus.on(EventType.JOB_STATUS_CHANGE, this.handleJobStatusChange.bind(this));
797
- const unsubProgress = this.eventBus.on(EventType.JOB_PROGRESS, this.handleJobProgress.bind(this));
798
- this.unsubscribers.push(unsubStatusChange, unsubProgress);
799
- logger.debug("TelemetryService initialized and listening to events");
800
- }
801
- /**
802
- * Handles job status change events and tracks them to analytics.
803
- * Only tracks events for meaningful state transitions: started, completed, and failed.
804
- */
805
- handleJobStatusChange(job) {
806
- const duration = job.startedAt ? Date.now() - job.startedAt.getTime() : null;
807
- const queueWaitTime = job.startedAt && job.createdAt ? job.startedAt.getTime() - job.createdAt.getTime() : null;
808
- switch (job.status) {
809
- case PipelineJobStatus.RUNNING:
810
- telemetry.track(TelemetryEvent.PIPELINE_JOB_STARTED, {
811
- jobId: job.id,
812
- library: job.library,
813
- hasVersion: !!job.version,
814
- maxPagesConfigured: job.scraperOptions?.maxPages ?? null,
815
- queueWaitTimeMs: queueWaitTime
816
- });
817
- break;
818
- case PipelineJobStatus.COMPLETED:
819
- telemetry.track(TelemetryEvent.PIPELINE_JOB_COMPLETED, {
820
- jobId: job.id,
821
- library: job.library,
822
- durationMs: duration,
823
- pagesProcessed: job.progressPages || 0,
824
- maxPagesConfigured: job.scraperOptions?.maxPages ?? null,
825
- hasVersion: !!job.version,
826
- throughputPagesPerSecond: duration && job.progressPages ? Math.round(job.progressPages / duration * 1e3) : 0
827
- });
828
- break;
829
- case PipelineJobStatus.FAILED:
830
- telemetry.track(TelemetryEvent.PIPELINE_JOB_FAILED, {
831
- jobId: job.id,
832
- library: job.library,
833
- durationMs: duration,
834
- pagesProcessed: job.progressPages || 0,
835
- maxPagesConfigured: job.scraperOptions?.maxPages ?? null,
836
- hasVersion: !!job.version,
837
- hasError: !!job.error,
838
- errorMessage: job.error?.message
839
- });
840
- break;
841
- default: break;
842
- }
843
- }
844
- /**
845
- * Handles job progress events. Currently a no-op but can be extended
846
- * for progress-specific telemetry tracking.
847
- */
848
- handleJobProgress(_event) {}
849
- /**
850
- * Cleans up event listeners.
851
- */
852
- shutdown() {
853
- for (const unsubscribe of this.unsubscribers) unsubscribe();
854
- this.unsubscribers = [];
855
- logger.debug("TelemetryService shut down");
856
- }
857
- };
858
- //#endregion
859
- //#region src/events/EventBusService.ts
860
- /**
861
- * Central event bus service for application-wide event distribution.
862
- *
863
- * This service provides a pub/sub mechanism that can be used by any service
864
- * to emit and listen for events. Events emitted here can be:
865
- * - Consumed locally by in-process subscribers
866
- * - Broadcast to remote processes via tRPC subscriptions
867
- * - Forwarded to SSE clients via the web service
868
- *
869
- * This decouples event producers (like DocumentManagementService) from
870
- * consumers (like the Web UI), enabling a clean, scalable architecture.
871
- */
872
- /**
873
- * Central event bus for application-wide events.
874
- */
875
- var EventBusService = class {
876
- emitter;
877
- constructor() {
878
- this.emitter = new EventEmitter();
879
- this.emitter.setMaxListeners(100);
880
- }
881
- /**
882
- * Emit an event to all subscribers.
883
- */
884
- emit(eventType, payload) {
885
- logger.debug(`Event emitted: ${eventType}`);
886
- this.emitter.emit(eventType, payload);
887
- }
888
- /**
889
- * Subscribe to events of a specific type.
890
- * Returns an unsubscribe function.
891
- */
892
- on(eventType, listener) {
893
- this.emitter.on(eventType, listener);
894
- return () => this.emitter.off(eventType, listener);
895
- }
896
- /**
897
- * Subscribe to events once (auto-unsubscribes after first event).
898
- */
899
- once(eventType, listener) {
900
- this.emitter.once(eventType, listener);
901
- }
902
- /**
903
- * Remove a specific listener.
904
- */
905
- off(eventType, listener) {
906
- this.emitter.off(eventType, listener);
907
- }
908
- /**
909
- * Remove all listeners for a specific event type, or all listeners if no type specified.
910
- */
911
- removeAllListeners(eventType) {
912
- if (eventType === void 0) this.emitter.removeAllListeners();
913
- else this.emitter.removeAllListeners(eventType);
914
- }
915
- /**
916
- * Get the count of listeners for a specific event type.
917
- */
918
- listenerCount(eventType) {
919
- return this.emitter.listenerCount(eventType);
920
- }
921
- };
922
- //#endregion
923
- //#region src/cli/utils.ts
924
- /**
925
- * Shared CLI utilities and helper functions.
926
- */
927
- /**
928
- * Retrieves the global EventBusService from the arguments context.
929
- * @param argv The parsed arguments context.
930
- * @returns The global EventBusService.
931
- * @throws Error if EventBusService is not initialized.
932
- */
933
- function getEventBus(argv) {
934
- const eventBus = argv._eventBus;
935
- if (!eventBus) throw new Error("EventBusService not initialized");
936
- return eventBus;
937
- }
938
- /**
939
- * Helper to extract GlobalOptions from the argv.
940
- * In Yargs, all options are in argv, so we just cast/pick.
941
- */
942
- function getGlobalOptions(argv) {
943
- return argv;
944
- }
945
- /**
946
- * Ensures that the Playwright browsers are installed, unless a system Chromium path is set.
947
- */
948
- function ensurePlaywrightBrowsersInstalled() {
949
- if (process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD === "1") {
950
- logger.debug("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD is set, skipping Playwright browser install.");
951
- return;
952
- }
953
- const chromiumEnvPath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH;
954
- if (chromiumEnvPath && existsSync(chromiumEnvPath)) {
955
- logger.debug(`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH is set to '${chromiumEnvPath}', skipping Playwright browser install.`);
956
- return;
957
- }
958
- try {
959
- const chromiumPath = chromium.executablePath();
960
- if (!chromiumPath || !existsSync(chromiumPath)) throw new Error("Playwright Chromium browser not found");
961
- } catch (error) {
962
- logger.debug(String(error));
963
- try {
964
- logger.info("🌐 Installing Playwright Chromium browser... (this may take a moment)");
965
- execSync("npm exec -y playwright install --no-shell --with-deps chromium", {
966
- stdio: "ignore",
967
- cwd: getProjectRoot()
968
- });
969
- } catch (_installErr) {
970
- logger.error("❌ Failed to install Playwright browsers automatically. Please run:\n npx playwright install --no-shell --with-deps chromium\nand try again.");
971
- process.exit(1);
972
- }
973
- }
974
- }
975
- /**
976
- * Resolves the protocol based on auto-detection or explicit specification.
977
- * Auto-detection uses TTY status to determine appropriate protocol.
978
- */
979
- function resolveProtocol(protocol) {
980
- if (protocol === "auto") {
981
- if (!process.stdin.isTTY && !process.stdout.isTTY) return "stdio";
982
- return "http";
983
- }
984
- if (protocol === "stdio" || protocol === "http") return protocol;
985
- throw new Error(`Invalid protocol: ${protocol}. Must be 'auto', 'stdio', or 'http'`);
986
- }
987
- /**
988
- * Validates that --resume flag is only used with in-process workers.
989
- */
990
- function validateResumeFlag(resume, serverUrl) {
991
- if (resume && serverUrl) throw new Error("--resume flag is incompatible with --server-url. External workers handle their own job recovery.");
992
- }
993
- /**
994
- * Validates and parses port number
995
- */
996
- function validatePort(portString) {
997
- const port = Number.parseInt(portString, 10);
998
- if (Number.isNaN(port) || port < 1 || port > 65535) throw new Error("Invalid port number");
999
- return port;
1000
- }
1001
- /**
1002
- * Validates host string for basic format checking
1003
- */
1004
- function validateHost(hostString) {
1005
- const trimmed = hostString.trim();
1006
- if (!trimmed) throw new Error("Host cannot be empty");
1007
- if (trimmed.includes(" ") || trimmed.includes(" ") || trimmed.includes("\n")) throw new Error("Host cannot contain whitespace");
1008
- return trimmed;
1009
- }
1010
- /**
1011
- * Creates AppServerConfig based on service requirements.
1012
- *
1013
- * AppConfig is the source of truth for host/auth/telemetry/read-only settings.
1014
- * AppServerConfig only selects which services to run and which port to bind to.
1015
- */
1016
- function createAppServerConfig(options) {
1017
- return {
1018
- enableWebInterface: options.enableWebInterface ?? false,
1019
- enableMcpServer: options.enableMcpServer ?? true,
1020
- enableApiServer: options.enableApiServer ?? false,
1021
- enableWorker: options.enableWorker ?? true,
1022
- port: options.port,
1023
- externalWorkerUrl: options.externalWorkerUrl,
1024
- showLogo: options.showLogo ?? true,
1025
- startupContext: options.startupContext
1026
- };
1027
- }
1028
- /**
1029
- * Parses custom headers from CLI options
1030
- */
1031
- function parseHeaders(headerOptions) {
1032
- const headers = {};
1033
- if (Array.isArray(headerOptions)) for (const entry of headerOptions) {
1034
- const idx = entry.indexOf(":");
1035
- if (idx > 0) {
1036
- const name = entry.slice(0, idx).trim();
1037
- const value = entry.slice(idx + 1).trim();
1038
- if (name) headers[name] = value;
1039
- }
1040
- }
1041
- return headers;
1042
- }
1043
- /**
1044
- * Parses auth configuration from CLI options.
1045
- * Environment variables are handled by createOptionWithEnv in command definitions.
1046
- * Precedence: CLI flags > env vars (handled by commander) > defaults
1047
- */
1048
- function parseAuthConfig(options) {
1049
- if (!options.authEnabled) return;
1050
- return {
1051
- enabled: true,
1052
- issuerUrl: options.authIssuerUrl,
1053
- audience: options.authAudience,
1054
- scopes: ["openid", "profile"]
1055
- };
1056
- }
1057
- /**
1058
- * Validates auth configuration when auth is enabled.
1059
- */
1060
- function validateAuthConfig(authConfig) {
1061
- if (!authConfig.enabled) return;
1062
- const errors = [];
1063
- if (!authConfig.issuerUrl) errors.push("--auth-issuer-url is required when auth is enabled");
1064
- else try {
1065
- if (new URL(authConfig.issuerUrl).protocol !== "https:") errors.push("Issuer URL must use HTTPS protocol");
1066
- } catch {
1067
- errors.push("Issuer URL must be a valid URL");
1068
- }
1069
- if (!authConfig.audience) errors.push("--auth-audience is required when auth is enabled");
1070
- else try {
1071
- const url = new URL(authConfig.audience);
1072
- if (url.protocol === "http:" && url.hostname !== "localhost") logger.warn("⚠️ Audience uses HTTP protocol - consider using HTTPS for production");
1073
- if (url.hash) errors.push("Audience must not contain URL fragments");
1074
- } catch {
1075
- if (authConfig.audience.startsWith("urn:")) {
1076
- const urnParts = authConfig.audience.split(":");
1077
- if (urnParts.length < 3 || !urnParts[1] || !urnParts[2]) errors.push("URN audience must follow format: urn:namespace:specific-string");
1078
- } else errors.push("Audience must be a valid absolute URL or URN (e.g., https://api.example.com or urn:company:service)");
1079
- }
1080
- if (errors.length > 0) throw new Error(`Auth configuration validation failed:\n${errors.join("\n")}`);
1081
- }
1082
- /**
1083
- * Warns about HTTP usage in production when auth is enabled.
1084
- */
1085
- function warnHttpUsage(authConfig, port) {
1086
- if (!authConfig?.enabled) return;
1087
- if (!(process.env.NODE_ENV !== "production" || port === 6280 || process.env.HOSTNAME?.includes("localhost"))) logger.warn("⚠️ Authentication is enabled but running over HTTP in production. Consider using HTTPS for security.");
1088
- }
1089
- /**
1090
- * Creates EventBusService and TelemetryService together.
1091
- * The TelemetryService automatically subscribes to events from the EventBusService.
1092
- * @returns Object containing both services
1093
- */
1094
- function createEventServices() {
1095
- const eventBus = new EventBusService();
1096
- return {
1097
- eventBus,
1098
- telemetryService: new TelemetryService(eventBus)
1099
- };
1100
- }
1101
- /**
1102
- * Resolves embedding configuration from the provided model specification.
1103
- * This function centralizes the logic for determining the embedding model.
1104
- *
1105
- * @param embeddingModel The embedding model specification string.
1106
- * @returns Embedding configuration or null if config is unavailable.
1107
- */
1108
- function resolveEmbeddingContext(embeddingModel) {
1109
- try {
1110
- const modelSpec = embeddingModel;
1111
- if (!modelSpec) {
1112
- logger.debug("No embedding model specified. Embeddings are disabled.");
1113
- return null;
1114
- }
1115
- logger.debug(`Resolving embedding configuration for model: ${modelSpec}`);
1116
- return EmbeddingConfig.parseEmbeddingConfig(modelSpec);
1117
- } catch (error) {
1118
- logger.debug(`Failed to resolve embedding configuration: ${error}`);
1119
- return null;
1120
- }
1121
- }
1122
- /**
1123
- * Prompts the user interactively to confirm an embedding model change.
1124
- * Returns true if the user confirms (y/Y), false otherwise.
1125
- */
1126
- function promptModelChangeConfirmation(previousModel, previousDimension, currentModel, currentDimension) {
1127
- return new Promise((resolve) => {
1128
- console.error(`\n⚠️ Embedding model change detected:\n Previous: ${previousModel} (${previousDimension} dimensions)\n Current: ${currentModel} (${currentDimension} dimensions)\n\n All existing embedding vectors will be invalidated.\n Libraries must be re-scraped to restore vector search.\n Full-text search will continue working for all existing documents.\n`);
1129
- const rl = createInterface({
1130
- input: process.stdin,
1131
- output: process.stderr
1132
- });
1133
- rl.question(" Proceed with model change? (y/N) ", (answer) => {
1134
- rl.close();
1135
- resolve(answer.trim().toLowerCase() === "y");
1136
- });
1137
- });
1138
- }
1139
- /**
1140
- * Handles EmbeddingModelChangedError during service initialization.
1141
- *
1142
- * - In non-interactive mode (no TTY): re-throws the error to fail startup.
1143
- * - In interactive mode (TTY): prompts the user for confirmation, then either
1144
- * resolves the model change (invalidates vectors) or exits.
1145
- *
1146
- * @param error The EmbeddingModelChangedError thrown by DocumentStore.initialize()
1147
- * @param service The DocumentManagementService instance (already partially initialized)
1148
- * @throws Re-throws the error in non-interactive mode or if the user rejects the change
1149
- */
1150
- async function handleEmbeddingModelChange(error, service) {
1151
- if (!process.stdin.isTTY || !process.stdout.isTTY) throw error;
1152
- if (!await promptModelChangeConfirmation(error.previousModel, error.previousDimension, error.currentModel, error.currentDimension)) throw new Error("Embedding model change rejected. Startup aborted.\nRestore the previous embedding model configuration to continue without changes.");
1153
- await service.resolveModelChange();
1154
- }
1155
- //#endregion
1156
- export { shouldEnableTelemetry as C, SUPPORTED_PROVIDERS as D, EmbeddingConfig as E, splitModelSpec as O, EventType as S, resolveStorePath as T, TelemetryService as _, getGlobalOptions as a, telemetry as b, parseHeaders as c, validateAuthConfig as d, validateHost as f, EventBusService as g, warnHttpUsage as h, getEventBus as i, resolveEmbeddingContext as l, validateResumeFlag as m, createEventServices as n, handleEmbeddingModelChange as o, validatePort as p, ensurePlaywrightBrowsersInstalled as r, parseAuthConfig as s, createAppServerConfig as t, resolveProtocol as u, TelemetryEvent as v, getProjectRoot as w, PipelineJobStatus as x, initTelemetry as y };
1157
-
1158
- //# sourceMappingURL=utils-uCqhR-rj.js.map