@arabold/docs-mcp-server 2.4.2 → 2.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 (34) hide show
  1. package/db/migrations/002-normalize-library-table.sql +5 -0
  2. package/db/migrations/003-normalize-vector-table.sql +5 -0
  3. package/db/migrations/004-complete-normalization.sql +7 -0
  4. package/db/migrations/007-dedupe-unversioned-versions.sql +5 -0
  5. package/db/migrations/009-add-pages-table.sql +10 -0
  6. package/db/migrations/014-rebuild-vector-partition-keys.sql +56 -0
  7. package/dist/HtmlDefuddleMiddleware-Cm0vQDqD.js +148 -0
  8. package/dist/HtmlDefuddleMiddleware-Cm0vQDqD.js.map +1 -0
  9. package/dist/assets/main.css +3 -1
  10. package/dist/assets/main.js +7845 -8777
  11. package/dist/assets/main.js.map +1 -1
  12. package/dist/env-DONvEfR5.js +30 -0
  13. package/dist/env-DONvEfR5.js.map +1 -0
  14. package/dist/index.js +10 -8
  15. package/dist/index.js.map +1 -1
  16. package/dist/logger-BBxstTD7.js +82 -0
  17. package/dist/logger-BBxstTD7.js.map +1 -0
  18. package/dist/main-BktKic6L.js +18646 -0
  19. package/dist/main-BktKic6L.js.map +1 -0
  20. package/dist/utils-B-zX5sgp.js +1113 -0
  21. package/dist/utils-B-zX5sgp.js.map +1 -0
  22. package/dist/utils-LjYa0nIu.js +2 -0
  23. package/package.json +61 -61
  24. package/public/assets/main.css +3 -1
  25. package/public/assets/main.js +7845 -8777
  26. package/public/assets/main.js.map +1 -1
  27. package/dist/HtmlDefuddleMiddleware-DjhdN_D2.js +0 -152
  28. package/dist/HtmlDefuddleMiddleware-DjhdN_D2.js.map +0 -1
  29. package/dist/logger-CLtABTNb.js +0 -99
  30. package/dist/logger-CLtABTNb.js.map +0 -1
  31. package/dist/main-WZKPkgC6.js +0 -20454
  32. package/dist/main-WZKPkgC6.js.map +0 -1
  33. package/dist/utils-CJgh41os.js +0 -1152
  34. package/dist/utils-CJgh41os.js.map +0 -1
