@gitpagedocs/tools 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +34 -0
  2. package/package.json +38 -0
  3. package/src/ai/bootstrap.ts +50 -0
  4. package/src/ai/catalog.ts +209 -0
  5. package/src/ai/env-credentials.ts +29 -0
  6. package/src/ai/factory.ts +14 -0
  7. package/src/ai/http/streaming.ts +52 -0
  8. package/src/ai/index.ts +32 -0
  9. package/src/ai/legacy-adapter.ts +33 -0
  10. package/src/ai/model-registry.ts +13 -0
  11. package/src/ai/providers/anthropic-provider.ts +77 -0
  12. package/src/ai/providers/cohere-provider.ts +66 -0
  13. package/src/ai/providers/gemini-provider.ts +84 -0
  14. package/src/ai/providers/ollama-provider.ts +69 -0
  15. package/src/ai/providers/openai-compatible-provider.ts +75 -0
  16. package/src/ai/providers/shared.ts +94 -0
  17. package/src/ai/registry.ts +29 -0
  18. package/src/cache/file-cache.ts +86 -0
  19. package/src/cache/index.ts +9 -0
  20. package/src/cache/memory-cache.ts +47 -0
  21. package/src/cache/web-storage-cache.ts +91 -0
  22. package/src/config/config-loader.ts +59 -0
  23. package/src/config/index.ts +1 -0
  24. package/src/constants/config.ts +8 -0
  25. package/src/constants/index.ts +1 -0
  26. package/src/crypto/doc-access.ts +64 -0
  27. package/src/crypto/index.ts +4 -0
  28. package/src/crypto/node-crypto-service.ts +87 -0
  29. package/src/crypto/web-crypto-service.ts +104 -0
  30. package/src/crypto/web.ts +4 -0
  31. package/src/documentation/doc-generator.ts +74 -0
  32. package/src/documentation/doc-updater.ts +47 -0
  33. package/src/documentation/index.ts +18 -0
  34. package/src/documentation/marker-patcher.ts +33 -0
  35. package/src/documentation/sections.ts +84 -0
  36. package/src/errors/app-error.ts +84 -0
  37. package/src/errors/index.ts +1 -0
  38. package/src/filesystem/file-service.ts +158 -0
  39. package/src/filesystem/index.ts +2 -0
  40. package/src/i18n/index.ts +36 -0
  41. package/src/i18n/language-bundles.ts +289 -0
  42. package/src/index.ts +26 -0
  43. package/src/logger/index.ts +2 -0
  44. package/src/logger/logger.ts +73 -0
  45. package/src/logger/redaction.ts +43 -0
  46. package/src/platform/index.ts +1 -0
  47. package/src/platform/user-config-dir.ts +48 -0
  48. package/src/ports/ai.ts +109 -0
  49. package/src/ports/cache.ts +16 -0
  50. package/src/ports/config.ts +21 -0
  51. package/src/ports/crypto.ts +33 -0
  52. package/src/ports/index.ts +15 -0
  53. package/src/ports/logger.ts +23 -0
  54. package/src/ports/security.ts +42 -0
  55. package/src/security/credential-vault.ts +117 -0
  56. package/src/security/file-vault-storage.ts +25 -0
  57. package/src/security/index.ts +8 -0
  58. package/src/security/migrate-plaintext-key.ts +38 -0
  59. package/src/security/password-gate.ts +62 -0
  60. package/src/security/web-storage-vault-storage.ts +23 -0
  61. package/src/security/web.ts +9 -0