@@ -1,152 +0,0 @@
1
- import * as cheerio from "cheerio";
2
- import { Defuddle } from "defuddle/node";
3
- import { parseHTML } from "linkedom";
4
- import { l as logger } from "./logger-CLtABTNb.js";
5
- const DEFAULT_MIN_RETENTION = 0.01;
6
- class HtmlDefuddleMiddleware {
7
- minTextRetentionRatio;
8
- constructor(options = {}) {
9
- this.minTextRetentionRatio = options.minTextRetentionRatio ?? DEFAULT_MIN_RETENTION;
10
- }
11
- async process(context, next) {
12
- const $ = context.dom;
13
- if (!$) {
14
- logger.warn(
15
- `⏭️ Skipping ${this.constructor.name}: context.dom is missing. Ensure HtmlCheerioParserMiddleware runs before this.`
16
- );
17
- await next();
18
- return;
19
- }
20
- try {
21
- const originalHtml = $.html();
22
- const $bodyClone = cheerio.load(`<body>${$("body").html() ?? ""}</body>`);
23
- $bodyClone("script, style, noscript, template").remove();
24
- const textLengthBefore = $bodyClone("body").text().trim().length;
25
- const { document } = parseHTML(originalHtml);
26
- this.applyExcludePreDefuddle(document, context);
27
- this.propagateLanguageHints(document);
28
- const result = await Defuddle(document, context.source, {
29
- // We do markdown conversion downstream (HtmlToMarkdownMiddleware), so
30
- // ask Defuddle for cleaned HTML, not markdown.
31
- markdown: false
32
- });
33
- const cleanedContent = typeof result?.content === "string" ? result.content : "";
34
- const wrappedHtml = `<!doctype html><html><head><title>${escapeHtml(result.title || context.title || "")}</title></head><body>${cleanedContent}</body></html>`;
35
- const cleaned$ = cheerio.load(wrappedHtml);
36
- cleaned$("script, style, noscript, iframe, svg, link, meta").remove();
37
- const cleanedText = cleaned$("body").text().trim();
38
- const ratio = textLengthBefore > 0 ? cleanedText.length / textLengthBefore : 0;
39
- if (!cleanedText || ratio < this.minTextRetentionRatio) {
40
- logger.warn(
41
- `⚠️ Defuddle retained ${cleanedText.length}/${textLengthBefore} chars (${(ratio * 100).toFixed(1)}%) for ${context.source}; falling back to original DOM with minimal sanitisation.`
42
- );
43
- $("script, style, noscript, iframe, svg, link, meta").remove();
44
- await next();
45
- return;
46
- }
47
- context.dom = cleaned$;
48
- if (!context.title && result.title) {
49
- context.title = result.title;
50
- }
51
- logger.debug(
52
- `Defuddle reduced body text from ${textLengthBefore} to ${cleanedText.length} chars (${(ratio * 100).toFixed(1)}%) for ${context.source}`
53
- );
54
- } catch (error) {
55
- logger.error(`❌ Defuddle extraction failed for ${context.source}: ${error}`);
56
- context.errors.push(
57
- error instanceof Error ? error : new Error(`Defuddle extraction failed: ${String(error)}`)
58
- );
59
- }
60
- await next();
61
- }
62
- /**
63
- * Normalise each `<pre>` so Defuddle preserves its language hint.
64
- *
65
- * Defuddle's standardise step strips `class="language-X"` unless `X` is one
66
- * of its allow-listed canonical language names (so `language-python3`,
67
- * `language-py`, etc. get dropped). It also unwraps highlighter ancestors
68
- * like `<div class="highlight-python3">`, losing that context entirely.
69
- *
70
- * However, Defuddle preserves `data-language` (and `data-lang`) verbatim and
71
- * promotes them to `class="language-X"` on the inner `<code>`. So this
72
- * pre-pass collects the language hint from `<pre>`, `<code>`, or nearby
73
- * ancestor classes and writes it back as `data-language` on `<pre>`. Our
74
- * Turndown rule in HtmlToMarkdownMiddleware then reads it off and emits a
75
- * fenced code block with the correct language.
76
- */
77
- propagateLanguageHints(document) {
78
- const pres = document.querySelectorAll("pre");
79
- for (const pre of Array.from(pres)) {
80
- const existingCode = pre.querySelector("code");
81
- if (pre.getAttribute("data-language")) continue;
82
- let lang = detectLanguageFromClass(pre.getAttribute("class")) || detectLanguageFromClass(existingCode?.getAttribute("class") ?? null);
83
- if (!lang) {
84
- let ancestor = pre.parentElement;
85
- let depth2 = 0;
86
- while (ancestor && depth2 < 5) {
87
- const found = detectLanguageFromClass(ancestor.getAttribute("class"));
88
- if (found) {
89
- lang = found;
90
- break;
91
- }
92
- ancestor = ancestor.parentElement;
93
- depth2++;
94
- }
95
- }
96
- if (!lang) continue;
97
- pre.setAttribute("data-language", lang);
98
- let wrapper = pre.parentElement;
99
- let depth = 0;
100
- while (wrapper && depth < 5) {
101
- const cls = wrapper.getAttribute("class") ?? "";
102
- const isHighlightWrapper = /(?:^|\s)(?:highlight|highlight-source-[A-Za-z0-9_+-]+|highlight-[A-Za-z0-9_+-]+)(?:\s|$)/.test(
103
- cls
104
- );
105
- if (isHighlightWrapper && wrapper.children.length === 1 && wrapper.parentElement) {
106
- wrapper.parentElement.replaceChild(pre, wrapper);
107
- wrapper = pre.parentElement;
108
- } else {
109
- break;
110
- }
111
- depth++;
112
- }
113
- }
114
- }
115
- applyExcludePreDefuddle(document, context) {
116
- const selectors = context.options.excludeSelectors ?? [];
117
- if (selectors.length === 0) return;
118
- for (const selector of selectors) {
119
- try {
120
- const matches = document.querySelectorAll(selector);
121
- for (const node of Array.from(matches)) {
122
- const tag = node.tagName?.toLowerCase();
123
- if (tag === "html" || tag === "body") continue;
124
- node.remove();
125
- }
126
- } catch (selectorError) {
127
- logger.warn(
128
- `⚠️ Invalid excludeSelector "${selector}" before Defuddle: ${selectorError}`
129
- );
130
- context.errors.push(
131
- new Error(`Invalid selector "${selector}": ${selectorError}`)
132
- );
133
- }
134
- }
135
- }
136
- }
137
- const LANGUAGE_CLASS_RE = /(?:^|\s)(?:highlight-source-|highlight-|language-)([A-Za-z0-9_+-]+)/;
138
- function detectLanguageFromClass(className) {
139
- if (!className) return "";
140
- const match = LANGUAGE_CLASS_RE.exec(className);
141
- if (!match) return "";
142
- const lang = match[1].toLowerCase();
143
- if (lang === "text" || lang === "highlighted" || lang === "wrap") return "";
144
- return lang;
145
- }
146
- function escapeHtml(value) {
147
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
148
- }
149
- export {
150
- HtmlDefuddleMiddleware
151
- };
152
- //# sourceMappingURL=HtmlDefuddleMiddleware-DjhdN_D2.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"HtmlDefuddleMiddleware-DjhdN_D2.js","sources":["../src/scraper/middleware/HtmlDefuddleMiddleware.ts"],"sourcesContent":["import * as cheerio from \"cheerio\";\nimport { Defuddle } from \"defuddle/node\";\nimport { parseHTML } from \"linkedom\";\nimport { logger } from \"../../utils/logger\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\n/**\n * Options for HtmlDefuddleMiddleware.\n */\nexport interface HtmlDefuddleOptions {\n /**\n * If Defuddle's extracted content drops below this fraction of the original\n * *visible* text length (script/style/noscript excluded), fall back to the\n * pre-extraction DOM. Set very low by default — Defuddle is intentionally\n * aggressive, and the more useful safety net is the empty-output check\n * below. The ratio is here mainly to catch catastrophic mis-extraction\n * (Defuddle latches onto a tiny element on a content-rich page).\n */\n minTextRetentionRatio?: number;\n}\n\nconst DEFAULT_MIN_RETENTION = 0.01;\n\n/**\n * Middleware that runs Defuddle as a drop-in replacement for\n * {@link HtmlSanitizerMiddleware}. It extracts the main article content,\n * removing navigation, footers, ads, and other boilerplate using Defuddle's\n * heuristics rather than a hand-maintained selector list.\n *\n * Pipeline contract:\n * - Reads HTML from `context.dom` (populated by HtmlCheerioParserMiddleware).\n * - Runs Defuddle via linkedom and replaces `context.dom` with a fresh Cheerio\n * DOM containing only the cleaned content (wrapped in `<html><body>…`).\n * - Honours `context.options.excludeSelectors` by stripping them from the\n * *source* DOM before Defuddle runs. Defuddle's standardise step unwraps\n * class/id hooks, so post-extraction selector matching is unreliable;\n * filtering on the source DOM matches the Cheerio sanitiser's behaviour\n * and the user's mental model.\n * - Updates `context.title` if Defuddle found a non-empty title and the\n * previous extractor left it empty.\n * - Falls back to the original DOM if Defuddle returns empty output or removes\n * substantially all text (see {@link minTextRetentionRatio}).\n */\nexport class HtmlDefuddleMiddleware implements ContentProcessorMiddleware {\n private readonly minTextRetentionRatio: number;\n\n constructor(options: HtmlDefuddleOptions = {}) {\n this.minTextRetentionRatio = options.minTextRetentionRatio ?? DEFAULT_MIN_RETENTION;\n }\n\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n const $ = context.dom;\n if (!$) {\n logger.warn(\n `⏭️ Skipping ${this.constructor.name}: context.dom is missing. Ensure HtmlCheerioParserMiddleware runs before this.`,\n );\n await next();\n return;\n }\n\n try {\n const originalHtml = $.html();\n // Measure *visible* text, excluding script/style content. SPA pages\n // (Next.js, Nuxt, etc.) embed huge hydration payloads inside <script>\n // tags whose textContent inflates the body text length by orders of\n // magnitude, which would otherwise trip the retention-ratio fallback.\n const $bodyClone = cheerio.load(`<body>${$(\"body\").html() ?? \"\"}</body>`);\n $bodyClone(\"script, style, noscript, template\").remove();\n const textLengthBefore = $bodyClone(\"body\").text().trim().length;\n\n const { document } = parseHTML(originalHtml);\n\n // Apply user-supplied excludeSelectors *before* Defuddle. Defuddle\n // standardises markup (e.g. unwrapping divs into <p>), which strips the\n // class/id hooks the user supplied — so post-extraction removal often\n // misses. Filtering on the source DOM matches the user's mental model\n // (same as the Cheerio sanitiser path).\n this.applyExcludePreDefuddle(document, context);\n\n // Defuddle's `standardize` step unwraps the language-bearing ancestor\n // divs that highlighters like Pygments/Sphinx and GitHub use (e.g.\n // `<div class=\"highlight-python3\"><pre>...</pre></div>`). Push the\n // detected language onto the inner `<code>` as `class=\"language-X\"` so\n // Defuddle preserves it and our Turndown rule can recover the fenced\n // code-block language.\n this.propagateLanguageHints(document);\n\n const result = await Defuddle(document, context.source, {\n // We do markdown conversion downstream (HtmlToMarkdownMiddleware), so\n // ask Defuddle for cleaned HTML, not markdown.\n markdown: false,\n });\n\n const cleanedContent = typeof result?.content === \"string\" ? result.content : \"\";\n\n // Build the cleaned Cheerio DOM *first*, then measure retention on the\n // post-sanitisation text. Doing the regex-strip-then-measure dance in\n // the other order let `<script>` *contents* (e.g. Next.js `__next_f`\n // hydration payloads) inflate the \"kept\" character count so the ratio\n // check passed, after which removing the script tags emptied the page.\n //\n // Note on H1 handling: Defuddle's standardize step deliberately drops\n // the first H1/H2 when it matches the extracted title (and converts\n // remaining H1s to H2s). The dropped headline text is preserved on\n // `context.title`, which the indexer attaches to every chunk as\n // metadata — so it's still searchable, just not duplicated inside the\n // chunk body. Defuddle exposes no granular flag to opt out of this\n // single behaviour (only the coarse `standardize: false` which would\n // also disable code-block / footnote standardisation).\n const wrappedHtml = `<!doctype html><html><head><title>${escapeHtml(result.title || context.title || \"\")}</title></head><body>${cleanedContent}</body></html>`;\n const cleaned$ = cheerio.load(wrappedHtml);\n\n // Strip dangerous / non-content tags. Defuddle can leak these (Next.js\n // hydration payloads being the worst offender) and they're never useful\n // in indexed markdown.\n cleaned$(\"script, style, noscript, iframe, svg, link, meta\").remove();\n\n // Measure retention on the post-strip text so the ratio reflects what\n // actually survives into the chunked output.\n const cleanedText = cleaned$(\"body\").text().trim();\n const ratio = textLengthBefore > 0 ? cleanedText.length / textLengthBefore : 0;\n\n if (!cleanedText || ratio < this.minTextRetentionRatio) {\n logger.warn(\n `⚠️ Defuddle retained ${cleanedText.length}/${textLengthBefore} chars (${(ratio * 100).toFixed(1)}%) for ${context.source}; falling back to original DOM with minimal sanitisation.`,\n );\n // Strip script/style/iframe defensively even on fallback — without\n // these the markdown converter renders hydration payloads (e.g.\n // Next.js __next_f) as multi-hundred-KB blobs.\n $(\"script, style, noscript, iframe, svg, link, meta\").remove();\n await next();\n return;\n }\n\n context.dom = cleaned$;\n if (!context.title && result.title) {\n context.title = result.title;\n }\n\n logger.debug(\n `Defuddle reduced body text from ${textLengthBefore} to ${cleanedText.length} chars (${(ratio * 100).toFixed(1)}%) for ${context.source}`,\n );\n } catch (error) {\n logger.error(`❌ Defuddle extraction failed for ${context.source}: ${error}`);\n context.errors.push(\n error instanceof Error\n ? error\n : new Error(`Defuddle extraction failed: ${String(error)}`),\n );\n }\n\n await next();\n }\n\n /**\n * Normalise each `<pre>` so Defuddle preserves its language hint.\n *\n * Defuddle's standardise step strips `class=\"language-X\"` unless `X` is one\n * of its allow-listed canonical language names (so `language-python3`,\n * `language-py`, etc. get dropped). It also unwraps highlighter ancestors\n * like `<div class=\"highlight-python3\">`, losing that context entirely.\n *\n * However, Defuddle preserves `data-language` (and `data-lang`) verbatim and\n * promotes them to `class=\"language-X\"` on the inner `<code>`. So this\n * pre-pass collects the language hint from `<pre>`, `<code>`, or nearby\n * ancestor classes and writes it back as `data-language` on `<pre>`. Our\n * Turndown rule in HtmlToMarkdownMiddleware then reads it off and emits a\n * fenced code block with the correct language.\n */\n private propagateLanguageHints(document: Document): void {\n const pres = document.querySelectorAll(\"pre\");\n for (const pre of Array.from(pres)) {\n const existingCode = pre.querySelector(\"code\");\n\n // Already set explicitly — leave alone.\n if (pre.getAttribute(\"data-language\")) continue;\n\n let lang =\n detectLanguageFromClass(pre.getAttribute(\"class\")) ||\n detectLanguageFromClass(existingCode?.getAttribute(\"class\") ?? null);\n\n if (!lang) {\n let ancestor: Element | null = pre.parentElement;\n let depth = 0;\n while (ancestor && depth < 5) {\n const found = detectLanguageFromClass(ancestor.getAttribute(\"class\"));\n if (found) {\n lang = found;\n break;\n }\n ancestor = ancestor.parentElement;\n depth++;\n }\n }\n\n if (!lang) continue;\n\n pre.setAttribute(\"data-language\", lang);\n\n // Unwrap any highlighter wrapper divs around this <pre>. Defuddle's\n // standardise step rewrites the `<pre>` (stripping its attributes,\n // including our data-language) when it sees this wrapped structure.\n // Replacing the wrapper with the bare <pre> sidesteps that path.\n let wrapper: Element | null = pre.parentElement;\n let depth = 0;\n while (wrapper && depth < 5) {\n const cls = wrapper.getAttribute(\"class\") ?? \"\";\n const isHighlightWrapper =\n /(?:^|\\s)(?:highlight|highlight-source-[A-Za-z0-9_+-]+|highlight-[A-Za-z0-9_+-]+)(?:\\s|$)/.test(\n cls,\n );\n if (\n isHighlightWrapper &&\n wrapper.children.length === 1 &&\n wrapper.parentElement\n ) {\n wrapper.parentElement.replaceChild(pre, wrapper);\n wrapper = pre.parentElement;\n } else {\n break;\n }\n depth++;\n }\n }\n }\n\n private applyExcludePreDefuddle(document: Document, context: MiddlewareContext): void {\n const selectors = context.options.excludeSelectors ?? [];\n if (selectors.length === 0) return;\n\n for (const selector of selectors) {\n try {\n const matches = document.querySelectorAll(selector);\n for (const node of Array.from(matches)) {\n const tag = node.tagName?.toLowerCase();\n if (tag === \"html\" || tag === \"body\") continue;\n node.remove();\n }\n } catch (selectorError) {\n logger.warn(\n `⚠️ Invalid excludeSelector \"${selector}\" before Defuddle: ${selectorError}`,\n );\n context.errors.push(\n new Error(`Invalid selector \"${selector}\": ${selectorError}`),\n );\n }\n }\n }\n}\n\nconst LANGUAGE_CLASS_RE =\n /(?:^|\\s)(?:highlight-source-|highlight-|language-)([A-Za-z0-9_+-]+)/;\n\nfunction detectLanguageFromClass(className: string | null | undefined): string {\n if (!className) return \"\";\n const match = LANGUAGE_CLASS_RE.exec(className);\n if (!match) return \"\";\n const lang = match[1].toLowerCase();\n // Skip generic non-language tokens that show up under `highlight-` prefix.\n if (lang === \"text\" || lang === \"highlighted\" || lang === \"wrap\") return \"\";\n return lang;\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n"],"names":["depth"],"mappings":";;;;AAqBA,MAAM,wBAAwB;AAsBvB,MAAM,uBAA6D;AAAA,EACvD;AAAA,EAEjB,YAAY,UAA+B,IAAI;AAC7C,SAAK,wBAAwB,QAAQ,yBAAyB;AAAA,EAChE;AAAA,EAEA,MAAM,QAAQ,SAA4B,MAA0C;AAClF,UAAM,IAAI,QAAQ;AAClB,QAAI,CAAC,GAAG;AACN,aAAO;AAAA,QACL,eAAe,KAAK,YAAY,IAAI;AAAA,MAAA;AAEtC,YAAM,KAAA;AACN;AAAA,IACF;AAEA,QAAI;AACF,YAAM,eAAe,EAAE,KAAA;AAKvB,YAAM,aAAa,QAAQ,KAAK,SAAS,EAAE,MAAM,EAAE,KAAA,KAAU,EAAE,SAAS;AACxE,iBAAW,mCAAmC,EAAE,OAAA;AAChD,YAAM,mBAAmB,WAAW,MAAM,EAAE,KAAA,EAAO,OAAO;AAE1D,YAAM,EAAE,SAAA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K,OAAO,GAAG;AACtC,gBAAM,MAAM,KAAK,SAAS,YAAA;AAC1B,cAAI,QAAQ,UAAU,QAAQ,OAAQ;AACtC,eAAK,OAAA;AAAA,QACP;AAAA,MACF,SAAS,eAAe;AACtB,eAAO;AAAA,UACL,gCAAgC,QAAQ,sBAAsB,aAAa;AAAA,QAAA;AAE7E,gBAAQ,OAAO;AAAA,UACb,IAAI,MAAM,qBAAqB,QAAQ,MAAM,aAAa,EAAE;AAAA,QAAA;AAAA,MAEhE;AAAA,IACF;AAAA,EACF;AACF;AAEA,MAAM,oBACJ;AAEF,SAAS,wBAAwB,WAA8C;AAC7E,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,QAAQ,kBAAkB,KAAK,SAAS;AAC9C,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,OAAO,MAAM,CAAC,EAAE,YAAA;AAEtB,MAAI,SAAS,UAAU,SAAS,iBAAiB,SAAS,OAAQ,QAAO;AACzE,SAAO;AACT;AAEA,SAAS,WAAW,OAAuB;AACzC,SAAO,MACJ,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ;AAC3B;"}
@@ -1,99 +0,0 @@
1
- function normalizeEnvValue(value) {
2
- const trimmed = value.trim();
3
- if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) {
4
- return trimmed.slice(1, -1);
5
- }
6
- return trimmed;
7
- }
8
- function sanitizeEnvironment(env = process.env) {
9
- const sanitizedKeys = [];
10
- for (const [key, value] of Object.entries(env)) {
11
- if (value === void 0) {
12
- continue;
13
- }
14
- const normalized = normalizeEnvValue(value);
15
- if (normalized !== value) {
16
- env[key] = normalized;
17
- sanitizedKeys.push(key);
18
- }
19
- }
20
- return sanitizedKeys;
21
- }
22
- const LogLevel = {
23
- ERROR: 0,
24
- WARN: 1,
25
- INFO: 2,
26
- DEBUG: 3
27
- };
28
- const LOG_LEVEL_MAP = {
29
- ERROR: LogLevel.ERROR,
30
- WARN: LogLevel.WARN,
31
- INFO: LogLevel.INFO,
32
- DEBUG: LogLevel.DEBUG
33
- };
34
- function suppressLogsInTests() {
35
- return !!process.env.VITEST_WORKER_ID && process.env.ENABLE_TEST_LOGS !== "1";
36
- }
37
- function isInteractiveSession() {
38
- return !!process.stdout.isTTY && !!process.stderr.isTTY;
39
- }
40
- function writeToStderr(message) {
41
- process.stderr.write(message.endsWith("\n") ? message : `${message}
42
- `);
43
- }
44
- function getLogLevelFromEnv() {
45
- const envLevel = process.env.LOG_LEVEL?.toUpperCase();
46
- return envLevel && envLevel in LOG_LEVEL_MAP ? LOG_LEVEL_MAP[envLevel] : null;
47
- }
48
- let currentLogLevel = getLogLevelFromEnv() ?? (isInteractiveSession() ? LogLevel.INFO : LogLevel.ERROR);
49
- function setLogLevel(level) {
50
- currentLogLevel = level;
51
- }
52
- const logger = {
53
- /**
54
- * Logs a debug message if the current log level is DEBUG or higher.
55
- * @param message - The message to log.
56
- */
57
- debug: (message) => {
58
- if (currentLogLevel >= LogLevel.DEBUG && !suppressLogsInTests()) {
59
- writeToStderr(message);
60
- }
61
- },
62
- /**
63
- * Logs an info message if the current log level is INFO or higher.
64
- * @param message - The message to log.
65
- */
66
- info: (message) => {
67
- if (currentLogLevel >= LogLevel.INFO && !suppressLogsInTests()) {
68
- writeToStderr(message);
69
- }
70
- },
71
- /**
72
- * Logs a warning message if the current log level is WARN or higher.
73
- * @param message - The message to log.
74
- */
75
- warn: (message) => {
76
- if (currentLogLevel >= LogLevel.WARN && !suppressLogsInTests()) {
77
- writeToStderr(message);
78
- }
79
- },
80
- /**
81
- * Logs an error message if the current log level is ERROR or higher.
82
- * Suppressed during test runs unless `ENABLE_TEST_LOGS=1` is set.
83
- * @param message - The message to log.
84
- */
85
- error: (message) => {
86
- if (currentLogLevel >= LogLevel.ERROR && !suppressLogsInTests()) {
87
- writeToStderr(message);
88
- }
89
- }
90
- };
91
- export {
92
- LogLevel as L,
93
- setLogLevel as a,
94
- getLogLevelFromEnv as g,
95
- logger as l,
96
- normalizeEnvValue as n,
97
- sanitizeEnvironment as s
98
- };
99
- //# sourceMappingURL=logger-CLtABTNb.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"logger-CLtABTNb.js","sources":["../src/utils/env.ts","../src/utils/logger.ts"],"sourcesContent":["/**\n * Normalize a single environment variable value by trimming surrounding whitespace\n * and removing matching outer quotes. Internal quotes are preserved.\n */\nexport function normalizeEnvValue(value: string): string {\n const trimmed = value.trim();\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n return trimmed.slice(1, -1);\n }\n return trimmed;\n}\n\n/**\n * Normalize all string values in process.env in place.\n * Returns the names of environment variables that changed.\n */\nexport function sanitizeEnvironment(env: NodeJS.ProcessEnv = process.env): string[] {\n const sanitizedKeys: string[] = [];\n\n for (const [key, value] of Object.entries(env)) {\n if (value === undefined) {\n continue;\n }\n\n const normalized = normalizeEnvValue(value);\n if (normalized !== value) {\n env[key] = normalized;\n sanitizedKeys.push(key);\n }\n }\n\n return sanitizedKeys;\n}\n","/**\n * Defines the available log levels.\n */\nexport const LogLevel = {\n ERROR: 0,\n WARN: 1,\n INFO: 2,\n DEBUG: 3,\n} as const;\n\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];\n\n/**\n * Maps string log level names to their numeric values.\n */\nconst LOG_LEVEL_MAP: Record<string, LogLevel> = {\n ERROR: LogLevel.ERROR,\n WARN: LogLevel.WARN,\n INFO: LogLevel.INFO,\n DEBUG: LogLevel.DEBUG,\n};\n\nfunction suppressLogsInTests(): boolean {\n return !!process.env.VITEST_WORKER_ID && process.env.ENABLE_TEST_LOGS !== \"1\";\n}\n\nfunction isInteractiveSession(): boolean {\n return !!process.stdout.isTTY && !!process.stderr.isTTY;\n}\n\nfunction writeToStderr(message: string): void {\n process.stderr.write(message.endsWith(\"\\n\") ? message : `${message}\\n`);\n}\n\n/**\n * Gets the log level from the `LOG_LEVEL` environment variable.\n * Returns the matching {@link LogLevel} value, or `null` if the variable\n * is unset or contains an unrecognised value.\n */\nexport function getLogLevelFromEnv(): LogLevel | null {\n const envLevel = process.env.LOG_LEVEL?.toUpperCase();\n return envLevel && envLevel in LOG_LEVEL_MAP ? LOG_LEVEL_MAP[envLevel] : null;\n}\n\nlet currentLogLevel: LogLevel =\n getLogLevelFromEnv() ?? (isInteractiveSession() ? LogLevel.INFO : LogLevel.ERROR);\n\n/**\n * Sets the current logging level for the application.\n */\nexport function setLogLevel(level: LogLevel): void {\n currentLogLevel = level;\n}\n\n/**\n * Returns the current logging level for the application.\n */\nexport function getLogLevel(): LogLevel {\n return currentLogLevel;\n}\n\n/**\n * Provides logging functionalities with level control.\n */\nexport const logger = {\n /**\n * Logs a debug message if the current log level is DEBUG or higher.\n * @param message - The message to log.\n */\n debug: (message: string) => {\n if (currentLogLevel >= LogLevel.DEBUG && !suppressLogsInTests()) {\n writeToStderr(message);\n }\n },\n /**\n * Logs an info message if the current log level is INFO or higher.\n * @param message - The message to log.\n */\n info: (message: string) => {\n if (currentLogLevel >= LogLevel.INFO && !suppressLogsInTests()) {\n writeToStderr(message);\n }\n },\n /**\n * Logs a warning message if the current log level is WARN or higher.\n * @param message - The message to log.\n */\n warn: (message: string) => {\n if (currentLogLevel >= LogLevel.WARN && !suppressLogsInTests()) {\n writeToStderr(message);\n }\n },\n /**\n * Logs an error message if the current log level is ERROR or higher.\n * Suppressed during test runs unless `ENABLE_TEST_LOGS=1` is set.\n * @param message - The message to log.\n */\n error: (message: string) => {\n if (currentLogLevel >= LogLevel.ERROR && !suppressLogsInTests()) {\n writeToStderr(message);\n }\n },\n};\n"],"names":[],"mappings":"AAIO,SAAS,kBAAkB,OAAuB;AACvD,QAAM,UAAU,MAAM,KAAA;AACtB,MACG,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,KAC/C,QAAQ,W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