@@ -0,0 +1,158 @@
1
+ import path from "node:path";
2
+ import { readFile, writeFile, mkdir, readdir, stat } from "node:fs/promises";
3
+ import { RepositoryError, ValidationError } from "../errors/app-error";
4
+
5
+ const DEFAULT_IGNORE = new Set([
6
+ "node_modules", ".git", ".next", "out", "dist", "prebuilt", ".turbo", "coverage",
7
+ ]);
8
+
9
+ export interface ListOptions {
10
+ recursive?: boolean;
11
+ maxEntries?: number;
12
+ }
13
+
14
+ export interface SearchOptions {
15
+ /** Restrict to files whose path includes this substring (e.g. ".ts"). */
16
+ extension?: string;
17
+ maxResults?: number;
18
+ maxFileBytes?: number;
19
+ }
20
+
21
+ export interface SearchMatch {
22
+ readonly file: string;
23
+ readonly line: number;
24
+ readonly text: string;
25
+ }
26
+
27
+ /** Extensions (lower-case, dot included) that `search()` scans by default. */
28
+ const TEXT_EXTENSIONS = new Set([
29
+ ".md", ".markdown", ".mdx", ".txt", ".json", ".yml", ".yaml",
30
+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
31
+ ".css", ".scss", ".htm", ".html", ".svg", ".toml", ".env",
32
+ ]);
33
+
34
+ /**
35
+ * Whether a repo-relative file path carries a text extension. The suffix after
36
+ * the last dot is compared, so a dotfile such as `.env` counts and a dot in a
37
+ * folder name (`dir.x/file`) does not.
38
+ */
39
+ function isTextFile(file: string): boolean {
40
+ const dot = file.lastIndexOf(".");
41
+ return dot !== -1 && TEXT_EXTENSIONS.has(file.slice(dot).toLowerCase());
42
+ }
43
+
44
+ /** Line matches of `needle` (already lower-cased) in one file, at most `limit`. */
45
+ function collectLineMatches(file: string, content: string, needle: string, limit: number): SearchMatch[] {
46
+ const found: SearchMatch[] = [];
47
+ const lines = content.split("\n");
48
+ for (let i = 0; i < lines.length && found.length < limit; i += 1) {
49
+ if (lines[i].toLowerCase().includes(needle)) {
50
+ found.push({ file, line: i + 1, text: lines[i].trim().slice(0, 240) });
51
+ }
52
+ }
53
+ return found;
54
+ }
55
+
56
+ /** Plain UTF-16 code-unit order (the default `sort()` order), independent of locale. */
57
+ function compareCodeUnits(a: string, b: string): number {
58
+ if (a < b) return -1;
59
+ if (a > b) return 1;
60
+ return 0;
61
+ }
62
+
63
+ /**
64
+ * Root-bounded filesystem service. All paths are resolved relative to `root`
65
+ * and may not escape it — the single safe FS surface for the CLI and MCP.
66
+ */
67
+ export class FileService {
68
+ constructor(private readonly root: string) {}
69
+
70
+ private resolveInside(relativePath: string): string {
71
+ const abs = path.resolve(this.root, relativePath);
72
+ const rel = path.relative(this.root, abs);
73
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
74
+ throw new ValidationError(`Path escapes the project root: ${relativePath}`);
75
+ }
76
+ return abs;
77
+ }
78
+
79
+ private toRel(abs: string): string {
80
+ return path.relative(this.root, abs).split(path.sep).join("/");
81
+ }
82
+
83
+ async list(relativeDir = ".", options: ListOptions = {}): Promise<string[]> {
84
+ const { recursive = false, maxEntries = 2000 } = options;
85
+ const start = this.resolveInside(relativeDir);
86
+ const out: string[] = [];
87
+
88
+ const walk = async (dir: string): Promise<void> => {
89
+ if (out.length >= maxEntries) return;
90
+ let entries: import("node:fs").Dirent[];
91
+ try {
92
+ entries = await readdir(dir, { withFileTypes: true });
93
+ } catch (cause) {
94
+ throw new RepositoryError(`Cannot read directory: ${this.toRel(dir)}`, { cause });
95
+ }
96
+ for (const entry of entries) {
97
+ if (DEFAULT_IGNORE.has(entry.name)) continue;
98
+ if (out.length >= maxEntries) break;
99
+ const abs = path.join(dir, entry.name);
100
+ out.push(this.toRel(abs) + (entry.isDirectory() ? "/" : ""));
101
+ if (recursive && entry.isDirectory()) await walk(abs);
102
+ }
103
+ };
104
+
105
+ await walk(start);
106
+ return out.sort(compareCodeUnits);
107
+ }
108
+
109
+ async read(relativePath: string, maxBytes = 512_000): Promise<string> {
110
+ const abs = this.resolveInside(relativePath);
111
+ const info = await stat(abs).catch((cause) => {
112
+ throw new RepositoryError(`File not found: ${relativePath}`, { cause });
113
+ });
114
+ if (info.size > maxBytes) {
115
+ throw new ValidationError(`File too large (${info.size} bytes > ${maxBytes}): ${relativePath}`);
116
+ }
117
+ return readFile(abs, "utf8");
118
+ }
119
+
120
+ async write(relativePath: string, content: string): Promise<string> {
121
+ const abs = this.resolveInside(relativePath);
122
+ await mkdir(path.dirname(abs), { recursive: true });
123
+ await writeFile(abs, content, "utf8");
124
+ return this.toRel(abs);
125
+ }
126
+
127
+ /** Directories are skipped; an explicit extension filter replaces the text-extension default. */
128
+ private static isSearchable(entry: string, extension?: string): boolean {
129
+ if (entry.endsWith("/")) return false;
130
+ return extension ? entry.endsWith(extension) : isTextFile(entry);
131
+ }
132
+
133
+ /** File content for searching, or undefined when it is missing, too large or unreadable. */
134
+ private async readForSearch(file: string, maxFileBytes: number): Promise<string | undefined> {
135
+ try {
136
+ return await this.read(file, maxFileBytes);
137
+ } catch {
138
+ return undefined;
139
+ }
140
+ }
141
+
142
+ async search(query: string, options: SearchOptions = {}): Promise<SearchMatch[]> {
143
+ if (!query.trim()) throw new ValidationError("Search query must not be empty.");
144
+ const { extension, maxResults = 200, maxFileBytes = 512_000 } = options;
145
+ const files = await this.list(".", { recursive: true, maxEntries: 5000 });
146
+ const matches: SearchMatch[] = [];
147
+ const needle = query.toLowerCase();
148
+
149
+ for (const file of files) {
150
+ if (matches.length >= maxResults) break;
151
+ if (!FileService.isSearchable(file, extension)) continue;
152
+ const content = await this.readForSearch(file, maxFileBytes);
153
+ if (content === undefined) continue;
154
+ matches.push(...collectLineMatches(file, content, needle, maxResults - matches.length));
155
+ }
156
+ return matches;
157
+ }
158
+ }
@@ -0,0 +1,2 @@
1
+ export { FileService } from "./file-service";
2
+ export type { ListOptions, SearchOptions, SearchMatch } from "./file-service";
@@ -0,0 +1,36 @@
1
+ export {
2
+ DEFAULT_LANGS_DIR,
3
+ DEFAULT_LANGS_MANIFEST_PATH,
4
+ LANGS_DIRNAME,
5
+ LANGS_MANIFEST_FILENAME,
6
+ applyLanguageBundles,
7
+ buildLanguageToggles,
8
+ filterEnabledLanguages,
9
+ getEnabledLanguages,
10
+ getLanguageBundlePath,
11
+ getSiteLanguageToggles,
12
+ isLanguageCode,
13
+ isLanguageEnabled,
14
+ loadConfigLanguageBundles,
15
+ loadLanguageBundles,
16
+ parseLanguageBundle,
17
+ parseLanguageManifest,
18
+ parseLanguageToggles,
19
+ resolveBundleLanguages,
20
+ splitLanguageBundles,
21
+ } from "./language-bundles";
22
+ export type {
23
+ InlineLangMenu,
24
+ InlineTranslationSection,
25
+ InlineTranslations,
26
+ JsonReader,
27
+ LanguageBundle,
28
+ LanguageBundleMap,
29
+ LanguageManifest,
30
+ LanguageStrings,
31
+ LanguageToggles,
32
+ LoadLanguageBundlesOptions,
33
+ LocalizableConfig,
34
+ LocalizableSite,
35
+ TranslationSections,
36
+ } from "./language-bundles";
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Language bundles — the UI strings of a gitpagedocs site, one JSON file per
3
+ * language, switched on and off from `config.json`:
4
+ *
5
+ * gitpagedocs/config.json { "site": { "languages": { "en": true, "pt": true, "es": false } } }
6
+ * gitpagedocs/langs/<lang>.json { "langmenu": {...}, "translations": {...} }
7
+ *
8
+ * `site.languages` is the only place a language is enabled (`true`) or disabled
9
+ * (`false`): a disabled language has its bundle skipped and is hidden from the
10
+ * language selector, even when its docs exist. A language the map does not
11
+ * mention stays enabled, so old configs keep every content language they ship.
12
+ *
13
+ * Historically the strings lived inline in `config.json` (`site.langmenu` keyed
14
+ * by language and `translations.<section>.<key>` keyed by language), and
15
+ * release 1.1.68 listed the languages in a separate `gitpagedocs/langs.json`
16
+ * manifest. Both still load: `applyLanguageBundles` folds the bundles back into
17
+ * the inline shape, so every consumer keeps reading `site.langmenu` /
18
+ * `translations` unchanged, and the manifest is read only when `config.json`
19
+ * carries no `site.languages`. Bundles win over inline strings.
20
+ */
21
+
22
+ export const LANGS_DIRNAME = "langs";
23
+ export const DEFAULT_LANGS_DIR = `gitpagedocs/${LANGS_DIRNAME}`;
24
+ /** Legacy (1.1.68) manifest; superseded by `site.languages` in config.json. */
25
+ export const LANGS_MANIFEST_FILENAME = "langs.json";
26
+ export const DEFAULT_LANGS_MANIFEST_PATH = `gitpagedocs/${LANGS_MANIFEST_FILENAME}`;
27
+
28
+ /** Language codes become file names, so they are kept to a safe alphabet. */
29
+ const LANGUAGE_CODE_PATTERN = /^[A-Za-z0-9]{2,8}(?:[-_][A-Za-z0-9]{1,8})?$/;
30
+
31
+ export type LanguageStrings = Record<string, string>;
32
+ export type TranslationSections = Record<string, LanguageStrings>;
33
+
34
+ /** `site.languages`: language code → enabled flag, in menu order. */
35
+ export type LanguageToggles = Record<string, boolean>;
36
+
37
+ /** Legacy `gitpagedocs/langs.json` shape. */
38
+ export interface LanguageManifest {
39
+ languages: string[];
40
+ }
41
+
42
+ export interface LanguageBundle {
43
+ langmenu?: LanguageStrings;
44
+ translations?: TranslationSections;
45
+ }
46
+
47
+ export type LanguageBundleMap = Record<string, LanguageBundle>;
48
+
49
+ /**
50
+ * Legacy inline shapes: `langmenu[lang][key]` and `translations[section][key][lang]`.
51
+ * Sections and keys may be absent, matching the optional fields of typed configs.
52
+ */
53
+ export type InlineLangMenu = Record<string, LanguageStrings>;
54
+ export type InlineTranslationSection = { [key: string]: LanguageStrings | undefined };
55
+ export type InlineTranslations = { [section: string]: InlineTranslationSection | undefined };
56
+
57
+ export interface LocalizableSite {
58
+ defaultLanguage?: string;
59
+ languages?: LanguageToggles;
60
+ langmenu?: InlineLangMenu;
61
+ supportedLanguages?: string[];
62
+ }
63
+
64
+ export interface LocalizableConfig {
65
+ site?: LocalizableSite;
66
+ translations?: InlineTranslations;
67
+ }
68
+
69
+ /** Reads a repo-relative JSON file; resolves null when it is missing or invalid. */
70
+ export type JsonReader = (relativePath: string) => Promise<unknown>;
71
+
72
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
73
+ return typeof value === "object" && value !== null && !Array.isArray(value);
74
+ }
75
+
76
+ function isStringRecord(value: unknown): value is LanguageStrings {
77
+ return isPlainObject(value) && Object.values(value).every((entry) => typeof entry === "string");
78
+ }
79
+
80
+ export function isLanguageCode(value: unknown): value is string {
81
+ return typeof value === "string" && LANGUAGE_CODE_PATTERN.test(value);
82
+ }
83
+
84
+ export function getLanguageBundlePath(language: string, langsDir: string = DEFAULT_LANGS_DIR): string {
85
+ return `${langsDir}/${language}.json`;
86
+ }
87
+
88
+ /** `{ en: true, pt: true }` for a language list; the generator's view of `site.languages`. */
89
+ export function buildLanguageToggles(languages: readonly string[], enabled = true): LanguageToggles {
90
+ const toggles: LanguageToggles = {};
91
+ for (const language of languages) toggles[language] = enabled;
92
+ return toggles;
93
+ }
94
+
95
+ /**
96
+ * Parses `site.languages`. Only valid codes with a boolean flag are kept, in
97
+ * key order; resolves null when nothing usable is there (legacy configs).
98
+ */
99
+ export function parseLanguageToggles(raw: unknown): LanguageToggles | null {
100
+ if (!isPlainObject(raw)) return null;
101
+ const toggles: LanguageToggles = {};
102
+ for (const [language, enabled] of Object.entries(raw)) {
103
+ if (isLanguageCode(language) && typeof enabled === "boolean") toggles[language] = enabled;
104
+ }
105
+ return Object.keys(toggles).length > 0 ? toggles : null;
106
+ }
107
+
108
+ export function getEnabledLanguages(toggles: LanguageToggles | null | undefined): string[] {
109
+ return Object.entries(toggles ?? {})
110
+ .filter(([, enabled]) => enabled)
111
+ .map(([language]) => language);
112
+ }
113
+
114
+ /** Only an explicit `false` disables a language; unknown codes stay enabled. */
115
+ export function isLanguageEnabled(toggles: LanguageToggles | null | undefined, language: string): boolean {
116
+ return toggles?.[language] !== false;
117
+ }
118
+
119
+ /**
120
+ * Drops the disabled languages from a content-derived list, keeping its order.
121
+ * A site can never end up without a language: when every entry is disabled the
122
+ * preferred (default) language survives, else the first one.
123
+ */
124
+ export function filterEnabledLanguages<T extends string>(
125
+ languages: readonly T[],
126
+ toggles: LanguageToggles | null | undefined,
127
+ preferred?: T,
128
+ ): T[] {
129
+ const enabled = languages.filter((language) => isLanguageEnabled(toggles, language));
130
+ if (enabled.length > 0 || languages.length === 0) return enabled;
131
+ const fallback = preferred !== undefined && languages.includes(preferred) ? preferred : languages[0];
132
+ return [fallback];
133
+ }
134
+
135
+ export function getSiteLanguageToggles(config: LocalizableConfig): LanguageToggles | null {
136
+ return parseLanguageToggles(config.site?.languages);
137
+ }
138
+
139
+ /** The bundles a config asks for: its enabled toggles, or null when it has none (legacy). */
140
+ export function resolveBundleLanguages(config: LocalizableConfig): string[] | null {
141
+ const toggles = getSiteLanguageToggles(config);
142
+ return toggles ? getEnabledLanguages(toggles) : null;
143
+ }
144
+
145
+ export function parseLanguageManifest(raw: unknown): LanguageManifest | null {
146
+ if (!isPlainObject(raw) || !Array.isArray(raw.languages)) return null;
147
+ const languages = Array.from(new Set(raw.languages.filter(isLanguageCode)));
148
+ return languages.length > 0 ? { languages } : null;
149
+ }
150
+
151
+ function parseTranslationSections(raw: unknown): TranslationSections | undefined {
152
+ if (!isPlainObject(raw)) return undefined;
153
+ const sections: TranslationSections = {};
154
+ for (const [section, strings] of Object.entries(raw)) {
155
+ if (isStringRecord(strings)) sections[section] = strings;
156
+ }
157
+ return sections;
158
+ }
159
+
160
+ export function parseLanguageBundle(raw: unknown): LanguageBundle | null {
161
+ if (!isPlainObject(raw)) return null;
162
+ const bundle: LanguageBundle = {};
163
+ if (isStringRecord(raw.langmenu)) bundle.langmenu = raw.langmenu;
164
+ const translations = parseTranslationSections(raw.translations);
165
+ if (translations) bundle.translations = translations;
166
+ return bundle;
167
+ }
168
+
169
+ export interface LoadLanguageBundlesOptions {
170
+ /** Languages to load (the enabled `site.languages`). Without it the legacy manifest is consulted. */
171
+ languages?: readonly string[];
172
+ manifestPath?: string;
173
+ langsDir?: string;
174
+ }
175
+
176
+ async function readLegacyManifestLanguages(readJson: JsonReader, manifestPath: string): Promise<string[] | null> {
177
+ const manifest = parseLanguageManifest(await readJson(manifestPath));
178
+ return manifest ? manifest.languages : null;
179
+ }
180
+
181
+ /**
182
+ * Loads one bundle per requested language. Resolves null when nothing is
183
+ * requested (legacy inline config without a manifest); bundles that are
184
+ * missing or malformed are skipped so one broken file never takes the other
185
+ * languages down.
186
+ */
187
+ export async function loadLanguageBundles(
188
+ readJson: JsonReader,
189
+ options: LoadLanguageBundlesOptions = {},
190
+ ): Promise<LanguageBundleMap | null> {
191
+ const languages =
192
+ options.languages ?? (await readLegacyManifestLanguages(readJson, options.manifestPath ?? DEFAULT_LANGS_MANIFEST_PATH));
193
+ if (!languages || languages.length === 0) return null;
194
+
195
+ const entries = await Promise.all(
196
+ languages.filter(isLanguageCode).map(async (language) => {
197
+ const bundle = parseLanguageBundle(await readJson(getLanguageBundlePath(language, options.langsDir)));
198
+ return [language, bundle] as const;
199
+ }),
200
+ );
201
+
202
+ const bundles: LanguageBundleMap = {};
203
+ for (const [language, bundle] of entries) {
204
+ if (bundle) bundles[language] = bundle;
205
+ }
206
+ return Object.keys(bundles).length > 0 ? bundles : null;
207
+ }
208
+
209
+ /** Loads the bundles `config.json` enables through `site.languages` (legacy manifest as fallback). */
210
+ export function loadConfigLanguageBundles(
211
+ config: LocalizableConfig,
212
+ readJson: JsonReader,
213
+ options: Omit<LoadLanguageBundlesOptions, "languages"> = {},
214
+ ): Promise<LanguageBundleMap | null> {
215
+ return loadLanguageBundles(readJson, { ...options, languages: resolveBundleLanguages(config) ?? undefined });
216
+ }
217
+
218
+ function mergeLangMenu(inline: InlineLangMenu | undefined, bundles: LanguageBundleMap): InlineLangMenu {
219
+ const merged: InlineLangMenu = { ...inline };
220
+ for (const [language, bundle] of Object.entries(bundles)) {
221
+ merged[language] = { ...inline?.[language], ...bundle.langmenu };
222
+ }
223
+ return merged;
224
+ }
225
+
226
+ function cloneTranslations(inline: InlineTranslations | undefined): Record<string, InlineTranslationSection> {
227
+ const cloned: Record<string, InlineTranslationSection> = {};
228
+ for (const [section, keys] of Object.entries(inline ?? {})) {
229
+ if (!keys) continue;
230
+ cloned[section] = {};
231
+ for (const [key, byLanguage] of Object.entries(keys)) {
232
+ if (byLanguage) cloned[section][key] = { ...byLanguage };
233
+ }
234
+ }
235
+ return cloned;
236
+ }
237
+
238
+ function mergeTranslations(inline: InlineTranslations | undefined, bundles: LanguageBundleMap): InlineTranslations {
239
+ const merged = cloneTranslations(inline);
240
+ for (const [language, bundle] of Object.entries(bundles)) {
241
+ for (const [section, strings] of Object.entries(bundle.translations ?? {})) {
242
+ const target = (merged[section] ??= {});
243
+ for (const [key, text] of Object.entries(strings)) {
244
+ target[key] = { ...target[key], [language]: text };
245
+ }
246
+ }
247
+ }
248
+ return merged;
249
+ }
250
+
251
+ /**
252
+ * Folds bundles into the legacy inline shape. The loaded bundles define
253
+ * `site.supportedLanguages`; `site.languages` and inline strings survive (the
254
+ * latter only for keys a bundle does not provide).
255
+ */
256
+ export function applyLanguageBundles<T extends LocalizableConfig>(config: T, bundles: LanguageBundleMap | null): T {
257
+ if (!bundles || Object.keys(bundles).length === 0) return config;
258
+ return {
259
+ ...config,
260
+ site: {
261
+ ...config.site,
262
+ langmenu: mergeLangMenu(config.site?.langmenu, bundles),
263
+ supportedLanguages: Object.keys(bundles),
264
+ },
265
+ translations: mergeTranslations(config.translations, bundles),
266
+ };
267
+ }
268
+
269
+ /** The generator-side inverse of `applyLanguageBundles`: one bundle per language. */
270
+ export function splitLanguageBundles(
271
+ languages: readonly string[],
272
+ langmenu: InlineLangMenu,
273
+ translations: InlineTranslations,
274
+ ): LanguageBundleMap {
275
+ const bundles: LanguageBundleMap = {};
276
+ for (const language of languages) {
277
+ const sections: TranslationSections = {};
278
+ for (const [section, keys] of Object.entries(translations)) {
279
+ const strings: LanguageStrings = {};
280
+ for (const [key, byLanguage] of Object.entries(keys ?? {})) {
281
+ const text = byLanguage?.[language];
282
+ if (typeof text === "string") strings[key] = text;
283
+ }
284
+ if (Object.keys(strings).length > 0) sections[section] = strings;
285
+ }
286
+ bundles[language] = { langmenu: { ...langmenu[language] }, translations: sections };
287
+ }
288
+ return bundles;
289
+ }
package/src/index.ts ADDED
@@ -0,0 +1,26 @@
1
+ // @gitpagedocs/tools — shared business-logic core.
2
+ //
3
+ // The single home for domain logic consumed by the frontend, the CLI and the
4
+ // MCP server. Consumers import from here (or subpath modules) and depend on the
5
+ // port interfaces, never on concrete adapters they don't need.
6
+
7
+ // Port contracts (type-only).
8
+ export type * from "./ports";
9
+
10
+ // Phase 4 — cross-cutting core implementations.
11
+ export * from "./errors";
12
+ export * from "./logger";
13
+ export * from "./crypto";
14
+ export * from "./cache";
15
+ export * from "./security";
16
+ export * from "./config";
17
+ export * from "./constants";
18
+ export * from "./platform";
19
+ export * from "./i18n";
20
+
21
+ // Phase 5 — shared AI system.
22
+ export * from "./ai";
23
+
24
+ // Phase 7 — filesystem + documentation services.
25
+ export * from "./filesystem";
26
+ export * from "./documentation";
@@ -0,0 +1,2 @@
1
+ export * from "./logger";
2
+ export { redact, redactFields, REDACTED } from "./redaction";
@@ -0,0 +1,73 @@
1
+ import type { Logger, LogFields, LogLevel, LogSink } from "../ports/logger";
2
+ import { redact, redactFields } from "./redaction";
3
+
4
+ const LEVEL_ORDER: Record<LogLevel, number> = { debug: 10, info: 20, warn: 30, error: 40 };
5
+
6
+ export interface LoggerOptions {
7
+ readonly level?: LogLevel;
8
+ readonly sink?: LogSink;
9
+ readonly baseFields?: LogFields;
10
+ }
11
+
12
+ /** Sink that writes redacted records to the console. */
13
+ export class ConsoleSink implements LogSink {
14
+ write(level: LogLevel, message: string, fields: LogFields): void {
15
+ const safeMessage = redact(message) as string;
16
+ const hasFields = Object.keys(fields).length > 0;
17
+ const payload = hasFields ? redactFields(fields as Record<string, unknown>) : undefined;
18
+ const line = `[${level}] ${safeMessage}`;
19
+ if (level === "error") console.error(line, payload ?? "");
20
+ else if (level === "warn") console.warn(line, payload ?? "");
21
+ else console.log(line, payload ?? "");
22
+ }
23
+ }
24
+
25
+ /** Discards all records (useful for tests / silent CLI runs). */
26
+ export class NullSink implements LogSink {
27
+ write(): void {
28
+ /* no-op */
29
+ }
30
+ }
31
+
32
+ class StandardLogger implements Logger {
33
+ private readonly level: LogLevel;
34
+ private readonly sink: LogSink;
35
+ private readonly baseFields: LogFields;
36
+
37
+ constructor(options: LoggerOptions) {
38
+ this.level = options.level ?? "info";
39
+ this.sink = options.sink ?? new ConsoleSink();
40
+ this.baseFields = options.baseFields ?? {};
41
+ }
42
+
43
+ private emit(level: LogLevel, message: string, fields?: LogFields): void {
44
+ if (LEVEL_ORDER[level] < LEVEL_ORDER[this.level]) return;
45
+ const merged = fields ? { ...this.baseFields, ...fields } : this.baseFields;
46
+ this.sink.write(level, message, merged);
47
+ }
48
+
49
+ debug(message: string, fields?: LogFields): void {
50
+ this.emit("debug", message, fields);
51
+ }
52
+ info(message: string, fields?: LogFields): void {
53
+ this.emit("info", message, fields);
54
+ }
55
+ warn(message: string, fields?: LogFields): void {
56
+ this.emit("warn", message, fields);
57
+ }
58
+ error(message: string, fields?: LogFields): void {
59
+ this.emit("error", message, fields);
60
+ }
61
+
62
+ child(fields: LogFields): Logger {
63
+ return new StandardLogger({
64
+ level: this.level,
65
+ sink: this.sink,
66
+ baseFields: { ...this.baseFields, ...fields },
67
+ });
68
+ }
69
+ }
70
+
71
+ export function createLogger(options: LoggerOptions = {}): Logger {
72
+ return new StandardLogger(options);
73
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Secret redaction. Applied to every log record before it reaches a sink so
3
+ * API keys and other credentials can never appear in logs.
4
+ */
5
+ const SENSITIVE_KEY_PATTERN = /(api[_-]?key|secret|token|password|passwd|authorization|bearer|x-api-key)/i;
6
+
7
+ /** Token-like values: long opaque strings, optionally with a provider prefix. */
8
+ const TOKEN_VALUE_PATTERN = /\b((?:sk|pk|gsk|xai|or|hf|ghp|gho|github_pat|AIza)[-_][A-Za-z0-9-_]{8,}|[A-Za-z0-9-_]{32,})\b/g;
9
+
10
+ export const REDACTED = "[REDACTED]";
11
+
12
+ /** Mask a string value, keeping a short, non-reversible hint. */
13
+ function maskValue(value: string): string {
14
+ if (value.length <= 8) return REDACTED;
15
+ return `${value.slice(0, 3)}…${value.slice(-4)}`;
16
+ }
17
+
18
+ function redactString(input: string): string {
19
+ return input.replace(TOKEN_VALUE_PATTERN, (match) => maskValue(match));
20
+ }
21
+
22
+ /** Recursively redact a value: sensitive keys are masked, strings scrubbed. */
23
+ export function redact(value: unknown, keyHint?: string): unknown {
24
+ if (typeof value === "string") {
25
+ if (keyHint && SENSITIVE_KEY_PATTERN.test(keyHint)) return maskValue(value);
26
+ return redactString(value);
27
+ }
28
+ if (Array.isArray(value)) {
29
+ return value.map((item) => redact(item));
30
+ }
31
+ if (value && typeof value === "object") {
32
+ const out: Record<string, unknown> = {};
33
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
34
+ out[k] = SENSITIVE_KEY_PATTERN.test(k) && typeof v === "string" ? maskValue(v) : redact(v, k);
35
+ }
36
+ return out;
37
+ }
38
+ return value;
39
+ }
40
+
41
+ export function redactFields(fields: Record<string, unknown>): Record<string, unknown> {
42
+ return redact(fields) as Record<string, unknown>;
43
+ }
@@ -0,0 +1 @@
1
+ export * from "./user-config-dir";
@@ -0,0 +1,48 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+
4
+ /** Environment variable that overrides the resolved user config directory. */
5
+ export const USER_CONFIG_DIR_ENV_VAR = "GITPAGEDOCS_CONFIG_DIR";
6
+
7
+ /** Directory name that holds gitpagedocs user-level configuration. */
8
+ export const USER_CONFIG_APP_DIR = "gitpagedocs";
9
+
10
+ export interface UserConfigDirContext {
11
+ /** Platform id (defaults to `process.platform`). */
12
+ platform?: NodeJS.Platform;
13
+ /** Environment map (defaults to `process.env`). */
14
+ env?: NodeJS.ProcessEnv;
15
+ /** User home directory (defaults to `os.homedir()`). */
16
+ homeDir?: string;
17
+ }
18
+
19
+ /**
20
+ * Resolve the per-user gitpagedocs configuration directory following each
21
+ * platform's convention:
22
+ *
23
+ * - Windows: `%APPDATA%\gitpagedocs`
24
+ * - macOS: `~/Library/Application Support/gitpagedocs`
25
+ * - Linux and others: `$XDG_CONFIG_HOME/gitpagedocs` or `~/.config/gitpagedocs`
26
+ *
27
+ * The `GITPAGEDOCS_CONFIG_DIR` environment variable overrides all of the above.
28
+ */
29
+ export function resolveUserConfigDir(context: UserConfigDirContext = {}): string {
30
+ const env = context.env ?? process.env;
31
+ const override = env[USER_CONFIG_DIR_ENV_VAR]?.trim();
32
+ if (override) return path.resolve(override);
33
+
34
+ const platform = context.platform ?? process.platform;
35
+ const homeDir = context.homeDir ?? os.homedir();
36
+
37
+ if (platform === "win32") {
38
+ const appData = env.APPDATA?.trim() || path.join(homeDir, "AppData", "Roaming");
39
+ return path.join(appData, USER_CONFIG_APP_DIR);
40
+ }
41
+
42
+ if (platform === "darwin") {
43
+ return path.join(homeDir, "Library", "Application Support", USER_CONFIG_APP_DIR);
44
+ }
45
+
46
+ const configHome = env.XDG_CONFIG_HOME?.trim() || path.join(homeDir, ".config");
47
+ return path.join(configHome, USER_CONFIG_APP_DIR);
48
+ }