@vortex-os/base 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -36
- package/dist/index.d.ts +1526 -23
- package/dist/index.js +3279 -20
- package/dist/index.js.map +1 -1
- package/package.json +16 -9
- package/dist/index.d.ts.map +0 -1
- package/src/index.ts +0 -33
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,MAAM,CAAC,MAAM,mBAAmB,GAAG,OAAgB,CAAC;AAWpD,MAAM,CAAC,MAAM,cAAc,GAAwB;IACjD,OAAO,EAAE,mBAAmB;IAC5B,SAAS,EAAE,WAAW;IACtB,iBAAiB,EAAE,OAAO;IAC1B,eAAe,EACb,yEAAyE;IAC3E,UAAU,EAAE,2CAA2C;CACxD,CAAC"}
|
|
1
|
+
{"version":3,"sources":["../../core/src/index.ts","../../core/src/types.ts","../../core/src/frontmatter.ts","../../core/src/privacy.ts","../../core/src/paths.ts","../../modules/slash-commands/src/index.ts","../../modules/slash-commands/src/registry.ts","../../modules/slash-commands/src/runner.ts","../../modules/memory-system/src/index.ts","../../modules/memory-system/src/types.ts","../../modules/memory-system/src/store.ts","../../modules/memory-system/src/memory-index.ts","../../modules/memory-system/src/sync.ts","../../modules/data-lint/src/index.ts","../../modules/data-lint/src/runner.ts","../../modules/data-lint/src/rules/require-frontmatter.ts","../../modules/data-lint/src/rules/privacy-valid.ts","../../modules/data-lint/src/rules/wiki-link-resolves.ts","../../modules/ai-coding-pitfalls/src/index.ts","../../modules/ai-coding-pitfalls/src/catalog.ts","../../modules/tool-rules/src/index.ts","../../modules/tool-rules/src/catalog.ts","../../modules/report-generator/src/index.ts","../../node_modules/marked/src/defaults.ts","../../node_modules/marked/src/rules.ts","../../node_modules/marked/src/helpers.ts","../../node_modules/marked/src/Tokenizer.ts","../../node_modules/marked/src/Lexer.ts","../../node_modules/marked/src/Renderer.ts","../../node_modules/marked/src/TextRenderer.ts","../../node_modules/marked/src/Parser.ts","../../node_modules/marked/src/Hooks.ts","../../node_modules/marked/src/Instance.ts","../../node_modules/marked/src/marked.ts","../../modules/report-generator/src/filter.ts","../../modules/report-generator/src/template.ts","../../modules/report-generator/src/renderer.ts","../../modules/til/src/index.ts","../../modules/til/src/store.ts","../../modules/til/src/append.ts","../../modules/decision-log/src/index.ts","../../modules/decision-log/src/store.ts","../../modules/decision-log/src/template.ts","../../modules/index-generator/src/index.ts","../../modules/index-generator/src/scan.ts","../../modules/index-generator/src/render.ts","../../modules/index-generator/src/nested.ts","../../modules/runbooks/src/index.ts","../../modules/runbooks/src/store.ts","../../modules/link-rewriter/src/index.ts","../../modules/link-rewriter/src/extract.ts","../../modules/link-rewriter/src/resolve.ts","../../modules/link-rewriter/src/checker.ts","../../modules/link-rewriter/src/rewrite.ts","../../plugins/session-rituals/src/index.ts","../../plugins/session-rituals/src/commands/decision.ts","../../plugins/session-rituals/src/commands/reindex.ts","../../plugins/session-rituals/src/commands/session-start.ts","../../plugins/session-rituals/src/commands/til.ts","../../plugins/session-rituals/src/commands/vortex.ts","../../plugins/session-rituals/src/registry.ts"],"sourcesContent":["export { Privacy } from \"./types.js\";\nexport type { FrontmatterDoc, ModuleContext } from \"./types.js\";\nexport { parseFrontmatter, serializeFrontmatter } from \"./frontmatter.js\";\nexport { isVisibleAt, maxPrivacy, normalizePrivacy } from \"./privacy.js\";\nexport { makeContext, moduleDir } from \"./paths.js\";\n","/**\n * Three-tier privacy classification used across VortEX.\n *\n * - `public` — safe to share with anyone, including in published repositories.\n * - `internal` — visible to the operator and their organization; not for public release.\n * - `personal` — personal data; never shared, never published.\n */\nexport const Privacy = {\n Public: \"public\",\n Internal: \"internal\",\n Personal: \"personal\",\n} as const;\n\nexport type Privacy = (typeof Privacy)[keyof typeof Privacy];\n\n/**\n * Parsed markdown document with separated YAML frontmatter and body.\n */\nexport interface FrontmatterDoc<T = Record<string, unknown>> {\n frontmatter: T & { privacy?: Privacy };\n body: string;\n}\n\n/**\n * Resolved paths for a VortEX repository root.\n *\n * Every module receives a `ModuleContext` from the host (CLI, plugin runtime,\n * or test harness) and resolves its own paths against it. Modules must not\n * derive paths by string manipulation against an assumed layout.\n */\nexport interface ModuleContext {\n repoRoot: string;\n agentDir: string;\n dataDir: string;\n modulesDir: string;\n pluginsDir: string;\n}\n","import { parse as parseYaml, stringify as stringifyYaml } from \"yaml\";\nimport type { FrontmatterDoc, Privacy } from \"./types.js\";\n\nconst FENCE = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?/;\nconst BOM = \"\";\n\n/**\n * Parse a markdown source into its YAML frontmatter and body. If no frontmatter\n * fence is present, returns an empty frontmatter object and the source unchanged.\n *\n * A leading UTF-8 BOM is stripped before matching. Windows-authored files\n * frequently begin with ``, which would otherwise prevent the fence\n * regex from anchoring to `---` at byte 0.\n */\nexport function parseFrontmatter<T = Record<string, unknown>>(\n source: string,\n): FrontmatterDoc<T> {\n const cleaned = source.startsWith(BOM) ? source.slice(1) : source;\n const match = cleaned.match(FENCE);\n if (!match) {\n return {\n frontmatter: {} as T & { privacy?: Privacy },\n body: cleaned,\n };\n }\n const yaml = match[1] ?? \"\";\n const body = cleaned.slice(match[0].length);\n let parsed: T & { privacy?: Privacy };\n try {\n parsed = (parseYaml(yaml) ?? {}) as T & { privacy?: Privacy };\n } catch {\n // The fence was present but its YAML body did not parse — often the\n // result of copy/paste artifacts (a stray `---` mid-document, headings\n // accidentally pasted inside the fence). Treat as no frontmatter so\n // callers can still read the body; the fence content is discarded.\n parsed = {} as T & { privacy?: Privacy };\n }\n return { frontmatter: parsed, body };\n}\n\n/**\n * Serialize a `FrontmatterDoc` back into markdown text. If the frontmatter is\n * empty, the body is returned unchanged (no empty fence is emitted).\n */\nexport function serializeFrontmatter<T = Record<string, unknown>>(\n doc: FrontmatterDoc<T>,\n): string {\n const keys = Object.keys(doc.frontmatter ?? {});\n if (keys.length === 0) return doc.body;\n const yaml = stringifyYaml(doc.frontmatter).trimEnd();\n return `---\\n${yaml}\\n---\\n${doc.body}`;\n}\n","import type { Privacy } from \"./types.js\";\n\nconst ORDER: Record<Privacy, number> = {\n public: 0,\n internal: 1,\n personal: 2,\n};\n\n/**\n * Returns true if a document with `docPrivacy` is visible to a viewer authorized\n * at `viewerPrivacy`. Viewers see content at or below their own level.\n *\n * - `public` viewer sees → public only\n * - `internal` viewer sees → public + internal\n * - `personal` viewer sees → all three\n */\nexport function isVisibleAt(docPrivacy: Privacy, viewerPrivacy: Privacy): boolean {\n return ORDER[docPrivacy] <= ORDER[viewerPrivacy];\n}\n\n/**\n * Returns the more-restrictive of two privacy levels.\n * Useful when combining content from multiple sources for sharing.\n */\nexport function maxPrivacy(a: Privacy, b: Privacy): Privacy {\n return ORDER[a] >= ORDER[b] ? a : b;\n}\n\n/**\n * Coerce an unknown value (e.g. user input or untyped frontmatter) into a\n * valid `Privacy`. Falls back to `internal` by default — the safest default\n * for unclassified content.\n */\nexport function normalizePrivacy(value: unknown, fallback: Privacy = \"internal\"): Privacy {\n if (value === \"public\" || value === \"internal\" || value === \"personal\") {\n return value;\n }\n return fallback;\n}\n","import { resolve, join } from \"node:path\";\nimport type { ModuleContext } from \"./types.js\";\n\n/**\n * Build a `ModuleContext` for the given VortEX repository root. The root is\n * resolved to an absolute path; standard subdirectories are derived by\n * convention and are not guaranteed to exist on disk.\n */\nexport function makeContext(repoRoot: string): ModuleContext {\n const root = resolve(repoRoot);\n return {\n repoRoot: root,\n agentDir: join(root, \".agent\"),\n dataDir: join(root, \"data\"),\n modulesDir: join(root, \"modules\"),\n pluginsDir: join(root, \"plugins\"),\n };\n}\n\n/**\n * Resolve the directory of a named module within the repository.\n */\nexport function moduleDir(ctx: ModuleContext, moduleName: string): string {\n return join(ctx.modulesDir, moduleName);\n}\n","export type { Command, CommandArg, CommandInput } from \"./types.js\";\nexport { CommandRegistry } from \"./registry.js\";\nexport { runSlash, CommandNotFoundError } from \"./runner.js\";\nexport type { RunOptions } from \"./runner.js\";\n","import type { Command } from \"./types.js\";\n\n/**\n * Holds registered commands and looks them up by name.\n *\n * Names are matched exactly. Registering two commands with the same name\n * is an error — the second call throws. Callers that want to override an\n * existing command must `unregister` first.\n */\nexport class CommandRegistry {\n private readonly commands = new Map<string, Command>();\n\n register(command: Command): void {\n if (this.commands.has(command.name)) {\n throw new Error(`Command \"${command.name}\" is already registered`);\n }\n this.commands.set(command.name, command);\n }\n\n unregister(name: string): boolean {\n return this.commands.delete(name);\n }\n\n has(name: string): boolean {\n return this.commands.has(name);\n }\n\n get(name: string): Command | undefined {\n return this.commands.get(name);\n }\n\n list(): readonly Command[] {\n return Array.from(this.commands.values());\n }\n}\n","import type { ModuleContext } from \"@vortex-os/core\";\nimport type { CommandRegistry } from \"./registry.js\";\nimport type { CommandArg, CommandInput } from \"./types.js\";\n\nexport interface RunOptions {\n readonly registry: CommandRegistry;\n readonly context: ModuleContext;\n}\n\n/**\n * Thrown by `runSlash` when the requested command name does not exist\n * in the registry. The unknown name is exposed for caller diagnostics.\n */\nexport class CommandNotFoundError extends Error {\n readonly commandName: string;\n\n constructor(commandName: string) {\n super(`Unknown command: ${commandName}`);\n this.name = \"CommandNotFoundError\";\n this.commandName = commandName;\n }\n}\n\n/**\n * Parse an input string and dispatch the matching command.\n *\n * Accepted forms (leading slash optional):\n * \"name\"\n * \"/name\"\n * \"name arg1 arg2 ...\"\n *\n * Returns whatever the command's handler returns (awaited if it is async).\n */\nexport async function runSlash(\n input: string,\n { registry, context }: RunOptions,\n): Promise<unknown> {\n const trimmed = input.trim().replace(/^\\//, \"\");\n if (trimmed.length === 0) {\n throw new Error(\"Empty command input\");\n }\n\n const tokens = trimmed.split(/\\s+/);\n const name = tokens[0] ?? \"\";\n const tail = tokens.slice(1);\n\n const command = registry.get(name);\n if (!command) {\n throw new CommandNotFoundError(name);\n }\n\n const args = parseArgs(tail, command.args);\n const rest = tail.join(\" \");\n const ci: CommandInput = {\n raw: trimmed,\n args,\n rest,\n context,\n };\n return command.handler(ci);\n}\n\nfunction parseArgs(\n tokens: readonly string[],\n schema: readonly CommandArg[] | undefined,\n): Record<string, string> {\n const out: Record<string, string> = {};\n if (!schema) return out;\n for (let i = 0; i < schema.length; i += 1) {\n const arg = schema[i];\n const value = tokens[i];\n if (arg && value !== undefined) {\n out[arg.name] = value;\n }\n }\n return out;\n}\n","export { MemoryType } from \"./types.js\";\nexport type { Memory, MemoryFrontmatter } from \"./types.js\";\nexport { MemoryStore } from \"./store.js\";\nexport { writeMemoryIndex } from \"./memory-index.js\";\nexport type { WriteMemoryIndexOptions } from \"./memory-index.js\";\nexport { diffStores } from \"./sync.js\";\nexport type { SyncDiff } from \"./sync.js\";\n","/**\n * Canonical memory categories.\n *\n * - `user` — facts about the operator (role, preferences, working style).\n * - `feedback` — corrections and validated approaches from the operator.\n * - `project` — ongoing work context (goals, deadlines, stakeholders).\n * - `reference` — pointers to external systems (dashboards, repos, channels).\n *\n * Hosts may extend the set, but stability of these four is preserved.\n */\nexport const MemoryType = {\n User: \"user\",\n Feedback: \"feedback\",\n Project: \"project\",\n Reference: \"reference\",\n} as const;\n\nexport type MemoryType = (typeof MemoryType)[keyof typeof MemoryType];\n\n/**\n * Frontmatter required on every memory file.\n *\n * `name` should match the file id (filename without `.md`). `description`\n * is a single-line summary used in the generated index. `type` places the\n * memory in one of the canonical categories. Additional keys (e.g.\n * `originSessionId`, `created`, custom tags) are tolerated and preserved\n * on round-trip but are not required.\n */\nexport interface MemoryFrontmatter {\n name: string;\n description: string;\n type: MemoryType;\n [key: string]: unknown;\n}\n\n/**\n * A parsed memory document, ready to be written back or rendered.\n *\n * `id` is the filename stem (no `.md`); it is the address by which the\n * store retrieves and overwrites the memory.\n */\nexport interface Memory {\n id: string;\n frontmatter: MemoryFrontmatter;\n body: string;\n}\n","import { readdir, readFile, writeFile, mkdir, unlink, stat } from \"node:fs/promises\";\nimport { join, basename, extname } from \"node:path\";\nimport { parseFrontmatter, serializeFrontmatter } from \"@vortex-os/core\";\nimport type { Memory, MemoryFrontmatter } from \"./types.js\";\n\n/**\n * A directory-backed memory store.\n *\n * Each memory lives in a single `.md` file. The `MEMORY.md` (generated index)\n * and `_INDEX.md` (Obsidian-friendly index) files are excluded — they are\n * derived views, not memories themselves.\n */\nexport class MemoryStore {\n constructor(readonly dir: string) {}\n\n /** Ensure the backing directory exists. Safe to call repeatedly. */\n async ensure(): Promise<void> {\n await mkdir(this.dir, { recursive: true });\n }\n\n /** List memory ids (filename stems), sorted lexicographically. */\n async list(): Promise<readonly string[]> {\n try {\n const entries = await readdir(this.dir);\n return entries\n .filter((e) => e.endsWith(\".md\") && e !== \"MEMORY.md\" && e !== \"_INDEX.md\")\n .map((e) => basename(e, extname(e)))\n .sort();\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw e;\n }\n }\n\n /** Read a memory by id. Throws if the file does not exist. */\n async read(id: string): Promise<Memory> {\n const raw = await readFile(this.pathFor(id), \"utf8\");\n const { frontmatter, body } = parseFrontmatter<MemoryFrontmatter>(raw);\n return { id, frontmatter, body };\n }\n\n /** Write (or overwrite) a memory. Ensures the directory exists first. */\n async write(memory: Memory): Promise<void> {\n await this.ensure();\n const source = serializeFrontmatter({\n frontmatter: memory.frontmatter,\n body: memory.body,\n });\n await writeFile(this.pathFor(memory.id), source, \"utf8\");\n }\n\n /** Delete a memory. Returns false if it did not exist. */\n async delete(id: string): Promise<boolean> {\n try {\n await unlink(this.pathFor(id));\n return true;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw e;\n }\n }\n\n /** Test whether a memory exists by id. */\n async has(id: string): Promise<boolean> {\n try {\n await stat(this.pathFor(id));\n return true;\n } catch {\n return false;\n }\n }\n\n /** Absolute path of a memory file (file may not exist). */\n pathFor(id: string): string {\n return join(this.dir, `${id}.md`);\n }\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { MemoryStore } from \"./store.js\";\n\nexport interface WriteMemoryIndexOptions {\n /** Top-level heading. Defaults to \"Memory Index\". */\n title?: string;\n /** Optional text placed above the heading (e.g. an HTML comment). */\n preamble?: string;\n}\n\n/**\n * Render a `MEMORY.md` index from the entries currently in `store` and\n * write it to `<store.dir>/MEMORY.md`. Existing `MEMORY.md` is overwritten.\n *\n * The index is a flat bullet list: one line per memory, linking to the\n * memory file and including the memory's `description`.\n */\nexport async function writeMemoryIndex(\n store: MemoryStore,\n options: WriteMemoryIndexOptions = {},\n): Promise<void> {\n const ids = await store.list();\n const lines: string[] = [];\n if (options.preamble) {\n lines.push(options.preamble, \"\");\n }\n lines.push(`# ${options.title ?? \"Memory Index\"}`, \"\");\n for (const id of ids) {\n const memory = await store.read(id);\n lines.push(\n `- [${memory.frontmatter.name}](${id}.md) — ${memory.frontmatter.description}`,\n );\n }\n await writeFile(join(store.dir, \"MEMORY.md\"), `${lines.join(\"\\n\")}\\n`, \"utf8\");\n}\n","import { readFile } from \"node:fs/promises\";\nimport type { MemoryStore } from \"./store.js\";\n\n/**\n * Difference between two memory stores. All three lists may be empty,\n * which means the stores are in sync.\n */\nexport interface SyncDiff {\n /** Ids present in `a` but not in `b`. */\n onlyInA: readonly string[];\n /** Ids present in `b` but not in `a`. */\n onlyInB: readonly string[];\n /** Ids present in both but whose raw file contents differ. */\n changed: readonly string[];\n}\n\n/**\n * Compute the diff between two memory stores. Neither store is modified.\n *\n * `changed` is determined by exact byte comparison of the underlying\n * `.md` files. Frontmatter ordering or whitespace differences therefore\n * count as a change — callers that want semantic equality should\n * re-serialize through `parseFrontmatter` / `serializeFrontmatter` before\n * comparing.\n */\nexport async function diffStores(\n a: MemoryStore,\n b: MemoryStore,\n): Promise<SyncDiff> {\n const [idsA, idsB] = await Promise.all([a.list(), b.list()]);\n const setA = new Set(idsA);\n const setB = new Set(idsB);\n\n const onlyInA = idsA.filter((id) => !setB.has(id));\n const onlyInB = idsB.filter((id) => !setA.has(id));\n const both = idsA.filter((id) => setB.has(id));\n\n const changed: string[] = [];\n for (const id of both) {\n const [contentA, contentB] = await Promise.all([\n readFile(a.pathFor(id), \"utf8\"),\n readFile(b.pathFor(id), \"utf8\"),\n ]);\n if (contentA !== contentB) {\n changed.push(id);\n }\n }\n\n return { onlyInA, onlyInB, changed };\n}\n","export type { Severity, LintFinding, LintRule, LintInput, LintReport } from \"./types.js\";\nexport { lintDirectory } from \"./runner.js\";\nexport type { LintOptions } from \"./runner.js\";\nexport { requireFrontmatter } from \"./rules/require-frontmatter.js\";\nexport type { RequireFrontmatterOptions } from \"./rules/require-frontmatter.js\";\nexport { privacyValid } from \"./rules/privacy-valid.js\";\nexport { wikiLinkResolves } from \"./rules/wiki-link-resolves.js\";\nexport type { WikiLinkResolvesOptions } from \"./rules/wiki-link-resolves.js\";\n","import { readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { LintFinding, LintReport, LintRule } from \"./types.js\";\n\nexport interface LintOptions {\n /** Directory to scan recursively. */\n readonly dir: string;\n /** Rules to apply to every file. */\n readonly rules: readonly LintRule[];\n /** File extensions to include. Defaults to `[\".md\"]`. */\n readonly extensions?: readonly string[];\n}\n\n/**\n * Recursively scan `dir` for files with the configured extensions and run\n * every rule against each file. Findings from all rules are aggregated into\n * a single `LintReport`. Order of findings within the report is not\n * guaranteed beyond \"file by file, rule by rule\".\n */\nexport async function lintDirectory(options: LintOptions): Promise<LintReport> {\n const start = Date.now();\n const extensions = options.extensions ?? [\".md\"];\n const files = await collectFiles(options.dir, extensions);\n const findings: LintFinding[] = [];\n\n for (const file of files) {\n const content = await readFile(file, \"utf8\");\n for (const rule of options.rules) {\n const result = await rule.check({ file, content });\n for (const f of result) findings.push(f);\n }\n }\n\n return {\n findings,\n filesScanned: files.length,\n rulesRun: options.rules.length,\n durationMs: Date.now() - start,\n };\n}\n\nasync function collectFiles(\n dir: string,\n extensions: readonly string[],\n): Promise<string[]> {\n const out: string[] = [];\n const stack: string[] = [dir];\n while (stack.length > 0) {\n const current = stack.pop();\n if (current === undefined) break;\n let entries;\n try {\n entries = await readdir(current, { withFileTypes: true });\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw e;\n }\n for (const entry of entries) {\n const full = join(current, entry.name);\n if (entry.isDirectory()) {\n stack.push(full);\n } else if (\n entry.isFile() &&\n extensions.some((ext) => entry.name.endsWith(ext))\n ) {\n out.push(full);\n }\n }\n }\n return out.sort();\n}\n","import { parseFrontmatter } from \"@vortex-os/core\";\nimport type { LintFinding, LintRule } from \"../types.js\";\n\nexport interface RequireFrontmatterOptions {\n /** Frontmatter keys that must be present and non-empty. */\n readonly required: readonly string[];\n}\n\n/**\n * Rule that ensures the listed frontmatter keys are present and non-empty.\n * Empty string, null, and undefined values all fail the check; `0`, `false`,\n * and structured values (arrays, objects) pass as long as they exist.\n */\nexport function requireFrontmatter(options: RequireFrontmatterOptions): LintRule {\n return {\n id: \"require-frontmatter\",\n description: `Ensure required frontmatter keys are present: ${options.required.join(\", \")}`,\n check({ file, content }) {\n const findings: LintFinding[] = [];\n const { frontmatter } = parseFrontmatter<Record<string, unknown>>(content);\n for (const key of options.required) {\n const value = frontmatter[key];\n if (value === undefined || value === null || value === \"\") {\n findings.push({\n rule: \"require-frontmatter\",\n severity: \"error\",\n file,\n message: `Missing required frontmatter key: \"${key}\"`,\n });\n }\n }\n return findings;\n },\n };\n}\n","import { parseFrontmatter } from \"@vortex-os/core\";\nimport type { LintFinding, LintRule } from \"../types.js\";\n\nconst CANONICAL = new Set([\"public\", \"internal\", \"personal\"]);\n\n/**\n * Rule that ensures, if a `privacy` frontmatter field is present, its value\n * is one of the canonical three: `public`, `internal`, `personal`.\n * Documents without any `privacy` field pass.\n */\nexport function privacyValid(): LintRule {\n return {\n id: \"privacy-valid\",\n description: \"Ensure frontmatter privacy is one of public/internal/personal\",\n check({ file, content }) {\n const findings: LintFinding[] = [];\n const { frontmatter } = parseFrontmatter<{ privacy?: unknown }>(content);\n if (frontmatter.privacy === undefined) return findings;\n if (typeof frontmatter.privacy !== \"string\" || !CANONICAL.has(frontmatter.privacy)) {\n findings.push({\n rule: \"privacy-valid\",\n severity: \"error\",\n file,\n message: `Invalid privacy value: ${JSON.stringify(frontmatter.privacy)}. Expected one of: public, internal, personal.`,\n });\n }\n return findings;\n },\n };\n}\n","import { readdir } from \"node:fs/promises\";\nimport { basename, extname, join } from \"node:path\";\nimport type { LintFinding, LintRule } from \"../types.js\";\n\nconst WIKI_LINK = /\\[\\[([^\\]|#]+)(?:[|#][^\\]]*)?\\]\\]/g;\n\nexport interface WikiLinkResolvesOptions {\n /** Directory under which valid link targets live. Searched recursively. */\n readonly searchRoot: string;\n /** Target file extensions. Defaults to `[\".md\"]`. */\n readonly extensions?: readonly string[];\n}\n\n/**\n * Rule that checks wiki-style links `[[target]]` resolve to an existing\n * file under `searchRoot` (by basename match, recursive). Aliases\n * (`[[target|alias]]`) and anchors (`[[target#section]]`) are stripped\n * before lookup.\n *\n * The target index is built lazily on the first invocation and cached for\n * the lifetime of the rule instance.\n */\nexport function wikiLinkResolves(options: WikiLinkResolvesOptions): LintRule {\n let cache: Set<string> | undefined;\n const extensions = options.extensions ?? [\".md\"];\n\n async function buildIndex(): Promise<Set<string>> {\n if (cache) return cache;\n const out = new Set<string>();\n const stack: string[] = [options.searchRoot];\n while (stack.length > 0) {\n const current = stack.pop();\n if (current === undefined) break;\n let entries;\n try {\n entries = await readdir(current, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of entries) {\n const full = join(current, entry.name);\n if (entry.isDirectory()) {\n stack.push(full);\n } else if (\n entry.isFile() &&\n extensions.some((ext) => entry.name.endsWith(ext))\n ) {\n out.add(basename(entry.name, extname(entry.name)));\n }\n }\n }\n cache = out;\n return out;\n }\n\n return {\n id: \"wiki-link-resolves\",\n description: \"Check [[wiki links]] resolve to an existing file by basename\",\n async check({ file, content }) {\n const findings: LintFinding[] = [];\n const index = await buildIndex();\n const lines = content.split(\"\\n\");\n lines.forEach((line, idx) => {\n for (const match of line.matchAll(WIKI_LINK)) {\n const target = match[1]?.trim();\n if (target && !index.has(target)) {\n findings.push({\n rule: \"wiki-link-resolves\",\n severity: \"warning\",\n file,\n line: idx + 1,\n message: `Unresolved wiki link: [[${target}]]`,\n });\n }\n }\n });\n return findings;\n },\n };\n}\n","export type { Pitfall, PitfallFrontmatter, PitfallSeverity } from \"./types.js\";\nexport { PitfallCatalog } from \"./catalog.js\";\n","import { readdir, readFile } from \"node:fs/promises\";\nimport { basename, extname, join } from \"node:path\";\nimport { parseFrontmatter } from \"@vortex-os/core\";\nimport type { Pitfall, PitfallFrontmatter } from \"./types.js\";\n\n/**\n * Directory-backed pitfall catalog. One `.md` file per pitfall.\n *\n * The catalog reads all `.md` files in `dir` on each query (no caching).\n * Callers that need cached behavior should wrap or call `list()` once and\n * reuse the result.\n */\nexport class PitfallCatalog {\n constructor(readonly dir: string) {}\n\n /** Load every pitfall in the directory, sorted by id. */\n async list(): Promise<readonly Pitfall[]> {\n const files = await this.entries();\n const out: Pitfall[] = [];\n for (const file of files) {\n out.push(await this.loadFile(file));\n }\n return out.sort((a, b) => a.id.localeCompare(b.id));\n }\n\n /** Load a single pitfall by id. Returns `undefined` if not found. */\n async get(id: string): Promise<Pitfall | undefined> {\n const all = await this.list();\n return all.find((p) => p.id === id);\n }\n\n /** Return only pitfalls matching the given category. */\n async filterByCategory(category: string): Promise<readonly Pitfall[]> {\n const all = await this.list();\n return all.filter((p) => p.category === category);\n }\n\n private async entries(): Promise<string[]> {\n try {\n const names = await readdir(this.dir);\n return names\n .filter((n) => n.endsWith(\".md\"))\n .map((n) => join(this.dir, n));\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw e;\n }\n }\n\n private async loadFile(path: string): Promise<Pitfall> {\n const raw = await readFile(path, \"utf8\");\n const { frontmatter, body } = parseFrontmatter<PitfallFrontmatter>(raw);\n const idFromFile = basename(path, extname(path));\n return {\n id: frontmatter.id ?? idFromFile,\n title: frontmatter.title,\n category: frontmatter.category,\n severity: frontmatter.severity,\n signal: frontmatter.signal,\n cause: frontmatter.cause,\n mitigation: frontmatter.mitigation,\n body: body.trimStart(),\n };\n }\n}\n","export type { ToolRule, ToolRuleFrontmatter, ToolRuleSeverity } from \"./types.js\";\nexport { ToolRuleCatalog } from \"./catalog.js\";\n","import { readdir, readFile } from \"node:fs/promises\";\nimport { basename, extname, join } from \"node:path\";\nimport { parseFrontmatter } from \"@vortex-os/core\";\nimport type { ToolRule, ToolRuleFrontmatter, ToolRuleSeverity } from \"./types.js\";\n\n/**\n * Directory-backed tool-rule catalog. One `.md` file per rule.\n *\n * The catalog reads all `.md` files in `dir` on each query (no caching).\n */\nexport class ToolRuleCatalog {\n constructor(readonly dir: string) {}\n\n /** Load every rule in the directory, sorted by id. */\n async list(): Promise<readonly ToolRule[]> {\n const files = await this.entries();\n const out: ToolRule[] = [];\n for (const file of files) {\n out.push(await this.loadFile(file));\n }\n return out.sort((a, b) => a.id.localeCompare(b.id));\n }\n\n /** Load a single rule by id. Returns `undefined` if not found. */\n async get(id: string): Promise<ToolRule | undefined> {\n const all = await this.list();\n return all.find((r) => r.id === id);\n }\n\n /** Return only rules whose `scope` matches exactly. */\n async filterByScope(scope: string): Promise<readonly ToolRule[]> {\n const all = await this.list();\n return all.filter((r) => r.scope === scope);\n }\n\n /** Return only rules whose `severity` matches. */\n async filterBySeverity(severity: ToolRuleSeverity): Promise<readonly ToolRule[]> {\n const all = await this.list();\n return all.filter((r) => r.severity === severity);\n }\n\n private async entries(): Promise<string[]> {\n try {\n const names = await readdir(this.dir);\n return names\n .filter((n) => n.endsWith(\".md\"))\n .map((n) => join(this.dir, n));\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw e;\n }\n }\n\n private async loadFile(path: string): Promise<ToolRule> {\n const raw = await readFile(path, \"utf8\");\n const { frontmatter, body } = parseFrontmatter<ToolRuleFrontmatter>(raw);\n const idFromFile = basename(path, extname(path));\n return {\n id: frontmatter.id ?? idFromFile,\n title: frontmatter.title,\n scope: frontmatter.scope,\n severity: frontmatter.severity,\n condition: frontmatter.condition,\n action: frontmatter.action,\n body: body.trimStart(),\n };\n }\n}\n","export type { RenderOptions, RenderResult, RenderWarning, WarningKind } from \"./types.js\";\nexport { renderHtml } from \"./renderer.js\";\nexport { stripPrivateSections } from \"./filter.js\";\nexport type { StripResult } from \"./filter.js\";\nexport { applyTemplate, DEFAULT_TEMPLATE } from \"./template.js\";\n","import type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Gets the original marked default options.\n */\nexport function _getDefaults<ParserOutput = string, RendererOutput = string>(): MarkedOptions<ParserOutput, RendererOutput> {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null,\n };\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport let _defaults: MarkedOptions<any, any> = _getDefaults();\n\nexport function changeDefaults<ParserOutput = string, RendererOutput = string>(newDefaults: MarkedOptions<ParserOutput, RendererOutput>) {\n _defaults = newDefaults;\n}\n","const noopTest = { exec: () => null } as unknown as RegExp;\n\nfunction edit(regex: string | RegExp, opt = '') {\n let source = typeof regex === 'string' ? regex : regex.source;\n const obj = {\n replace: (name: string | RegExp, val: string | RegExp) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(other.caret, '$1');\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n },\n };\n return obj;\n}\n\nconst supportsLookbehind = (() => {\ntry {\n // eslint-disable-next-line prefer-regex-literals\n return !!new RegExp('(?<=1)(?<!1)');\n} catch {\n // See browser support here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion\n return false;\n}\n})();\n\nexport const other = {\n codeRemoveIndent: /^(?: {1,4}| {0,3}\\t)/gm,\n outputLinkReplace: /\\\\([\\[\\]])/g,\n indentCodeCompensation: /^(\\s+)(?:```)/,\n beginningSpace: /^\\s+/,\n endingHash: /#$/,\n startingSpaceChar: /^ /,\n endingSpaceChar: / $/,\n nonSpaceChar: /[^ ]/,\n newLineCharGlobal: /\\n/g,\n tabCharGlobal: /\\t/g,\n multipleSpaceGlobal: /\\s+/g,\n blankLine: /^[ \\t]*$/,\n doubleBlankLine: /\\n[ \\t]*\\n[ \\t]*$/,\n blockquoteStart: /^ {0,3}>/,\n blockquoteSetextReplace: /\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,\n blockquoteSetextReplace2: /^ {0,3}>[ \\t]?/gm,\n listReplaceTabs: /^\\t+/,\n listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,\n listIsTask: /^\\[[ xX]\\] /,\n listReplaceTask: /^\\[[ xX]\\] +/,\n anyLine: /\\n.*\\n/,\n hrefBrackets: /^<(.*)>$/,\n tableDelimiter: /[:|]/,\n tableAlignChars: /^\\||\\| *$/g,\n tableRowBlankLine: /\\n[ \\t]*$/,\n tableAlignRight: /^ *-+: *$/,\n tableAlignCenter: /^ *:-+: *$/,\n tableAlignLeft: /^ *:-+ *$/,\n startATag: /^<a /i,\n endATag: /^<\\/a>/i,\n startPreScriptTag: /^<(pre|code|kbd|script)(\\s|>)/i,\n endPreScriptTag: /^<\\/(pre|code|kbd|script)(\\s|>)/i,\n startAngleBracket: /^</,\n endAngleBracket: />$/,\n pedanticHrefTitle: /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,\n unicodeAlphaNumeric: /[\\p{L}\\p{N}]/u,\n escapeTest: /[&<>\"']/,\n escapeReplace: /[&<>\"']/g,\n escapeTestNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,\n escapeReplaceNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,\n unescapeTest: /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig,\n caret: /(^|[^\\[])\\^/g,\n percentDecode: /%25/g,\n findPipe: /\\|/g,\n splitPipe: / \\|/,\n slashPipe: /\\\\\\|/g,\n carriageReturn: /\\r\\n|\\r/g,\n spaceLine: /^ +$/gm,\n notSpaceStart: /^\\S*/,\n endingNewline: /\\n$/,\n listItemRegex: (bull: string) => new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`),\n nextBulletRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`),\n hrRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`),\n fencesBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`),\n headingBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),\n htmlBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'),\n};\n\n/**\n * Block-Level Grammar\n */\n\nconst newline = /^(?:[ \\t]*(?:\\n|$))+/;\nconst blockCode = /^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/;\nconst fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/;\nconst hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nconst heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nconst bullet = /(?:[*+-]|\\d{1,9}[.)])/;\nconst lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/;\nconst lheading = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/\\|table/g, '') // table not in commonmark\n .getRegex();\nconst lheadingGfm = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/table/g, / {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/) // table can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\n\nconst list = edit(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\n\nconst _tag = 'address|article|aside|base|basefont|blockquote|body|caption'\n + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'\n + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'\n + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'\n + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'\n + '|tr|track|ul';\nconst _comment = /<!--(?:-?>|[\\s\\S]*?(?:-->|$))/;\nconst html = edit(\n '^ {0,3}(?:' // optional indentation\n+ '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:</\\\\1>[^\\\\n]*\\\\n+|$)' // (1)\n+ '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n+ '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)' // (3)\n+ '|<![A-Z][\\\\s\\\\S]*?(?:>\\\\n*|$)' // (4)\n+ '|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?(?:\\\\]\\\\]>\\\\n*|$)' // (5)\n+ '|</?(tag)(?: +|\\\\n|/?>)[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (6)\n+ '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) open tag\n+ '|</(?!script|pre|style|textarea)[a-z][\\\\w-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) closing tag\n+ ')', 'i')\n .replace('comment', _comment)\n .replace('tag', _tag)\n .replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst paragraph = edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex();\n\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n\n/**\n * Normal Block Grammar\n */\n\nconst blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText,\n};\n\ntype BlockKeys = keyof typeof blockNormal;\n\n/**\n * GFM Block Grammar\n */\n\nconst gfmTable = edit(\n '^ *([^\\\\n ].*)\\\\n' // Header\n+ ' {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)' // Align\n+ '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)') // Cells\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('blockquote', ' {0,3}>')\n .replace('code', '(?: {4}| {0,3}\\t)[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // tables can be interrupted by type (6) html blocks\n .getRegex();\n\nconst blockGfm: Record<BlockKeys, RegExp> = {\n ...blockNormal,\n lheading: lheadingGfm,\n table: gfmTable,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('table', gfmTable) // interrupt paragraphs with table\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex(),\n};\n\n/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\n\nconst blockPedantic: Record<BlockKeys, RegExp> = {\n ...blockNormal,\n html: edit(\n '^ *(?:comment *(?:\\\\n|\\\\s*$)'\n + '|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)' // closed tag\n + '|<tag(?:\"[^\"]*\"|\\'[^\\']*\\'|\\\\s[^\\'\"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))')\n .replace('comment', _comment)\n .replace(/tag/g, '(?!(?:'\n + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'\n + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'\n + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b')\n .getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest, // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' *#{1,6} *[^\\n]')\n .replace('lheading', lheading)\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('|fences', '')\n .replace('|list', '')\n .replace('|html', '')\n .replace('|tag', '')\n .getRegex(),\n};\n\n/**\n * Inline-Level Grammar\n */\n\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/;\n\n// list of unicode punctuation marks, plus any missing characters from CommonMark spec\nconst _punctuation = /[\\p{P}\\p{S}]/u;\nconst _punctuationOrSpace = /[\\s\\p{P}\\p{S}]/u;\nconst _notPunctuationOrSpace = /[^\\s\\p{P}\\p{S}]/u;\nconst punctuation = edit(/^((?![*_])punctSpace)/, 'u')\n .replace(/punctSpace/g, _punctuationOrSpace).getRegex();\n\n// GFM allows ~ inside strong and em for strikethrough\nconst _punctuationGfmStrongEm = /(?!~)[\\p{P}\\p{S}]/u;\nconst _punctuationOrSpaceGfmStrongEm = /(?!~)[\\s\\p{P}\\p{S}]/u;\nconst _notPunctuationOrSpaceGfmStrongEm = /(?:[^\\s\\p{P}\\p{S}]|~)/u;\n\n// sequences em should skip over [title](link), `code`, <html>\nconst blockSkip = edit(/link|precode-code|html/, 'g')\n .replace('link', /\\[(?:[^\\[\\]`]|(?<a>`+)[^`]+\\k<a>(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/)\n .replace('precode-', supportsLookbehind ? '(?<!`)()' : '(^^|[^`])')\n .replace('code', /(?<b>`+)[^`]+\\k<b>(?!`)/)\n .replace('html', /<(?! )[^<>]*?>/)\n .getRegex();\n\nconst emStrongLDelimCore = /^(?:\\*+(?:((?!\\*)punct)|[^\\s*]))|^_+(?:((?!_)punct)|([^\\s_]))/;\n\nconst emStrongLDelim = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongLDelimGfm = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\nconst emStrongRDelimAstCore =\n '^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n+ '|[^*]+(?=[^*])' // Consume to delim\n+ '|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter\n+ '|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter\n+ '|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)' // (4) ***# can only be Left Delimiter\n+ '|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter\n\nconst emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm)\n .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm)\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit(\n '^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n+ '|[^_]+(?=[^_])' // Consume to delim\n+ '|(?!_)punct(_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n+ '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter\n+ '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter\n+ '|[\\\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter\n+ '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst anyPunctuation = edit(/\\\\(punct)/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/)\n .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)\n .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)\n .getRegex();\n\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit(\n '^comment'\n + '|^</[a-zA-Z][\\\\w:-]*\\\\s*>' // self-closing tag\n + '|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>' // open tag\n + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. <?php ?>\n + '|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>' // declaration, e.g. <!DOCTYPE html>\n + '|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>') // CDATA section\n .replace('comment', _inlineComment)\n .replace('attribute', /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst _inlineLabel = /(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+[^`]*?`+(?!`)|[^\\[\\]\\\\`])*?/;\n\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]*(?:\\n[ \\t]*)?)(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\n\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n\nconst _caseInsensitiveProtocol = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;\n\n/**\n * Normal Inline Grammar\n */\n\nconst inlineNormal = {\n _backpedal: noopTest, // only used for GFM url\n anyPunctuation,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest,\n};\n\ntype InlineKeys = keyof typeof inlineNormal;\n\n/**\n * Pedantic Inline Grammar\n */\n\nconst inlinePedantic: Record<InlineKeys, RegExp> = {\n ...inlineNormal,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/)\n .replace('label', _inlineLabel)\n .getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/)\n .replace('label', _inlineLabel)\n .getRegex(),\n};\n\n/**\n * GFM Inline Grammar\n */\n\nconst inlineGfm: Record<InlineKeys, RegExp> = {\n ...inlineNormal,\n emStrongRDelimAst: emStrongRDelimAstGfm,\n emStrongLDelim: emStrongLDelimGfm,\n url: edit(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/)\n .replace('protocol', _caseInsensitiveProtocol)\n .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)\n .getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,\n text: edit(/^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|protocol:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)))/)\n .replace('protocol', _caseInsensitiveProtocol)\n .getRegex(),\n};\n\n/**\n * GFM + Line Breaks Inline Grammar\n */\n\nconst inlineBreaks: Record<InlineKeys, RegExp> = {\n ...inlineGfm,\n br: edit(br).replace('{2,}', '*').getRegex(),\n text: edit(inlineGfm.text)\n .replace('\\\\b_', '\\\\b_| {2,}\\\\n')\n .replace(/\\{2,\\}/g, '*')\n .getRegex(),\n};\n\n/**\n * exports\n */\n\nexport const block = {\n normal: blockNormal,\n gfm: blockGfm,\n pedantic: blockPedantic,\n};\n\nexport const inline = {\n normal: inlineNormal,\n gfm: inlineGfm,\n breaks: inlineBreaks,\n pedantic: inlinePedantic,\n};\n\nexport interface Rules {\n other: typeof other\n block: Record<BlockKeys, RegExp>\n inline: Record<InlineKeys, RegExp>\n}\n","import { other } from './rules.ts';\n\n/**\n * Helpers\n */\nconst escapeReplacements: { [index: string]: string } = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\nconst getEscapeReplacement = (ch: string) => escapeReplacements[ch];\n\nexport function escape(html: string, encode?: boolean) {\n if (encode) {\n if (other.escapeTest.test(html)) {\n return html.replace(other.escapeReplace, getEscapeReplacement);\n }\n } else {\n if (other.escapeTestNoEncode.test(html)) {\n return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n\n return html;\n}\n\nexport function unescape(html: string) {\n // explicitly match decimal, hex, and named HTML entities\n return html.replace(other.unescapeTest, (_, n) => {\n n = n.toLowerCase();\n if (n === 'colon') return ':';\n if (n.charAt(0) === '#') {\n return n.charAt(1) === 'x'\n ? String.fromCharCode(parseInt(n.substring(2), 16))\n : String.fromCharCode(+n.substring(1));\n }\n return '';\n });\n}\n\nexport function cleanUrl(href: string) {\n try {\n href = encodeURI(href).replace(other.percentDecode, '%');\n } catch {\n return null;\n }\n return href;\n}\n\nexport function splitCells(tableRow: string, count?: number) {\n // ensure that every cell-delimiting pipe has a space\n // before it to distinguish it from an escaped pipe\n const row = tableRow.replace(other.findPipe, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\') escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n } else {\n // add space before unescaped |\n return ' |';\n }\n }),\n cells = row.split(other.splitPipe);\n let i = 0;\n\n // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells.at(-1)?.trim()) {\n cells.pop();\n }\n\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n } else {\n while (cells.length < count) cells.push('');\n }\n }\n\n for (; i < cells.length; i++) {\n // leading or trailing whitespace is ignored per the gfm spec\n cells[i] = cells[i].trim().replace(other.slashPipe, '|');\n }\n return cells;\n}\n\n/**\n * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n * /c*$/ is vulnerable to REDOS.\n *\n * @param str\n * @param c\n * @param invert Remove suffix of non-c chars instead. Default falsey.\n */\nexport function rtrim(str: string, c: string, invert?: boolean) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n\n // Step left until we fail to match the invert condition.\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n } else if (currChar !== c && invert) {\n suffLen++;\n } else {\n break;\n }\n }\n\n return str.slice(0, l - suffLen);\n}\n\nexport function findClosingBracket(str: string, b: string) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n } else if (str[i] === b[0]) {\n level++;\n } else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n if (level > 0) {\n return -2;\n }\n\n return -1;\n}\n","import { _defaults } from './defaults.ts';\nimport {\n rtrim,\n splitCells,\n findClosingBracket,\n} from './helpers.ts';\nimport type { Rules } from './rules.ts';\nimport type { _Lexer } from './Lexer.ts';\nimport type { Links, Tokens, Token } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\nfunction outputLink(cap: string[], link: Pick<Tokens.Link, 'href' | 'title'>, raw: string, lexer: _Lexer, rules: Rules): Tokens.Link | Tokens.Image {\n const href = link.href;\n const title = link.title || null;\n const text = cap[1].replace(rules.other.outputLinkReplace, '$1');\n\n lexer.state.inLink = true;\n const token: Tokens.Link | Tokens.Image = {\n type: cap[0].charAt(0) === '!' ? 'image' : 'link',\n raw,\n href,\n title,\n text,\n tokens: lexer.inlineTokens(text),\n };\n lexer.state.inLink = false;\n return token;\n}\n\nfunction indentCodeCompensation(raw: string, text: string, rules: Rules) {\n const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);\n\n if (matchIndentToCode === null) {\n return text;\n }\n\n const indentToCode = matchIndentToCode[1];\n\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(rules.other.beginningSpace);\n if (matchIndentInNode === null) {\n return node;\n }\n\n const [indentInNode] = matchIndentInNode;\n\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n\n return node;\n })\n .join('\\n');\n}\n\n/**\n * Tokenizer\n */\nexport class _Tokenizer<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n rules!: Rules; // set by the lexer\n lexer!: _Lexer<ParserOutput, RendererOutput>; // set by the lexer\n\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n }\n\n space(src: string): Tokens.Space | undefined {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: 'space',\n raw: cap[0],\n };\n }\n }\n\n code(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const text = cap[0].replace(this.rules.other.codeRemoveIndent, '');\n return {\n type: 'code',\n raw: cap[0],\n codeBlockStyle: 'indented',\n text: !this.options.pedantic\n ? rtrim(text, '\\n')\n : text,\n };\n }\n }\n\n fences(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '', this.rules);\n\n return {\n type: 'code',\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],\n text,\n };\n }\n }\n\n heading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n\n // remove trailing #s\n if (this.rules.other.endingHash.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n hr(src: string): Tokens.Hr | undefined {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: 'hr',\n raw: rtrim(cap[0], '\\n'),\n };\n }\n }\n\n blockquote(src: string): Tokens.Blockquote | undefined {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n let lines = rtrim(cap[0], '\\n').split('\\n');\n let raw = '';\n let text = '';\n const tokens: Token[] = [];\n\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (this.rules.other.blockquoteStart.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n } else if (!inBlockquote) {\n currentLines.push(lines[i]);\n } else {\n break;\n }\n }\n lines = lines.slice(i);\n\n const currentRaw = currentLines.join('\\n');\n const currentText = currentRaw\n // precede setext continuation with 4 spaces so it isn't a setext\n .replace(this.rules.other.blockquoteSetextReplace, '\\n $1')\n .replace(this.rules.other.blockquoteSetextReplace2, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n\n // parse blockquote lines as top level tokens\n // merge paragraphs if this is a continuation\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n this.lexer.blockTokens(currentText, tokens, true);\n this.lexer.state.top = top;\n\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n\n const lastToken = tokens.at(-1);\n\n if (lastToken?.type === 'code') {\n // blockquote continuation cannot be preceded by a code block\n break;\n } else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken as Tokens.Blockquote;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.blockquote(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.text.length) + newToken.text;\n break;\n } else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken as Tokens.List;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;\n lines = newText.substring(tokens.at(-1)!.raw.length).split('\\n');\n continue;\n }\n }\n\n return {\n type: 'blockquote',\n raw,\n tokens,\n text,\n };\n }\n }\n\n list(src: string): Tokens.List | undefined {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n\n const list: Tokens.List = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: [],\n };\n\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n\n // Get next list item\n const itemRegex = this.rules.other.listItemRegex(bull);\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n let raw = '';\n let itemContents = '';\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n\n raw = cap[0];\n src = src.substring(raw.length);\n\n let line = cap[2].split('\\n', 1)[0].replace(this.rules.other.listReplaceTabs, (t: string) => ' '.repeat(3 * t.length));\n let nextLine = src.split('\\n', 1)[0];\n let blankLine = !line.trim();\n\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n } else if (blankLine) {\n indent = cap[1].length + 1;\n } else {\n indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char\n indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent\n itemContents = line.slice(indent);\n indent += cap[1].length;\n }\n\n if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line\n raw += nextLine + '\\n';\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n\n if (!endEarly) {\n const nextBulletRegex = this.rules.other.nextBulletRegex(indent);\n const hrRegex = this.rules.other.hrRegex(indent);\n const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);\n const headingBeginRegex = this.rules.other.headingBeginRegex(indent);\n const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);\n\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n let nextLineWithoutTabs;\n nextLine = rawLine;\n\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' ');\n nextLineWithoutTabs = nextLine;\n } else {\n nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' ');\n }\n\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of html block\n if (htmlBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n\n // Horizontal rule found\n if (hrRegex.test(nextLine)) {\n break;\n }\n\n if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLineWithoutTabs.slice(indent);\n } else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n\n // paragraph continuation unless last line was a different block level element\n if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n\n itemContents += '\\n' + nextLine;\n }\n\n if (!blankLine && !nextLine.trim()) { // Check if current line is blank\n blankLine = true;\n }\n\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLineWithoutTabs.slice(indent);\n }\n }\n\n if (!list.loose) {\n // If the previous item ended with a blank line, the list is loose\n if (endsWithBlankLine) {\n list.loose = true;\n } else if (this.rules.other.doubleBlankLine.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n\n let istask: RegExpExecArray | null = null;\n let ischecked: boolean | undefined;\n // Check for task list items\n if (this.options.gfm) {\n istask = this.rules.other.listIsTask.exec(itemContents);\n if (istask) {\n ischecked = istask[0] !== '[ ] ';\n itemContents = itemContents.replace(this.rules.other.listReplaceTask, '');\n }\n }\n\n list.items.push({\n type: 'list_item',\n raw,\n task: !!istask,\n checked: ischecked,\n loose: false,\n text: itemContents,\n tokens: [],\n });\n\n list.raw += raw;\n }\n\n // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n const lastItem = list.items.at(-1);\n if (lastItem) {\n lastItem.raw = lastItem.raw.trimEnd();\n lastItem.text = lastItem.text.trimEnd();\n } else {\n // not a list since there were no items\n return;\n }\n list.raw = list.raw.trimEnd();\n\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (let i = 0; i < list.items.length; i++) {\n this.lexer.state.top = false;\n list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);\n\n if (!list.loose) {\n // Check if list should be loose\n const spacers = list.items[i].tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw));\n\n list.loose = hasMultipleLineBreaks;\n }\n }\n\n // Set all items to loose if list is loose\n if (list.loose) {\n for (let i = 0; i < list.items.length; i++) {\n list.items[i].loose = true;\n }\n }\n\n return list;\n }\n }\n\n html(src: string): Tokens.HTML | undefined {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const token: Tokens.HTML = {\n type: 'html',\n block: true,\n raw: cap[0],\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: cap[0],\n };\n return token;\n }\n }\n\n def(src: string): Tokens.Def | undefined {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' ');\n const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];\n return {\n type: 'def',\n tag,\n raw: cap[0],\n href,\n title,\n };\n }\n }\n\n table(src: string): Tokens.Table | undefined {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n\n if (!this.rules.other.tableDelimiter.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|');\n const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\\n') : [];\n\n const item: Tokens.Table = {\n type: 'table',\n raw: cap[0],\n header: [],\n align: [],\n rows: [],\n };\n\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n\n for (const align of aligns) {\n if (this.rules.other.tableAlignRight.test(align)) {\n item.align.push('right');\n } else if (this.rules.other.tableAlignCenter.test(align)) {\n item.align.push('center');\n } else if (this.rules.other.tableAlignLeft.test(align)) {\n item.align.push('left');\n } else {\n item.align.push(null);\n }\n }\n\n for (let i = 0; i < headers.length; i++) {\n item.header.push({\n text: headers[i],\n tokens: this.lexer.inline(headers[i]),\n header: true,\n align: item.align[i],\n });\n }\n\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map((cell, i) => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell),\n header: false,\n align: item.align[i],\n };\n }));\n }\n\n return item;\n }\n\n lheading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text: cap[1],\n tokens: this.lexer.inline(cap[1]),\n };\n }\n }\n\n paragraph(src: string): Tokens.Paragraph | undefined {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === '\\n'\n ? cap[1].slice(0, -1)\n : cap[1];\n return {\n type: 'paragraph',\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n text(src: string): Tokens.Text | undefined {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0]),\n };\n }\n }\n\n escape(src: string): Tokens.Escape | undefined {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: cap[1],\n };\n }\n }\n\n tag(src: string): Tokens.Tag | undefined {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {\n this.lexer.state.inLink = true;\n } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n\n return {\n type: 'html',\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0],\n };\n }\n }\n\n link(src: string): Tokens.Link | Tokens.Image | undefined {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {\n // commonmark requires matching angle brackets\n if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n return;\n }\n\n // ending angle bracket cannot be escaped\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n } else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex === -2) {\n // more open parens than closed\n return;\n }\n\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf('!') === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = '';\n }\n }\n let href = cap[2];\n let title = '';\n if (this.options.pedantic) {\n // split pedantic href and title\n const link = this.rules.other.pedanticHrefTitle.exec(href);\n\n if (link) {\n href = link[1];\n title = link[3];\n }\n } else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n\n href = href.trim();\n if (this.rules.other.startAngleBracket.test(href)) {\n if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\n } else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title,\n }, cap[0], this.lexer, this.rules);\n }\n }\n\n reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src))\n || (cap = this.rules.inline.nolink.exec(src))) {\n const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' ');\n const link = links[linkString.toLowerCase()];\n if (!link) {\n const text = cap[0].charAt(0);\n return {\n type: 'text',\n raw: text,\n text,\n };\n }\n return outputLink(cap, link, cap[0], this.lexer, this.rules);\n }\n }\n\n emStrong(src: string, maskedSrc: string, prevChar = ''): Tokens.Em | Tokens.Strong | undefined {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match) return;\n\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return;\n\n const nextChar = match[1] || match[2] || '';\n\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n\n while ((match = endReg.exec(maskedSrc)) != null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n\n if (!rDelim) continue; // skip single * in __abc*abc__\n\n rLength = [...rDelim].length;\n\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n } else if (match[5] || match[6]) { // either Left or Right Delim\n if (lLength % 3 && !((lLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue; // CommonMark Emphasis Rules 9-10\n }\n }\n\n delimTotal -= rLength;\n\n if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n\n // Remove extra characters. *a*** -> *a*\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n // char length can be >1 for unicode characters;\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n\n // Create `em` if smallest delimiter has odd char count. *a***\n if (Math.min(lLength, rLength) % 2) {\n const text = raw.slice(1, -1);\n return {\n type: 'em',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n\n // Create 'strong' if smallest delimiter has even char count. **a***\n const text = raw.slice(2, -2);\n return {\n type: 'strong',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n }\n }\n\n codespan(src: string): Tokens.Codespan | undefined {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' ');\n const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);\n const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n return {\n type: 'codespan',\n raw: cap[0],\n text,\n };\n }\n }\n\n br(src: string): Tokens.Br | undefined {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: 'br',\n raw: cap[0],\n };\n }\n }\n\n del(src: string): Tokens.Del | undefined {\n const cap = this.rules.inline.del.exec(src);\n if (cap) {\n return {\n type: 'del',\n raw: cap[0],\n text: cap[2],\n tokens: this.lexer.inlineTokens(cap[2]),\n };\n }\n }\n\n autolink(src: string): Tokens.Link | undefined {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[1];\n href = 'mailto:' + text;\n } else {\n text = cap[1];\n href = text;\n }\n\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n url(src: string): Tokens.Link | undefined {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[0];\n href = 'mailto:' + text;\n } else {\n // do extended autolink path validation\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';\n } while (prevCapZero !== cap[0]);\n text = cap[0];\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\n } else {\n href = cap[0];\n }\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n inlineText(src: string): Tokens.Text | undefined {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n const escaped = this.lexer.state.inRawBlock;\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n escaped,\n };\n }\n }\n}\n","import { _Tokenizer } from './Tokenizer.ts';\nimport { _defaults } from './defaults.ts';\nimport { other, block, inline } from './rules.ts';\nimport type { Token, TokensList, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Block Lexer\n */\nexport class _Lexer<ParserOutput = string, RendererOutput = string> {\n tokens: TokensList;\n options: MarkedOptions<ParserOutput, RendererOutput>;\n state: {\n inLink: boolean;\n inRawBlock: boolean;\n top: boolean;\n };\n\n private tokenizer: _Tokenizer<ParserOutput, RendererOutput>;\n private inlineQueue: { src: string, tokens: Token[] }[];\n\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n // TokenList cannot be created in one go\n this.tokens = [] as unknown as TokensList;\n this.tokens.links = Object.create(null);\n this.options = options || _defaults;\n this.options.tokenizer = this.options.tokenizer || new _Tokenizer<ParserOutput, RendererOutput>();\n this.tokenizer = this.options.tokenizer;\n this.tokenizer.options = this.options;\n this.tokenizer.lexer = this;\n this.inlineQueue = [];\n this.state = {\n inLink: false,\n inRawBlock: false,\n top: true,\n };\n\n const rules = {\n other,\n block: block.normal,\n inline: inline.normal,\n };\n\n if (this.options.pedantic) {\n rules.block = block.pedantic;\n rules.inline = inline.pedantic;\n } else if (this.options.gfm) {\n rules.block = block.gfm;\n if (this.options.breaks) {\n rules.inline = inline.breaks;\n } else {\n rules.inline = inline.gfm;\n }\n }\n this.tokenizer.rules = rules;\n }\n\n /**\n * Expose Rules\n */\n static get rules() {\n return {\n block,\n inline,\n };\n }\n\n /**\n * Static Lex Method\n */\n static lex<ParserOutput = string, RendererOutput = string>(src: string, options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const lexer = new _Lexer<ParserOutput, RendererOutput>(options);\n return lexer.lex(src);\n }\n\n /**\n * Static Lex Inline Method\n */\n static lexInline<ParserOutput = string, RendererOutput = string>(src: string, options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const lexer = new _Lexer<ParserOutput, RendererOutput>(options);\n return lexer.inlineTokens(src);\n }\n\n /**\n * Preprocessing\n */\n lex(src: string) {\n src = src.replace(other.carriageReturn, '\\n');\n\n this.blockTokens(src, this.tokens);\n\n for (let i = 0; i < this.inlineQueue.length; i++) {\n const next = this.inlineQueue[i];\n this.inlineTokens(next.src, next.tokens);\n }\n this.inlineQueue = [];\n\n return this.tokens;\n }\n\n /**\n * Lexing\n */\n blockTokens(src: string, tokens?: Token[], lastParagraphClipped?: boolean): Token[];\n blockTokens(src: string, tokens?: TokensList, lastParagraphClipped?: boolean): TokensList;\n blockTokens(src: string, tokens: Token[] = [], lastParagraphClipped = false) {\n if (this.options.pedantic) {\n src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, '');\n }\n\n while (src) {\n let token: Tokens.Generic | undefined;\n\n if (this.options.extensions?.block?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.raw.length === 1 && lastToken !== undefined) {\n // if there's a single \\n as a spacer, it's terminating the last line,\n // so move it there so that we don't get unnecessary paragraph tags\n lastToken.raw += '\\n';\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n // An indented code block cannot interrupt a paragraph.\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // fences\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // hr\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // list\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title,\n };\n tokens.push(token);\n }\n continue;\n }\n\n // table (gfm)\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n const lastToken = tokens.at(-1);\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n lastParagraphClipped = cutSrc.length !== src.length;\n src = src.substring(token.raw.length);\n continue;\n }\n\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n\n this.state.top = true;\n return tokens;\n }\n\n inline(src: string, tokens: Token[] = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n\n /**\n * Lexing/Compiling\n */\n inlineTokens(src: string, tokens: Token[] = []): Token[] {\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match: RegExpExecArray | null = null;\n\n // Mask out reflinks\n if (this.tokens.links) {\n const links = Object.keys(this.tokens.links);\n if (links.length > 0) {\n while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {\n maskedSrc = maskedSrc.slice(0, match.index)\n + '[' + 'a'.repeat(match[0].length - 2) + ']'\n + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\n\n // Mask out escaped characters\n while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);\n }\n\n // Mask out other blocks\n let offset;\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n offset = match[2] ? match[2].length : 0;\n maskedSrc = maskedSrc.slice(0, match.index + offset) + '[' + 'a'.repeat(match[0].length - offset - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n\n // Mask out blocks from extensions\n maskedSrc = this.options.hooks?.emStrongMask?.call({ lexer: this }, maskedSrc) ?? maskedSrc;\n\n let keepPrevChar = false;\n let prevChar = '';\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n\n let token: Tokens.Generic | undefined;\n\n // extensions\n if (this.options.extensions?.inline?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // link\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.type === 'text' && lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // em & strong\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // br\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // del (gfm)\n if (token = this.tokenizer.del(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // autolink\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // url (gfm)\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n\n return tokens;\n }\n}\n","import { _defaults } from './defaults.ts';\nimport {\n cleanUrl,\n escape,\n} from './helpers.ts';\nimport { other } from './rules.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Tokens } from './Tokens.ts';\nimport type { _Parser } from './Parser.ts';\n\n/**\n * Renderer\n */\nexport class _Renderer<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n parser!: _Parser<ParserOutput, RendererOutput>; // set by the parser\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n }\n\n space(token: Tokens.Space): RendererOutput {\n return '' as RendererOutput;\n }\n\n code({ text, lang, escaped }: Tokens.Code): RendererOutput {\n const langString = (lang || '').match(other.notSpaceStart)?.[0];\n\n const code = text.replace(other.endingNewline, '') + '\\n';\n\n if (!langString) {\n return '<pre><code>'\n + (escaped ? code : escape(code, true))\n + '</code></pre>\\n' as RendererOutput;\n }\n\n return '<pre><code class=\"language-'\n + escape(langString)\n + '\">'\n + (escaped ? code : escape(code, true))\n + '</code></pre>\\n' as RendererOutput;\n }\n\n blockquote({ tokens }: Tokens.Blockquote): RendererOutput {\n const body = this.parser.parse(tokens);\n return `<blockquote>\\n${body}</blockquote>\\n` as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n def(token: Tokens.Def): RendererOutput {\n return '' as RendererOutput;\n }\n\n heading({ tokens, depth }: Tokens.Heading): RendererOutput {\n return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>\\n` as RendererOutput;\n }\n\n hr(token: Tokens.Hr): RendererOutput {\n return '<hr>\\n' as RendererOutput;\n }\n\n list(token: Tokens.List): RendererOutput {\n const ordered = token.ordered;\n const start = token.start;\n\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n body += this.listitem(item);\n }\n\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '</' + type + '>\\n' as RendererOutput;\n }\n\n listitem(item: Tokens.ListItem): RendererOutput {\n let itemBody = '';\n if (item.task) {\n const checkbox = this.checkbox({ checked: !!item.checked });\n if (item.loose) {\n if (item.tokens[0]?.type === 'paragraph') {\n item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n item.tokens[0].tokens[0].text = checkbox + ' ' + escape(item.tokens[0].tokens[0].text);\n item.tokens[0].tokens[0].escaped = true;\n }\n } else {\n item.tokens.unshift({\n type: 'text',\n raw: checkbox + ' ',\n text: checkbox + ' ',\n escaped: true,\n });\n }\n } else {\n itemBody += checkbox + ' ';\n }\n }\n\n itemBody += this.parser.parse(item.tokens, !!item.loose);\n\n return `<li>${itemBody}</li>\\n` as RendererOutput;\n }\n\n checkbox({ checked }: Tokens.Checkbox): RendererOutput {\n return '<input '\n + (checked ? 'checked=\"\" ' : '')\n + 'disabled=\"\" type=\"checkbox\">' as RendererOutput;\n }\n\n paragraph({ tokens }: Tokens.Paragraph): RendererOutput {\n return `<p>${this.parser.parseInline(tokens)}</p>\\n` as RendererOutput;\n }\n\n table(token: Tokens.Table): RendererOutput {\n let header = '';\n\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell(token.header[j]);\n }\n header += this.tablerow({ text: cell as ParserOutput });\n\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n\n body += this.tablerow({ text: cell as ParserOutput });\n }\n if (body) body = `<tbody>${body}</tbody>`;\n\n return '<table>\\n'\n + '<thead>\\n'\n + header\n + '</thead>\\n'\n + body\n + '</table>\\n' as RendererOutput;\n }\n\n tablerow({ text }: Tokens.TableRow<ParserOutput>): RendererOutput {\n return `<tr>\\n${text}</tr>\\n` as RendererOutput;\n }\n\n tablecell(token: Tokens.TableCell): RendererOutput {\n const content = this.parser.parseInline(token.tokens);\n const type = token.header ? 'th' : 'td';\n const tag = token.align\n ? `<${type} align=\"${token.align}\">`\n : `<${type}>`;\n return tag + content + `</${type}>\\n` as RendererOutput;\n }\n\n /**\n * span level renderer\n */\n strong({ tokens }: Tokens.Strong): RendererOutput {\n return `<strong>${this.parser.parseInline(tokens)}</strong>` as RendererOutput;\n }\n\n em({ tokens }: Tokens.Em): RendererOutput {\n return `<em>${this.parser.parseInline(tokens)}</em>` as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return `<code>${escape(text, true)}</code>` as RendererOutput;\n }\n\n br(token: Tokens.Br): RendererOutput {\n return '<br>' as RendererOutput;\n }\n\n del({ tokens }: Tokens.Del): RendererOutput {\n return `<del>${this.parser.parseInline(tokens)}</del>` as RendererOutput;\n }\n\n link({ href, title, tokens }: Tokens.Link): RendererOutput {\n const text = this.parser.parseInline(tokens) as string;\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text as RendererOutput;\n }\n href = cleanHref;\n let out = '<a href=\"' + href + '\"';\n if (title) {\n out += ' title=\"' + (escape(title)) + '\"';\n }\n out += '>' + text + '</a>';\n return out as RendererOutput;\n }\n\n image({ href, title, text, tokens }: Tokens.Image): RendererOutput {\n if (tokens) {\n text = this.parser.parseInline(tokens, this.parser.textRenderer) as string;\n }\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return escape(text) as RendererOutput;\n }\n href = cleanHref;\n\n let out = `<img src=\"${href}\" alt=\"${text}\"`;\n if (title) {\n out += ` title=\"${escape(title)}\"`;\n }\n out += '>';\n return out as RendererOutput;\n }\n\n text(token: Tokens.Text | Tokens.Escape): RendererOutput {\n return 'tokens' in token && token.tokens\n ? this.parser.parseInline(token.tokens) as unknown as RendererOutput\n : ('escaped' in token && token.escaped ? token.text as RendererOutput : escape(token.text) as RendererOutput);\n }\n}\n","import type { Tokens } from './Tokens.ts';\n\n/**\n * TextRenderer\n * returns only the textual part of the token\n */\nexport class _TextRenderer<RendererOutput = string> {\n // no need for block level renderers\n strong({ text }: Tokens.Strong): RendererOutput {\n return text as RendererOutput;\n }\n\n em({ text }: Tokens.Em): RendererOutput {\n return text as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return text as RendererOutput;\n }\n\n del({ text }: Tokens.Del): RendererOutput {\n return text as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n link({ text }: Tokens.Link): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n image({ text }: Tokens.Image): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n br(): RendererOutput {\n return '' as RendererOutput;\n }\n}\n","import { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _defaults } from './defaults.ts';\nimport type { MarkedToken, Token, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Parsing & Compiling\n */\nexport class _Parser<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n renderer: _Renderer<ParserOutput, RendererOutput>;\n textRenderer: _TextRenderer<RendererOutput>;\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n this.options.renderer = this.options.renderer || new _Renderer<ParserOutput, RendererOutput>();\n this.renderer = this.options.renderer;\n this.renderer.options = this.options;\n this.renderer.parser = this;\n this.textRenderer = new _TextRenderer<RendererOutput>();\n }\n\n /**\n * Static Parse Method\n */\n static parse<ParserOutput = string, RendererOutput = string>(tokens: Token[], options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const parser = new _Parser<ParserOutput, RendererOutput>(options);\n return parser.parse(tokens);\n }\n\n /**\n * Static Parse Inline Method\n */\n static parseInline<ParserOutput = string, RendererOutput = string>(tokens: Token[], options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const parser = new _Parser<ParserOutput, RendererOutput>(options);\n return parser.parseInline(tokens);\n }\n\n /**\n * Parse Loop\n */\n parse(tokens: Token[], top = true): ParserOutput {\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const genericToken = anyToken as Tokens.Generic;\n const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);\n if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'def', 'paragraph', 'text'].includes(genericToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'space': {\n out += this.renderer.space(token);\n continue;\n }\n case 'hr': {\n out += this.renderer.hr(token);\n continue;\n }\n case 'heading': {\n out += this.renderer.heading(token);\n continue;\n }\n case 'code': {\n out += this.renderer.code(token);\n continue;\n }\n case 'table': {\n out += this.renderer.table(token);\n continue;\n }\n case 'blockquote': {\n out += this.renderer.blockquote(token);\n continue;\n }\n case 'list': {\n out += this.renderer.list(token);\n continue;\n }\n case 'html': {\n out += this.renderer.html(token);\n continue;\n }\n case 'def': {\n out += this.renderer.def(token);\n continue;\n }\n case 'paragraph': {\n out += this.renderer.paragraph(token);\n continue;\n }\n case 'text': {\n let textToken = token;\n let body = this.renderer.text(textToken) as string;\n while (i + 1 < tokens.length && tokens[i + 1].type === 'text') {\n textToken = tokens[++i] as Tokens.Text;\n body += ('\\n' + this.renderer.text(textToken));\n }\n if (top) {\n out += this.renderer.paragraph({\n type: 'paragraph',\n raw: body,\n text: body,\n tokens: [{ type: 'text', raw: body, text: body, escaped: true }],\n });\n } else {\n out += body;\n }\n continue;\n }\n\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n\n return out as ParserOutput;\n }\n\n /**\n * Parse Inline Tokens\n */\n parseInline(tokens: Token[], renderer: _Renderer<ParserOutput, RendererOutput> | _TextRenderer<RendererOutput> = this.renderer): ParserOutput {\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);\n if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'escape': {\n out += renderer.text(token);\n break;\n }\n case 'html': {\n out += renderer.html(token);\n break;\n }\n case 'link': {\n out += renderer.link(token);\n break;\n }\n case 'image': {\n out += renderer.image(token);\n break;\n }\n case 'strong': {\n out += renderer.strong(token);\n break;\n }\n case 'em': {\n out += renderer.em(token);\n break;\n }\n case 'codespan': {\n out += renderer.codespan(token);\n break;\n }\n case 'br': {\n out += renderer.br(token);\n break;\n }\n case 'del': {\n out += renderer.del(token);\n break;\n }\n case 'text': {\n out += renderer.text(token);\n break;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out as ParserOutput;\n }\n}\n","import { _defaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\n\nexport class _Hooks<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n block?: boolean;\n\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n }\n\n static passThroughHooks = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n 'emStrongMask',\n ]);\n\n static passThroughHooksRespectAsync = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n ]);\n\n /**\n * Process markdown before marked\n */\n preprocess(markdown: string) {\n return markdown;\n }\n\n /**\n * Process HTML after marked is finished\n */\n postprocess(html: ParserOutput) {\n return html;\n }\n\n /**\n * Process all tokens before walk tokens\n */\n processAllTokens(tokens: Token[] | TokensList) {\n return tokens;\n }\n\n /**\n * Mask contents that should not be interpreted as em/strong delimiters\n */\n emStrongMask(src: string) {\n return src;\n }\n\n /**\n * Provide function to tokenize markdown\n */\n provideLexer() {\n return this.block ? _Lexer.lex : _Lexer.lexInline;\n }\n\n /**\n * Provide function to parse tokens\n */\n provideParser() {\n return this.block ? _Parser.parse<ParserOutput, RendererOutput> : _Parser.parseInline<ParserOutput, RendererOutput>;\n }\n}\n","import { _getDefaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { escape } from './helpers.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, Tokens, TokensList } from './Tokens.ts';\n\nexport type MaybePromise = void | Promise<void>;\n\ntype UnknownFunction = (...args: unknown[]) => unknown;\ntype GenericRendererFunction = (...args: unknown[]) => string | false;\n\nexport class Marked<ParserOutput = string, RendererOutput = string> {\n defaults = _getDefaults<ParserOutput, RendererOutput>();\n options = this.setOptions;\n\n parse = this.parseMarkdown(true);\n parseInline = this.parseMarkdown(false);\n\n Parser = _Parser<ParserOutput, RendererOutput>;\n Renderer = _Renderer<ParserOutput, RendererOutput>;\n TextRenderer = _TextRenderer<RendererOutput>;\n Lexer = _Lexer;\n Tokenizer = _Tokenizer<ParserOutput, RendererOutput>;\n Hooks = _Hooks<ParserOutput, RendererOutput>;\n\n constructor(...args: MarkedExtension<ParserOutput, RendererOutput>[]) {\n this.use(...args);\n }\n\n /**\n * Run callback for every token\n */\n walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n let values: MaybePromise[] = [];\n for (const token of tokens) {\n values = values.concat(callback.call(this, token));\n switch (token.type) {\n case 'table': {\n const tableToken = token as Tokens.Table;\n for (const cell of tableToken.header) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n for (const row of tableToken.rows) {\n for (const cell of row) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n }\n break;\n }\n case 'list': {\n const listToken = token as Tokens.List;\n values = values.concat(this.walkTokens(listToken.items, callback));\n break;\n }\n default: {\n const genericToken = token as Tokens.Generic;\n if (this.defaults.extensions?.childTokens?.[genericToken.type]) {\n this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {\n const tokens = genericToken[childTokens].flat(Infinity) as Token[] | TokensList;\n values = values.concat(this.walkTokens(tokens, callback));\n });\n } else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n\n use(...args: MarkedExtension<ParserOutput, RendererOutput>[]) {\n const extensions: MarkedOptions<ParserOutput, RendererOutput>['extensions'] = this.defaults.extensions || { renderers: {}, childTokens: {} };\n\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack } as MarkedOptions<ParserOutput, RendererOutput>;\n\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n\n // ==-- Parse \"addon\" extensions --== //\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error('extension name required');\n }\n if ('renderer' in ext) { // Renderer extensions\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n // Replace extension with func to run new extension but fall back if false\n extensions.renderers[ext.name] = function(...args) {\n let ret = ext.renderer.apply(this, args);\n if (ret === false) {\n ret = prevRenderer.apply(this, args);\n }\n return ret;\n };\n } else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if ('tokenizer' in ext) { // Tokenizer Extensions\n if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n } else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) { // Function to check for start of token\n if (ext.level === 'block') {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n } else {\n extensions.startBlock = [ext.start];\n }\n } else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n } else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n\n // ==-- Parse \"overwrite\" extensions --== //\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer<ParserOutput, RendererOutput>(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if (['options', 'parser'].includes(prop)) {\n // ignore options property\n continue;\n }\n const rendererProp = prop as Exclude<keyof _Renderer<ParserOutput, RendererOutput>, 'options' | 'parser'>;\n const rendererFunc = pack.renderer[rendererProp] as GenericRendererFunction;\n const prevRenderer = renderer[rendererProp] as GenericRendererFunction;\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args: unknown[]) => {\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return (ret || '') as RendererOutput;\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer<ParserOutput, RendererOutput>(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if (['options', 'rules', 'lexer'].includes(prop)) {\n // ignore options, rules, and lexer properties\n continue;\n }\n const tokenizerProp = prop as Exclude<keyof _Tokenizer<ParserOutput, RendererOutput>, 'options' | 'rules' | 'lexer'>;\n const tokenizerFunc = pack.tokenizer[tokenizerProp] as UnknownFunction;\n const prevTokenizer = tokenizer[tokenizerProp] as UnknownFunction;\n // Replace tokenizer with func to run extension, but fall back if false\n // @ts-expect-error cannot type tokenizer function dynamically\n tokenizer[tokenizerProp] = (...args: unknown[]) => {\n let ret = tokenizerFunc.apply(tokenizer, args);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n\n // ==-- Parse Hooks extensions --== //\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks<ParserOutput, RendererOutput>();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if (['options', 'block'].includes(prop)) {\n // ignore options and block properties\n continue;\n }\n const hooksProp = prop as Exclude<keyof _Hooks<ParserOutput, RendererOutput>, 'options' | 'block'>;\n const hooksFunc = pack.hooks[hooksProp] as UnknownFunction;\n const prevHook = hooks[hooksProp] as UnknownFunction;\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg: unknown) => {\n if (this.defaults.async && _Hooks.passThroughHooksRespectAsync.has(prop)) {\n return (async() => {\n const ret = await hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n })();\n }\n\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n } else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args: unknown[]) => {\n if (this.defaults.async) {\n return (async() => {\n let ret = await hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = await prevHook.apply(hooks, args);\n }\n return ret;\n })();\n }\n\n let ret = hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = prevHook.apply(hooks, args);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n\n // ==-- Parse WalkTokens extensions --== //\n if (pack.walkTokens) {\n const walkTokens = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function(token) {\n let values: MaybePromise[] = [];\n values.push(packWalktokens.call(this, token));\n if (walkTokens) {\n values = values.concat(walkTokens.call(this, token));\n }\n return values;\n };\n }\n\n this.defaults = { ...this.defaults, ...opts };\n });\n\n return this;\n }\n\n setOptions(opt: MarkedOptions<ParserOutput, RendererOutput>) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n\n lexer(src: string, options?: MarkedOptions<ParserOutput, RendererOutput>) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n\n parser(tokens: Token[], options?: MarkedOptions<ParserOutput, RendererOutput>) {\n return _Parser.parse<ParserOutput, RendererOutput>(tokens, options ?? this.defaults);\n }\n\n private parseMarkdown(blockType: boolean) {\n type overloadedParse = {\n (src: string, options: MarkedOptions<ParserOutput, RendererOutput> & { async: true }): Promise<ParserOutput>;\n (src: string, options: MarkedOptions<ParserOutput, RendererOutput> & { async: false }): ParserOutput;\n (src: string, options?: MarkedOptions<ParserOutput, RendererOutput> | null): ParserOutput | Promise<ParserOutput>;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const parse: overloadedParse = (src: string, options?: MarkedOptions<ParserOutput, RendererOutput> | null): any => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n\n const throwError = this.onError(!!opt.silent, !!opt.async);\n\n // throw error if an extension set async to true but parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));\n }\n\n // throw error in case of non string input\n if (typeof src === 'undefined' || src === null) {\n return throwError(new Error('marked(): input parameter is undefined or null'));\n }\n if (typeof src !== 'string') {\n return throwError(new Error('marked(): input parameter is of type '\n + Object.prototype.toString.call(src) + ', string expected'));\n }\n\n if (opt.hooks) {\n opt.hooks.options = opt;\n opt.hooks.block = blockType;\n }\n\n if (opt.async) {\n return (async() => {\n const processedSrc = opt.hooks ? await opt.hooks.preprocess(src) : src;\n const lexer = opt.hooks ? await opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);\n const tokens = await lexer(processedSrc, opt);\n const processedTokens = opt.hooks ? await opt.hooks.processAllTokens(tokens) : tokens;\n if (opt.walkTokens) {\n await Promise.all(this.walkTokens(processedTokens, opt.walkTokens));\n }\n const parser = opt.hooks ? await opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);\n const html = await parser(processedTokens, opt);\n return opt.hooks ? await opt.hooks.postprocess(html) : html;\n })().catch(throwError);\n }\n\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src) as string;\n }\n const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);\n let tokens = lexer(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n } catch(e) {\n return throwError(e as Error);\n }\n };\n\n return parse;\n }\n\n private onError(silent: boolean, async: boolean) {\n return (e: Error): string | Promise<string> => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n\n if (silent) {\n const msg = '<p>An error occurred:</p><pre>'\n + escape(e.message + '', true)\n + '</pre>';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n","import { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { Marked } from './Instance.ts';\nimport {\n _getDefaults,\n changeDefaults,\n _defaults,\n} from './defaults.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\nimport type { MaybePromise } from './Instance.ts';\n\nconst markedInstance = new Marked();\n\n/**\n * Compiles markdown to HTML asynchronously.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options, having async: true\n * @return Promise of string of compiled HTML\n */\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise<string>;\n\n/**\n * Compiles markdown to HTML.\n *\n * @param src String of markdown source to be compiled\n * @param options Optional hash of options\n * @return String of compiled HTML. Will be a Promise of string if async is set to true by any extensions.\n */\nexport function marked(src: string, options: MarkedOptions & { async: false }): string;\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise<string>;\nexport function marked(src: string, options?: MarkedOptions | null): string | Promise<string>;\nexport function marked(src: string, opt?: MarkedOptions | null): string | Promise<string> {\n return markedInstance.parse(src, opt);\n}\n\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\nmarked.setOptions = function(options: MarkedOptions) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\n\nmarked.defaults = _defaults;\n\n/**\n * Use Extension\n */\n\nmarked.use = function(...args: MarkedExtension[]) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n\n/**\n * Run callback for every token\n */\n\nmarked.walkTokens = function(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n return markedInstance.walkTokens(tokens, callback);\n};\n\n/**\n * Compiles markdown to HTML without enclosing `p` tag.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options\n * @return String of compiled HTML\n */\nmarked.parseInline = markedInstance.parseInline;\n\n/**\n * Expose\n */\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\n\nexport const options = marked.options;\nexport const setOptions = marked.setOptions;\nexport const use = marked.use;\nexport const walkTokens = marked.walkTokens;\nexport const parseInline = marked.parseInline;\nexport const parse = marked;\nexport const parser = _Parser.parse;\nexport const lexer = _Lexer.lex;\nexport { _defaults as defaults, _getDefaults as getDefaults } from './defaults.ts';\nexport { _Lexer as Lexer } from './Lexer.ts';\nexport { _Parser as Parser } from './Parser.ts';\nexport { _Tokenizer as Tokenizer } from './Tokenizer.ts';\nexport { _Renderer as Renderer } from './Renderer.ts';\nexport { _TextRenderer as TextRenderer } from './TextRenderer.ts';\nexport { _Hooks as Hooks } from './Hooks.ts';\nexport { Marked } from './Instance.ts';\nexport type * from './MarkedOptions.ts';\nexport type * from './Tokens.ts';\n","import { isVisibleAt, normalizePrivacy } from \"@vortex-os/core\";\nimport type { Privacy } from \"@vortex-os/core\";\nimport type { RenderWarning } from \"./types.js\";\n\nconst SECTION_PATTERN =\n /<!--\\s*vortex:privacy\\s+(\\w+)\\s*-->([\\s\\S]*?)<!--\\s*\\/vortex:privacy\\s*-->/g;\n\nexport interface StripResult {\n readonly content: string;\n readonly warnings: readonly RenderWarning[];\n}\n\n/**\n * Remove section blocks whose declared privacy exceeds the target.\n *\n * Each section is delimited by `<!-- vortex:privacy LEVEL -->` and\n * `<!-- /vortex:privacy -->`. Sections at or below target privacy keep\n * their body (markers themselves are removed). Sections above target are\n * stripped entirely and a `section-stripped` warning is reported.\n *\n * Sections do not nest; the parser does not support nesting.\n */\nexport function stripPrivateSections(\n content: string,\n targetPrivacy: Privacy,\n): StripResult {\n const warnings: RenderWarning[] = [];\n const out = content.replace(SECTION_PATTERN, (_match, levelRaw: string, body: string) => {\n const sectionPrivacy = normalizePrivacy(levelRaw);\n if (isVisibleAt(sectionPrivacy, targetPrivacy)) {\n return body;\n }\n warnings.push({\n kind: \"section-stripped\",\n reason: `Stripped section with privacy=${sectionPrivacy} (above target ${targetPrivacy})`,\n });\n return \"\";\n });\n return { content: out, warnings };\n}\n","/**\n * Minimal default template. Hosts that want styling, navigation, or\n * additional metadata should pass a custom `template` to `renderHtml`.\n */\nexport const DEFAULT_TEMPLATE = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>{{title}}</title>\n</head>\n<body>\n{{content}}\n</body>\n</html>\n`;\n\n/**\n * Replace `{{name}}` placeholders in a template string with values from\n * `vars`. Missing keys are replaced with the empty string.\n */\nexport function applyTemplate(\n template: string,\n vars: Readonly<Record<string, string>>,\n): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_match, key: string) => {\n return vars[key] ?? \"\";\n });\n}\n","import { marked } from \"marked\";\nimport { isVisibleAt, normalizePrivacy, parseFrontmatter } from \"@vortex-os/core\";\nimport type { Privacy } from \"@vortex-os/core\";\nimport { stripPrivateSections } from \"./filter.js\";\nimport { applyTemplate, DEFAULT_TEMPLATE } from \"./template.js\";\nimport type { RenderOptions, RenderResult } from \"./types.js\";\n\n/**\n * Render a markdown source to HTML, applying document-level and\n * section-level privacy filtering before conversion.\n *\n * If the document's own privacy exceeds the target, an empty result is\n * returned with a `document-not-visible` warning and no body conversion\n * is performed.\n */\nexport async function renderHtml(\n source: string,\n options: RenderOptions,\n): Promise<RenderResult> {\n const { frontmatter, body } = parseFrontmatter<{\n privacy?: unknown;\n title?: unknown;\n }>(source);\n const documentPrivacy: Privacy = normalizePrivacy(frontmatter.privacy);\n\n if (!isVisibleAt(documentPrivacy, options.targetPrivacy)) {\n return {\n html: \"\",\n documentPrivacy,\n visible: false,\n warnings: [\n {\n kind: \"document-not-visible\",\n reason: `Document privacy is ${documentPrivacy}; viewer target is ${options.targetPrivacy}.`,\n },\n ],\n };\n }\n\n const stripped = stripPrivateSections(body, options.targetPrivacy);\n const inner = (await Promise.resolve(\n marked.parse(stripped.content, { gfm: true, breaks: false }),\n )) as string;\n const title =\n options.title ?? (typeof frontmatter.title === \"string\" ? frontmatter.title : \"\");\n const template = options.template ?? DEFAULT_TEMPLATE;\n const html = applyTemplate(template, { title, content: inner });\n\n return {\n html,\n documentPrivacy,\n visible: true,\n warnings: stripped.warnings,\n };\n}\n","export type { TilEntry, TilFrontmatter } from \"./types.js\";\nexport { TilStore } from \"./store.js\";\nexport { appendSection } from \"./append.js\";\n","import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { parseFrontmatter } from \"@vortex-os/core\";\nimport type { TilEntry, TilFrontmatter } from \"./types.js\";\n\nconst FILENAME_PATTERN = /^(\\d{4}-\\d{2}-\\d{2})-(.+)\\.md$/;\nconst MONTH_PATTERN = /^\\d{2}$/;\nconst YEAR_PATTERN = /^\\d{4}$/;\n\n/**\n * Directory-backed TIL store. Expected layout: `<rootDir>/YYYY/MM/YYYY-MM-DD-keyword.md`.\n *\n * The store treats missing subdirectories as empty, never as errors —\n * a brand-new month with no entries returns an empty list, not a throw.\n */\nexport class TilStore {\n constructor(readonly rootDir: string) {}\n\n /** All entries across all years and months, sorted by date ascending. */\n async list(): Promise<readonly TilEntry[]> {\n const years = await this.listSubdirs(this.rootDir, YEAR_PATTERN);\n const entries: TilEntry[] = [];\n for (const year of years) {\n const yearDir = join(this.rootDir, year);\n const months = await this.listSubdirs(yearDir, MONTH_PATTERN);\n for (const month of months) {\n entries.push(...(await this.entriesIn(join(yearDir, month))));\n }\n }\n return entries.sort((a, b) =>\n a.date === b.date ? a.keyword.localeCompare(b.keyword) : a.date.localeCompare(b.date),\n );\n }\n\n /** Entries within one calendar month. */\n async listByMonth(year: number, month: number): Promise<readonly TilEntry[]> {\n const monthDir = join(\n this.rootDir,\n String(year).padStart(4, \"0\"),\n String(month).padStart(2, \"0\"),\n );\n const entries = await this.entriesIn(monthDir);\n return entries.sort((a, b) =>\n a.date === b.date ? a.keyword.localeCompare(b.keyword) : a.date.localeCompare(b.date),\n );\n }\n\n /**\n * The first entry matching `date` (`YYYY-MM-DD`). If multiple files exist\n * for that date with different keywords, the lexicographically-first one\n * is returned. Use `list()` when all are needed.\n */\n async get(date: string): Promise<TilEntry | undefined> {\n const [year, month] = date.split(\"-\");\n if (!year || !month) return undefined;\n const monthDir = join(this.rootDir, year, month);\n const entries = (await this.entriesIn(monthDir))\n .filter((e) => e.date === date)\n .sort((a, b) => a.keyword.localeCompare(b.keyword));\n return entries[0];\n }\n\n /** Most recent entry by date (descending), then keyword (descending). */\n async getLatest(): Promise<TilEntry | undefined> {\n const all = await this.list();\n if (all.length === 0) return undefined;\n return all[all.length - 1];\n }\n\n /** Resolve the file path for a given (date, keyword), without creating it. */\n pathFor(date: string, keyword: string): string {\n const [year, month] = date.split(\"-\");\n if (!year || !month) {\n throw new Error(`Invalid date: ${date} (expected YYYY-MM-DD)`);\n }\n return join(this.rootDir, year, month, `${date}-${keyword}.md`);\n }\n\n private async listSubdirs(dir: string, pattern: RegExp): Promise<readonly string[]> {\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n return entries\n .filter((e) => e.isDirectory() && pattern.test(e.name))\n .map((e) => e.name)\n .sort();\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw e;\n }\n }\n\n private async entriesIn(monthDir: string): Promise<TilEntry[]> {\n let names: string[];\n try {\n names = await readdir(monthDir);\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw e;\n }\n const out: TilEntry[] = [];\n for (const name of names) {\n const match = name.match(FILENAME_PATTERN);\n if (!match) continue;\n const path = join(monthDir, name);\n try {\n const info = await stat(path);\n if (!info.isFile()) continue;\n } catch {\n continue;\n }\n const raw = await readFile(path, \"utf8\");\n const { frontmatter, body } = parseFrontmatter<TilFrontmatter>(raw);\n const date = match[1] ?? \"\";\n const keyword = match[2] ?? \"\";\n out.push({ date, keyword, path, frontmatter, body });\n }\n return out;\n }\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport type { TilEntry } from \"./types.js\";\n\n/**\n * Append a new section to the end of an existing TIL entry's file.\n *\n * The resulting markdown adds two leading blank lines, then `## <title>`,\n * then a blank line, then the body. The entry's frontmatter is not touched.\n *\n * Returns the updated raw markdown that was written.\n */\nexport async function appendSection(\n entry: TilEntry,\n title: string,\n body: string,\n): Promise<string> {\n const original = await readFile(entry.path, \"utf8\");\n const trimmed = original.replace(/\\s+$/u, \"\");\n const section = `## ${title}\\n\\n${body.trimEnd()}\\n`;\n const next = `${trimmed}\\n\\n${section}`;\n await writeFile(entry.path, next, \"utf8\");\n return next;\n}\n","export type {\n DecisionEntry,\n DecisionFilter,\n DecisionLogFrontmatter,\n DecisionTemplateInput,\n} from \"./types.js\";\nexport { DecisionStore } from \"./store.js\";\nexport { renderTemplate } from \"./template.js\";\n","import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { parseFrontmatter } from \"@vortex-os/core\";\nimport type {\n DecisionEntry,\n DecisionFilter,\n DecisionLogFrontmatter,\n} from \"./types.js\";\n\nconst FILENAME_PATTERN = /^(\\d{4}-\\d{2}-\\d{2})-(.+)\\.md$/;\n\n/**\n * Directory-backed Decision-Log store. Expected layout is flat —\n * `<rootDir>/YYYY-MM-DD-<slug>.md`, no year/month subdirectories.\n *\n * Non-entry files at the root (README, _TEMPLATE, anything not matching\n * the date-prefix pattern) are silently ignored.\n *\n * A missing root directory returns an empty list rather than throwing,\n * so a brand-new template clone with no entries is a normal state.\n */\nexport class DecisionStore {\n constructor(readonly rootDir: string) {}\n\n /** All entries, sorted by date ascending, then slug ascending. */\n async list(): Promise<readonly DecisionEntry[]> {\n let names: string[];\n try {\n names = await readdir(this.rootDir);\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw e;\n }\n const out: DecisionEntry[] = [];\n for (const name of names) {\n const match = name.match(FILENAME_PATTERN);\n if (!match) continue;\n const path = join(this.rootDir, name);\n try {\n const info = await stat(path);\n if (!info.isFile()) continue;\n } catch {\n continue;\n }\n const raw = await readFile(path, \"utf8\");\n const { frontmatter, body } =\n parseFrontmatter<DecisionLogFrontmatter>(raw);\n const date = match[1] ?? \"\";\n const slug = match[2] ?? \"\";\n out.push({ date, slug, path, frontmatter, body });\n }\n return out.sort((a, b) =>\n a.date === b.date\n ? a.slug.localeCompare(b.slug)\n : a.date.localeCompare(b.date),\n );\n }\n\n /**\n * Entries whose filename starts with `date` (`YYYY-MM-DD`). Multiple\n * decisions on the same day are returned in slug-ascending order.\n */\n async getByDate(date: string): Promise<readonly DecisionEntry[]> {\n const all = await this.list();\n return all.filter((e) => e.date === date);\n }\n\n /**\n * The first entry matching `date` and (optionally) `slug`. When no slug is\n * provided and multiple entries share the date, the lexicographically-first\n * one is returned.\n */\n async get(date: string, slug?: string): Promise<DecisionEntry | undefined> {\n const matches = await this.getByDate(date);\n if (slug === undefined) return matches[0];\n return matches.find((e) => e.slug === slug);\n }\n\n /** Most recent entry by date (descending), then slug (descending). */\n async getLatest(): Promise<DecisionEntry | undefined> {\n const all = await this.list();\n if (all.length === 0) return undefined;\n return all[all.length - 1];\n }\n\n /**\n * Subset of entries matching the given criteria. Empty/undefined fields\n * are ignored. Returns entries in the same order as {@link list}.\n */\n async filter(criteria: DecisionFilter): Promise<readonly DecisionEntry[]> {\n const all = await this.list();\n return all.filter((e) => {\n if (criteria.status !== undefined && e.frontmatter.status !== criteria.status) {\n return false;\n }\n if (criteria.tag !== undefined) {\n const tags = e.frontmatter.tags ?? [];\n if (!tags.includes(criteria.tag)) return false;\n }\n if (criteria.fromDate !== undefined && e.date < criteria.fromDate) {\n return false;\n }\n if (criteria.toDate !== undefined && e.date > criteria.toDate) {\n return false;\n }\n return true;\n });\n }\n\n /** Resolve the file path for a given (date, slug), without creating it. */\n pathFor(date: string, slug: string): string {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(date)) {\n throw new Error(`Invalid date: ${date} (expected YYYY-MM-DD)`);\n }\n return join(this.rootDir, `${date}-${slug}.md`);\n }\n}\n","import type { DecisionTemplateInput } from \"./types.js\";\n\n/**\n * Render a new Decision-Log entry body using an obsidian-style template\n * convention. Caller is responsible for writing the result to disk via\n * {@link DecisionStore.pathFor}.\n *\n * The output deliberately mirrors a human-authored template so the\n * shape stays consistent whether the entry was created by hand or by\n * this helper.\n */\nexport function renderTemplate(input: DecisionTemplateInput): string {\n const tags = [\"decision-log\", ...(input.tags ?? [])];\n const tagsLine = tags.map((t) => `\"${t}\"`).join(\", \");\n const area = input.area ?? \"work / personal / other\";\n\n return [\n \"---\",\n \"type: decision-log\",\n \"status: active\",\n \"privacy: personal\",\n `created: ${input.date}`,\n `updated: ${input.date}`,\n `tags: [${tagsLine}]`,\n \"---\",\n \"\",\n `# ${input.title}`,\n \"\",\n `- **Date**: ${input.date}`,\n `- **Area**: ${area}`,\n \"- **Tag**: #decision-log\",\n \"\",\n \"## Context\",\n \"\",\n \"{What problem prompted this decision? Why was a choice required? 2-3 sentences.}\",\n \"\",\n \"## Options\",\n \"\",\n \"| Option | Content | Pros | Cons |\",\n \"|--------|---------|------|------|\",\n \"| A | | | |\",\n \"| B | | | |\",\n \"| C | | | |\",\n \"\",\n \"## Chosen: {A/B/C}\",\n \"\",\n \"## Why this one\",\n \"\",\n \"{The core section. The real reasoning behind the choice, candidly.}\",\n \"\",\n \"## Principle (patterns emerge when this repeats)\",\n \"\",\n \"> {One sentence: the judgment criterion this decision exposed.}\",\n \"\",\n \"## Result (optional)\",\n \"\",\n \"{Fill in only for verifiable decisions. Delete the section for taste/preference records.}\",\n \"\",\n ].join(\"\\n\");\n}\n","export type {\n IndexEntry,\n RenderIndexInput,\n ScanOptions,\n} from \"./types.js\";\nexport { scanDirectory } from \"./scan.js\";\nexport { renderIndex } from \"./render.js\";\nexport { findIndexableDirs } from \"./nested.js\";\n","import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { basename, extname, join, relative } from \"node:path\";\nimport { parseFrontmatter } from \"@vortex-os/core\";\nimport type { IndexEntry, ScanOptions } from \"./types.js\";\n\nconst RESERVED_FILES: ReadonlySet<string> = new Set([\"README.md\", \"_INDEX.md\"]);\nconst H1_PATTERN = /^#\\s+(.+?)\\s*$/m;\n\n/**\n * Scan a directory of markdown notes and produce one {@link IndexEntry}\n * per file, sorted by `relPath` ascending.\n *\n * - Files whose names are `README.md` or `_INDEX.md` are always skipped.\n * - Hidden entries (name starting with `.` or `_`, except `_TEMPLATE` which\n * is still surfaced but can be excluded via `skipPrefixes: [\"_TEMPLATE\"]`)\n * are not descended into when `recursive: true`.\n * - A missing directory returns an empty list rather than throwing.\n */\nexport async function scanDirectory(\n rootDir: string,\n opts: ScanOptions = {},\n): Promise<readonly IndexEntry[]> {\n const skipFilenames = new Set([\n ...RESERVED_FILES,\n ...(opts.skipFilenames ?? []),\n ]);\n const skipPrefixes = opts.skipPrefixes ?? [];\n const recursive = opts.recursive ?? false;\n\n const out: IndexEntry[] = [];\n await walk(rootDir, rootDir, recursive, skipFilenames, skipPrefixes, out);\n return out.sort((a, b) => a.relPath.localeCompare(b.relPath));\n}\n\nasync function walk(\n rootDir: string,\n currentDir: string,\n recursive: boolean,\n skipFilenames: ReadonlySet<string>,\n skipPrefixes: readonly string[],\n out: IndexEntry[],\n): Promise<void> {\n let entries;\n try {\n entries = await readdir(currentDir, { withFileTypes: true });\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw e;\n }\n\n for (const dirent of entries) {\n const name = dirent.name;\n if (dirent.isDirectory()) {\n if (!recursive) continue;\n if (name.startsWith(\".\") || name.startsWith(\"_\")) continue;\n await walk(\n rootDir,\n join(currentDir, name),\n recursive,\n skipFilenames,\n skipPrefixes,\n out,\n );\n continue;\n }\n if (!dirent.isFile()) continue;\n if (extname(name) !== \".md\") continue;\n if (skipFilenames.has(name)) continue;\n\n const nameNoExt = basename(name, \".md\");\n if (skipPrefixes.some((p) => nameNoExt.startsWith(p))) continue;\n\n const fullPath = join(currentDir, name);\n let info;\n try {\n info = await stat(fullPath);\n if (!info.isFile()) continue;\n } catch {\n continue;\n }\n const raw = await readFile(fullPath, \"utf8\");\n const { frontmatter, body } = parseFrontmatter<Record<string, unknown>>(raw);\n const title = extractTitle(body) ?? nameNoExt;\n const description = extractDescription(frontmatter, body);\n const type = stringField(frontmatter, \"type\");\n const updated =\n stringField(frontmatter, \"updated\") ?? stringField(frontmatter, \"created\");\n\n out.push({\n relPath: relative(rootDir, fullPath).split(/[\\\\/]/).join(\"/\"),\n name: nameNoExt,\n title,\n description,\n type,\n updated,\n });\n }\n}\n\nfunction extractTitle(body: string): string | undefined {\n const m = body.match(H1_PATTERN);\n if (!m) return undefined;\n return m[1]?.trim();\n}\n\nfunction extractDescription(\n frontmatter: Record<string, unknown>,\n body: string,\n): string | undefined {\n const fm = stringField(frontmatter, \"description\");\n if (fm) return fm;\n // First non-empty, non-heading, non-blockquote paragraph.\n const lines = body.split(/\\r?\\n/);\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n if (trimmed.startsWith(\"#\")) continue;\n if (trimmed.startsWith(\">\")) continue;\n if (trimmed.startsWith(\"-\") || trimmed.startsWith(\"*\")) continue;\n return trimmed.length > 160 ? `${trimmed.slice(0, 157)}...` : trimmed;\n }\n return undefined;\n}\n\nfunction stringField(\n obj: Record<string, unknown>,\n key: string,\n): string | undefined {\n const v = obj[key];\n return typeof v === \"string\" && v.length > 0 ? v : undefined;\n}\n","import type { RenderIndexInput } from \"./types.js\";\n\n/**\n * Render an `_INDEX.md` body from a {@link RenderIndexInput}.\n *\n * Output shape:\n *\n * ---\n * type: index\n * status: active\n * privacy: <privacy>\n * updated: <updated>\n * tags: [index, <extraTags...>]\n * ---\n *\n * # <title>\n *\n * > <description>\n *\n * ## 항목 (<count>)\n *\n * | 파일 | 설명 | 갱신 |\n * |---|---|---|\n * | [[<name>]] | <description or title> | <updated> |\n * ...\n *\n * ## 관련 (only if `related` is non-empty)\n *\n * - [[<related[0]>]]\n * ...\n *\n * Caller is responsible for writing this body to disk. The renderer never\n * touches the filesystem.\n */\nexport function renderIndex(input: RenderIndexInput): string {\n const updated = input.updated ?? today();\n const privacy = input.privacy ?? \"internal\";\n const tags = [\"index\", ...(input.extraTags ?? [])];\n const tagsLine = tags.map((t) => `\"${t}\"`).join(\", \");\n\n const lines: string[] = [\n \"---\",\n \"type: index\",\n \"status: active\",\n `privacy: ${privacy}`,\n `updated: ${updated}`,\n `tags: [${tagsLine}]`,\n \"---\",\n \"\",\n `# ${input.title}`,\n \"\",\n ];\n\n if (input.description && input.description.length > 0) {\n lines.push(`> ${input.description}`, \"\");\n }\n\n lines.push(`## 항목 (${input.entries.length})`, \"\");\n\n if (input.entries.length === 0) {\n lines.push(\"(비어 있음)\", \"\");\n } else {\n lines.push(\"| 파일 | 설명 | 갱신 |\", \"|---|---|---|\");\n for (const e of input.entries) {\n const desc = sanitizeCell(e.description ?? e.title);\n const upd = e.updated ?? \"—\";\n lines.push(`| [[${e.name}]] | ${desc} | ${upd} |`);\n }\n lines.push(\"\");\n }\n\n if (input.related && input.related.length > 0) {\n lines.push(\"## 관련\", \"\");\n for (const r of input.related) {\n lines.push(`- [[${r}]]`);\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n\nfunction sanitizeCell(s: string): string {\n // Markdown tables: pipe must be escaped, newlines collapse to spaces.\n return s.replace(/\\|/g, \"\\\\|\").replace(/\\r?\\n/g, \" \").trim();\n}\n\nfunction today(): string {\n const d = new Date();\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, \"0\");\n const day = String(d.getDate()).padStart(2, \"0\");\n return `${y}-${m}-${day}`;\n}\n","import { readdir, stat } from \"node:fs/promises\";\nimport { extname, join } from \"node:path\";\n\n/**\n * Walk a directory tree and return every subdirectory that contains at\n * least `minEntries` markdown files at its top level. The root directory\n * itself is included if it qualifies.\n *\n * \"At its top level\" means `.md` files **directly inside** the directory\n * (not in its subdirectories) — this is what an `_INDEX.md` in that\n * directory would index.\n *\n * `README.md` and `_INDEX.md` files are not counted (they are not\n * indexable entries). `.md` files starting with prefixes in `skipPrefixes`\n * are also not counted.\n *\n * Hidden directories (`.foo`) are not descended into. `_foo` directories\n * are descended into — they may legitimately contain content\n * (`_HUB-*.md`, `_INDEX.md` of subdirectories).\n *\n * A missing root directory returns an empty list rather than throwing.\n *\n * Use case — splitting a giant flat `_INDEX.md` into per-folder\n * indexes: scan a tree, find the meaningful directories, write an\n * `_INDEX.md` in each.\n */\nexport async function findIndexableDirs(\n rootDir: string,\n options: {\n minEntries?: number;\n skipPrefixes?: readonly string[];\n } = {},\n): Promise<readonly string[]> {\n const minEntries = options.minEntries ?? 1;\n const skipPrefixes = options.skipPrefixes ?? [];\n const out: string[] = [];\n await walk(rootDir, minEntries, skipPrefixes, out);\n return out;\n}\n\nasync function walk(\n dir: string,\n minEntries: number,\n skipPrefixes: readonly string[],\n out: string[],\n): Promise<void> {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw e;\n }\n\n let mdCount = 0;\n const subdirs: string[] = [];\n for (const dirent of entries) {\n if (dirent.isDirectory()) {\n if (dirent.name.startsWith(\".\")) continue;\n subdirs.push(dirent.name);\n continue;\n }\n if (!dirent.isFile()) continue;\n if (extname(dirent.name) !== \".md\") continue;\n if (dirent.name === \"README.md\" || dirent.name === \"_INDEX.md\") continue;\n const nameNoExt = dirent.name.slice(0, -3);\n if (skipPrefixes.some((p) => nameNoExt.startsWith(p))) continue;\n // Confirm it's a regular file (not a symlink to a directory, etc.).\n try {\n const info = await stat(join(dir, dirent.name));\n if (!info.isFile()) continue;\n } catch {\n continue;\n }\n mdCount++;\n }\n\n if (mdCount >= minEntries) {\n out.push(dir);\n }\n\n for (const name of subdirs) {\n await walk(join(dir, name), minEntries, skipPrefixes, out);\n }\n}\n","export type {\n RunbookEntry,\n RunbookFilter,\n RunbookFrontmatter,\n} from \"./types.js\";\nexport { RunbookStore } from \"./store.js\";\n","import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { extname, join } from \"node:path\";\nimport { parseFrontmatter } from \"@vortex-os/core\";\nimport type {\n RunbookEntry,\n RunbookFilter,\n RunbookFrontmatter,\n} from \"./types.js\";\n\nconst RESERVED_FILES: ReadonlySet<string> = new Set([\"README.md\", \"_INDEX.md\"]);\n\n/**\n * Directory-backed runbook store. Expected layout is flat —\n * `<rootDir>/<slug>.md`, no subdirectories.\n *\n * Non-entry files at the root (README, _INDEX, anything not ending in `.md`)\n * are silently ignored. A missing root directory returns an empty list\n * rather than throwing.\n */\nexport class RunbookStore {\n constructor(readonly rootDir: string) {}\n\n /** All entries, sorted by slug ascending. */\n async list(): Promise<readonly RunbookEntry[]> {\n let names: string[];\n try {\n names = await readdir(this.rootDir);\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw e;\n }\n const out: RunbookEntry[] = [];\n for (const name of names) {\n if (extname(name) !== \".md\") continue;\n if (RESERVED_FILES.has(name)) continue;\n const path = join(this.rootDir, name);\n try {\n const info = await stat(path);\n if (!info.isFile()) continue;\n } catch {\n continue;\n }\n const raw = await readFile(path, \"utf8\");\n const { frontmatter, body } =\n parseFrontmatter<RunbookFrontmatter>(raw);\n const slug = name.slice(0, -3);\n out.push({ slug, path, frontmatter, body });\n }\n return out.sort((a, b) => a.slug.localeCompare(b.slug));\n }\n\n /** A single entry by slug, or undefined if not found. */\n async get(slug: string): Promise<RunbookEntry | undefined> {\n const all = await this.list();\n return all.find((e) => e.slug === slug);\n }\n\n /**\n * Subset of entries matching the given criteria. Empty/undefined fields\n * are ignored. Returns entries in the same order as {@link list}.\n */\n async filter(criteria: RunbookFilter): Promise<readonly RunbookEntry[]> {\n const all = await this.list();\n return all.filter((e) => {\n if (criteria.status !== undefined && e.frontmatter.status !== criteria.status) {\n return false;\n }\n if (criteria.tag !== undefined) {\n const tags = e.frontmatter.tags ?? [];\n if (!tags.includes(criteria.tag)) return false;\n }\n if (\n criteria.incidentType !== undefined &&\n e.frontmatter[\"incident-type\"] !== criteria.incidentType\n ) {\n return false;\n }\n return true;\n });\n }\n\n /**\n * Entries whose `last_tested` is older than `staleAfterDays` from the\n * given reference date (default: today). Entries without a `last_tested`\n * field are treated as \"never tested\" and are always returned.\n *\n * This is the practical reason runbooks are a module rather than plain\n * data — periodic reverification is a real operational need.\n */\n async getStaleByLastTested(\n staleAfterDays: number,\n referenceDate?: Date,\n ): Promise<readonly RunbookEntry[]> {\n if (!Number.isFinite(staleAfterDays) || staleAfterDays < 0) {\n throw new Error(`Invalid staleAfterDays: ${staleAfterDays}`);\n }\n const now = referenceDate ?? new Date();\n const threshold = now.getTime() - staleAfterDays * 86_400_000;\n const all = await this.list();\n return all.filter((e) => {\n const lt = e.frontmatter.last_tested;\n if (!lt) return true;\n const parsed = parseIsoDate(lt);\n if (parsed === undefined) return true;\n return parsed < threshold;\n });\n }\n}\n\nfunction parseIsoDate(s: string): number | undefined {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(s)) return undefined;\n const t = Date.parse(`${s}T00:00:00Z`);\n return Number.isNaN(t) ? undefined : t;\n}\n","export type {\n BrokenLink,\n LinkCheckResult,\n WikiLink,\n} from \"./types.js\";\nexport { extractWikiLinks } from \"./extract.js\";\nexport {\n buildFileIndex,\n resolveLink,\n toRel,\n} from \"./resolve.js\";\nexport type {\n BuildIndexOptions,\n FileIndex,\n ResolveOpts,\n ResolveOutcome,\n} from \"./resolve.js\";\nexport { checkDirectory, topBrokenTargets } from \"./checker.js\";\nexport type { CheckDirectoryOptions } from \"./checker.js\";\nexport { rewriteBody, rewriteDirectory } from \"./rewrite.js\";\nexport type {\n FileRewrite,\n RedirectionMap,\n RewriteOptions,\n RewriteResult,\n} from \"./rewrite.js\";\n","import type { WikiLink } from \"./types.js\";\n\n/**\n * Match a single wiki link including optional anchor and alias.\n *\n * `[[name]]` / `[[name|alias]]` / `[[name#anchor]]` / `[[name#anchor|alias]]`\n *\n * The name part disallows `|`, `#`, and `]` so the components separate\n * cleanly even when several links appear on one line.\n */\nconst WIKI_LINK_PATTERN = /\\[\\[([^\\]|#\\n]+?)(?:#([^\\]|\\n]+?))?(?:\\|([^\\]\\n]+?))?\\]\\]/g;\n\n/**\n * Extract every wiki link from a markdown body. Returns links in\n * document order; duplicates are preserved (callers can dedupe if they\n * want, but a broken link in two places is still two repairs).\n *\n * Code fences and inline code spans are not stripped — this module\n * treats markdown as text. Hosts that need to ignore links inside\n * code blocks should pre-filter the body.\n */\nexport function extractWikiLinks(body: string): readonly WikiLink[] {\n const out: WikiLink[] = [];\n for (const match of body.matchAll(WIKI_LINK_PATTERN)) {\n const name = match[1]?.trim();\n if (!name) continue;\n const anchor = match[2]?.trim();\n const alias = match[3]?.trim();\n out.push({\n name,\n anchor: anchor || undefined,\n alias: alias || undefined,\n raw: match[0],\n });\n }\n return out;\n}\n","import { readdir, stat } from \"node:fs/promises\";\nimport {\n basename,\n dirname,\n extname,\n isAbsolute,\n join,\n relative,\n resolve as pathResolve,\n} from \"node:path\";\n\n/**\n * Filesystem index of every `.md` file under a root.\n *\n * Provides two lookup paths:\n *\n * - `byBasename` — `name` (no `.md`) → list of absolute paths. Used for\n * bare wiki links like `[[Foo]]`, which Obsidian resolves by filename\n * anywhere in the vault.\n * - `byRelPath` — forward-slash relative path (no `.md`) → absolute path.\n * Used for path-aware wiki links like `[[Projects/Home/Foo]]` or\n * `[[../Foo]]`, where the operator wrote a path on purpose to\n * disambiguate.\n *\n * `rootDir` is retained so resolvers can interpret root-relative paths.\n */\nexport interface FileIndex {\n readonly byBasename: ReadonlyMap<string, readonly string[]>;\n readonly byRelPath: ReadonlyMap<string, string>;\n /**\n * Optional lowercase rel-path → absolute-path map for case-insensitive\n * fallback. Present only when {@link buildFileIndex} was called with\n * `caseInsensitive: true`. If two rel-paths collide after lowercasing,\n * the first walker-visited path wins; the conflict is silent (rare in\n * a well-organized tree).\n */\n readonly byRelPathLower?: ReadonlyMap<string, string>;\n readonly rootDir: string;\n}\n\n/**\n * Options for {@link buildFileIndex}.\n */\nexport interface BuildIndexOptions {\n /**\n * Build an additional lowercase `byRelPathLower` map so {@link resolveLink}\n * can fall back to case-insensitive matching when the exact-case path\n * lookup fails. Useful when the operator's wiki-link convention uses\n * different casing than the on-disk layout (a frequent situation when\n * content is migrated from one vault into another with renamed roots,\n * e.g. `[[Projects/Home/foo]]` vs `data/projects/home/foo.md`).\n *\n * Default: false. Bare-name lookup is unaffected — Obsidian historically\n * treats bare names case-sensitively, and we keep that.\n */\n caseInsensitive?: boolean;\n /**\n * Extra file extensions (besides `.md`) to include in the index. Each\n * extension must include the leading dot, e.g. `[\".hwp\", \".docx\", \".pdf\"]`.\n *\n * `.md` files are always indexed with the extension stripped from their\n * key — `[[Foo]]` matches `Foo.md`. Files with one of the additional\n * extensions are indexed with the extension *kept*, so they only match\n * when the operator writes the full filename — `[[Foo.hwp]]` matches\n * `Foo.hwp`. This avoids surprise collisions where `[[Foo]]` would\n * suddenly match a non-markdown file.\n *\n * Default: `[]` (only `.md` is indexed; preserves v1 behavior).\n *\n * Note: only `.md` files are scanned for wiki links by\n * {@link import(\"./checker.js\").checkDirectory} and rewritten by\n * {@link import(\"./rewrite.js\").rewriteDirectory}. Additional extensions\n * affect *resolution targets* (what a wiki link can point at), not\n * *scan sources* (what a wiki link can appear in).\n */\n additionalExtensions?: readonly string[];\n}\n\n/**\n * Walk `rootDir` recursively and build a {@link FileIndex} of every `.md`\n * file (plus any `additionalExtensions` requested).\n *\n * Hidden directories (`.foo`) are skipped. `_foo` directories ARE indexed —\n * Obsidian wiki links can target any markdown file regardless of underscore\n * prefix, so we mirror that. A missing root returns an empty index.\n */\nexport async function buildFileIndex(\n rootDir: string,\n options: BuildIndexOptions = {},\n): Promise<FileIndex> {\n const byBasename = new Map<string, string[]>();\n const byRelPath = new Map<string, string>();\n const additional = new Set(options.additionalExtensions ?? []);\n await walk(rootDir, rootDir, byBasename, byRelPath, additional);\n if (options.caseInsensitive) {\n const byRelPathLower = new Map<string, string>();\n for (const [rel, abs] of byRelPath) {\n const lower = rel.toLowerCase();\n if (!byRelPathLower.has(lower)) byRelPathLower.set(lower, abs);\n }\n return { byBasename, byRelPath, byRelPathLower, rootDir };\n }\n return { byBasename, byRelPath, rootDir };\n}\n\nasync function walk(\n rootDir: string,\n dir: string,\n byBasename: Map<string, string[]>,\n byRelPath: Map<string, string>,\n additionalExts: ReadonlySet<string>,\n): Promise<void> {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw e;\n }\n for (const dirent of entries) {\n const name = dirent.name;\n if (dirent.isDirectory()) {\n if (name.startsWith(\".\")) continue;\n await walk(rootDir, join(dir, name), byBasename, byRelPath, additionalExts);\n continue;\n }\n if (!dirent.isFile()) continue;\n const ext = extname(name);\n const isMd = ext === \".md\";\n if (!isMd && !additionalExts.has(ext)) continue;\n const path = join(dir, name);\n try {\n const info = await stat(path);\n if (!info.isFile()) continue;\n } catch {\n continue;\n }\n // `.md` strips its extension from keys; non-md files keep it so a\n // bare `[[Foo]]` cannot accidentally resolve to `Foo.hwp`.\n const key = isMd ? basename(name, \".md\") : name;\n const list = byBasename.get(key);\n if (list) {\n list.push(path);\n } else {\n byBasename.set(key, [path]);\n }\n const relRaw = relative(rootDir, path).split(/[\\\\/]/).join(\"/\");\n const rel = isMd ? relRaw.replace(/\\.md$/, \"\") : relRaw;\n byRelPath.set(rel, path);\n }\n}\n\n/**\n * Resolution outcome for a single wiki link.\n *\n * - `unique`: one and only one file matched.\n * - `not-found`: no file matched.\n * - `ambiguous`: multiple files share the basename (only possible for\n * bare-name links; path-aware links always resolve uniquely or fail).\n */\nexport type ResolveOutcome =\n | { kind: \"unique\"; path: string }\n | { kind: \"not-found\" }\n | { kind: \"ambiguous\"; candidates: readonly string[] };\n\n/**\n * Optional hints that turn on path-aware resolution.\n *\n * - `sourcePath` — absolute path of the file the link was found in.\n * Required to resolve `../foo`-style relative links.\n *\n * When neither hint is set, behavior collapses to bare-name lookup\n * (basename only), matching the original v1 semantics.\n */\nexport interface ResolveOpts {\n sourcePath?: string;\n}\n\n/**\n * Look up a wiki link in the index. Three cases:\n *\n * 1. **Bare name** (`[[Foo]]`) — basename lookup only. Returns `unique`\n * if exactly one `Foo.md` exists, `ambiguous` if multiple, `not-found`\n * otherwise.\n * 2. **Root-relative path** (`[[Projects/Foo]]`) — exact rel-path lookup\n * against the index. Always `unique` or `not-found`.\n * 3. **Source-relative path** (`[[../Foo]]`, `[[./Foo]]`) — resolved\n * against `dirname(sourcePath)` first, then looked up by rel-path.\n * Requires `opts.sourcePath`; without it, returns `not-found`.\n *\n * Trailing `.md` in the link name is stripped before matching.\n */\nexport function resolveLink(\n name: string,\n index: FileIndex,\n opts: ResolveOpts = {},\n): ResolveOutcome {\n // Strip any explicit .md extension the operator may have typed.\n const stripped = name.replace(/\\.md$/u, \"\");\n\n if (!stripped.includes(\"/\") && !stripped.includes(\"\\\\\")) {\n // Case 1: bare name → basename lookup.\n const list = index.byBasename.get(stripped);\n if (!list || list.length === 0) return { kind: \"not-found\" };\n if (list.length === 1) return { kind: \"unique\", path: list[0]! };\n return { kind: \"ambiguous\", candidates: list };\n }\n\n const normalized = stripped.replace(/\\\\/g, \"/\");\n\n if (normalized.startsWith(\"../\") || normalized.startsWith(\"./\")) {\n // Case 3: source-relative path. Need a base to resolve from.\n if (!opts.sourcePath) return { kind: \"not-found\" };\n const baseDir = dirname(opts.sourcePath);\n const absolute = pathResolve(baseDir, normalized);\n const rel = relative(index.rootDir, absolute)\n .split(/[\\\\/]/)\n .join(\"/\");\n // Guard: if the relative path climbs above rootDir, the link cannot\n // resolve within this index.\n if (rel.startsWith(\"..\") || isAbsolute(rel)) {\n return { kind: \"not-found\" };\n }\n return lookupRelPath(rel, index);\n }\n\n // Case 2: root-relative path.\n return lookupRelPath(normalized, index);\n}\n\n/**\n * Look up a rel-path with optional case-insensitive fallback.\n */\nfunction lookupRelPath(rel: string, index: FileIndex): ResolveOutcome {\n const exact = index.byRelPath.get(rel);\n if (exact) return { kind: \"unique\", path: exact };\n if (index.byRelPathLower) {\n const fallback = index.byRelPathLower.get(rel.toLowerCase());\n if (fallback) return { kind: \"unique\", path: fallback };\n }\n return { kind: \"not-found\" };\n}\n\n/**\n * Reduce an absolute path to one relative to `rootDir`, using forward\n * slashes. Useful for reporting.\n */\nexport function toRel(path: string, rootDir: string): string {\n return relative(rootDir, path).split(/[\\\\/]/).join(\"/\");\n}\n","import { readFile } from \"node:fs/promises\";\nimport { extname } from \"node:path\";\nimport { parseFrontmatter } from \"@vortex-os/core\";\nimport { extractWikiLinks } from \"./extract.js\";\nimport { buildFileIndex, resolveLink } from \"./resolve.js\";\nimport type { BuildIndexOptions } from \"./resolve.js\";\nimport type { BrokenLink, LinkCheckResult } from \"./types.js\";\n\n/**\n * Options for {@link checkDirectory}.\n */\nexport interface CheckDirectoryOptions extends BuildIndexOptions {}\n\n/**\n * Scan every `.md` file under `rootDir`, extract wiki links, and\n * report which ones cannot be resolved (or resolve to multiple files).\n *\n * This is read-only — it does not modify any file. The function returns\n * a structured result so hosts can decide whether to log, fail a build,\n * propose rewrites, etc.\n *\n * Pass `caseInsensitive: true` when wiki-link casing may differ from\n * the on-disk path (e.g. content migrated from a vault with different\n * directory naming conventions).\n */\nexport async function checkDirectory(\n rootDir: string,\n options: CheckDirectoryOptions = {},\n): Promise<LinkCheckResult> {\n const index = await buildFileIndex(rootDir, options);\n const broken: BrokenLink[] = [];\n const ambiguous: BrokenLink[] = [];\n\n let filesScanned = 0;\n let totalLinks = 0;\n let resolved = 0;\n\n for (const paths of index.byBasename.values()) {\n for (const path of paths) {\n // Only markdown files carry wiki-link text. Non-md entries in the\n // index (when `additionalExtensions` is set) are resolution targets,\n // not scan sources.\n if (extname(path) !== \".md\") continue;\n filesScanned++;\n const raw = await readFile(path, \"utf8\");\n const { body } = parseFrontmatter(raw);\n const links = extractWikiLinks(body);\n totalLinks += links.length;\n for (const link of links) {\n const outcome = resolveLink(link.name, index, { sourcePath: path });\n if (outcome.kind === \"unique\") {\n resolved++;\n } else if (outcome.kind === \"not-found\") {\n broken.push({ sourcePath: path, link, reason: \"not-found\" });\n } else {\n ambiguous.push({\n sourcePath: path,\n link,\n reason: \"ambiguous\",\n candidates: outcome.candidates,\n });\n }\n }\n }\n }\n\n return { filesScanned, totalLinks, resolved, broken, ambiguous };\n}\n\n/**\n * Group broken links by target name and return counts in descending order.\n * Useful for quickly identifying the most-cited missing pages.\n */\nexport function topBrokenTargets(\n broken: readonly BrokenLink[],\n limit = 20,\n): readonly { readonly name: string; readonly count: number }[] {\n const counts = new Map<string, number>();\n for (const b of broken) {\n counts.set(b.link.name, (counts.get(b.link.name) ?? 0) + 1);\n }\n return [...counts.entries()]\n .map(([name, count]) => ({ name, count }))\n .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name))\n .slice(0, limit);\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport { extname } from \"node:path\";\nimport { extractWikiLinks } from \"./extract.js\";\nimport { buildFileIndex } from \"./resolve.js\";\n\n/**\n * Map of wiki-link names to replace.\n *\n * Both keys and values are the `name` portion of a wiki link — what\n * appears between `[[` and the optional `#anchor` / `|alias`. Anchors\n * and aliases on the original link are preserved automatically.\n *\n * Examples:\n * { \"API-Tokens\": \"secrets/api-tokens\" }\n * [[API-Tokens]] → [[secrets/api-tokens]]\n * [[API-Tokens|토큰]] → [[secrets/api-tokens|토큰]]\n * [[API-Tokens#A|토큰]] → [[secrets/api-tokens#A|토큰]]\n *\n * Use the exact name string the operator wrote — no normalization is\n * applied. If the same broken target appears with different spellings\n * (e.g. case differences), provide one entry per spelling.\n */\nexport type RedirectionMap = ReadonlyMap<string, string>;\n\n/**\n * Options for {@link rewriteDirectory}.\n */\nexport interface RewriteOptions {\n /**\n * The redirection map driving the rewrite. Links whose name is not\n * a key in this map are left untouched.\n */\n redirections: RedirectionMap;\n /**\n * When true, do not write any files. The result still describes the\n * rewrites that would happen — useful for showing the operator what\n * a redirection map will do before it does it.\n */\n dryRun?: boolean;\n}\n\n/**\n * Per-file detail of a rewrite operation.\n */\nexport interface FileRewrite {\n readonly sourcePath: string;\n readonly rewrites: readonly { readonly from: string; readonly to: string }[];\n}\n\n/**\n * Aggregate result of {@link rewriteDirectory}.\n */\nexport interface RewriteResult {\n readonly filesScanned: number;\n /** Files whose body was changed (or would be changed under dry-run). */\n readonly filesChanged: number;\n /** Total number of link replacements (may exceed `filesChanged`). */\n readonly rewritesApplied: number;\n /** Links matching a redirection key but ultimately not replaced — currently always 0; reserved for future skip reasons. */\n readonly skipped: number;\n readonly details: readonly FileRewrite[];\n readonly dryRun: boolean;\n}\n\n/**\n * Walk every `.md` file under `rootDir`, replace wiki links whose name\n * is a key in `redirections`, and write the changed files back to disk\n * (or describe what would change when `dryRun: true`).\n *\n * Only the link `name` is replaced. Anchors (`#Section`) and aliases\n * (`|display`) carry over verbatim onto the replacement link. The\n * surrounding markdown body is untouched.\n *\n * Rewriting is deterministic and order-independent — within a file,\n * every occurrence of every mapped key is replaced exactly once per\n * occurrence, with no chaining (the replacement is not re-scanned for\n * further matches).\n */\nexport async function rewriteDirectory(\n rootDir: string,\n opts: RewriteOptions,\n): Promise<RewriteResult> {\n const { redirections, dryRun = false } = opts;\n const index = await buildFileIndex(rootDir);\n\n let filesScanned = 0;\n let filesChanged = 0;\n let rewritesApplied = 0;\n const details: FileRewrite[] = [];\n\n for (const paths of index.byBasename.values()) {\n for (const path of paths) {\n // Only markdown files have rewritable wiki-link bodies. Non-md\n // entries in the index (when callers asked for `additionalExtensions`\n // upstream) are resolution targets, not rewrite sources.\n if (extname(path) !== \".md\") continue;\n filesScanned++;\n const raw = await readFile(path, \"utf8\");\n const { newBody, fileRewrites } = rewriteBody(raw, redirections);\n if (fileRewrites.length === 0) continue;\n filesChanged++;\n rewritesApplied += fileRewrites.length;\n details.push({ sourcePath: path, rewrites: fileRewrites });\n if (!dryRun) {\n await writeFile(path, newBody, \"utf8\");\n }\n }\n }\n\n return {\n filesScanned,\n filesChanged,\n rewritesApplied,\n skipped: 0,\n details,\n dryRun,\n };\n}\n\n/**\n * Pure transformation: take a markdown body, return the body with all\n * `[[…]]` links whose name appears in `redirections` rewritten. Exported\n * for testing and for callers that need to rewrite an in-memory string.\n *\n * The transformation does not touch markdown outside `[[…]]` patterns.\n */\nexport function rewriteBody(\n body: string,\n redirections: RedirectionMap,\n): { newBody: string; fileRewrites: { from: string; to: string }[] } {\n const fileRewrites: { from: string; to: string }[] = [];\n // Reconstruct each match piece-by-piece so we keep the same anchor/\n // alias the operator wrote.\n const links = extractWikiLinks(body);\n if (links.length === 0) return { newBody: body, fileRewrites };\n\n let out = \"\";\n let cursor = 0;\n\n // We need positional info: walk the body with the same regex used in\n // extract.ts so we know where each match starts and ends.\n const pattern = /\\[\\[([^\\]|#\\n]+?)(?:#([^\\]|\\n]+?))?(?:\\|([^\\]\\n]+?))?\\]\\]/g;\n let m: RegExpExecArray | null;\n while ((m = pattern.exec(body)) !== null) {\n const [whole, rawName, rawAnchor, rawAlias] = m;\n const name = (rawName ?? \"\").trim();\n const target = redirections.get(name);\n if (!target) continue;\n\n // Found a replacement. Emit everything up to this match unchanged…\n out += body.slice(cursor, m.index);\n // …then build the replacement preserving anchor and alias.\n let replacement = `[[${target}`;\n if (rawAnchor) replacement += `#${rawAnchor}`;\n if (rawAlias) replacement += `|${rawAlias}`;\n replacement += \"]]\";\n out += replacement;\n cursor = m.index + whole.length;\n fileRewrites.push({ from: whole, to: replacement });\n }\n\n // Tail: everything after the last replacement (or the whole body if\n // nothing matched).\n out += body.slice(cursor);\n return { newBody: out, fileRewrites };\n}\n","export { createRitualRegistry } from \"./registry.js\";\nexport { sessionStartCommand } from \"./commands/session-start.js\";\nexport type { SessionStartReport } from \"./commands/session-start.js\";\nexport { reindexCommand } from \"./commands/reindex.js\";\nexport type { ReindexResult } from \"./commands/reindex.js\";\nexport { decisionCommand } from \"./commands/decision.js\";\nexport type { NewDecisionResult } from \"./commands/decision.js\";\nexport { tilCommand } from \"./commands/til.js\";\nexport type { TilAppendResult } from \"./commands/til.js\";\nexport { vortexCommand } from \"./commands/vortex.js\";\nexport type {\n VortexResult,\n VortexInitResult,\n VortexHelpResult,\n VortexPlannedResult,\n} from \"./commands/vortex.js\";\n","import { writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport { DecisionStore, renderTemplate } from \"@vortex-os/decision-log\";\nimport type { Command, CommandInput } from \"@vortex-os/slash-commands\";\n\nexport interface NewDecisionResult {\n readonly path: string;\n readonly date: string;\n readonly slug: string;\n}\n\n/**\n * `/decision <slug> <title...>` — Create a new Decision Log entry from\n * the canonical template at `data/decision-log/<today>-<slug>.md`.\n *\n * `slug` is required and used in the filename. The remaining tokens form\n * the entry title (the H1 in the rendered body). The command refuses to\n * overwrite an existing file — it errors out so the caller can decide.\n */\nexport const decisionCommand: Command<NewDecisionResult> = {\n name: \"decision\",\n description: \"Create a new Decision Log entry from the template.\",\n args: [\n { name: \"slug\", description: \"Kebab-style identifier used in the filename.\", required: true },\n { name: \"title\", description: \"One-line decision title (rest of the input).\", required: true },\n ],\n handler: async (input: CommandInput): Promise<NewDecisionResult> => {\n const slug = input.args.slug;\n if (!slug) {\n throw new Error(\"`/decision` requires a slug argument.\");\n }\n // The runner already populated args.slug from the first token. The\n // title is `rest` minus that first token; recover it by taking the\n // raw input and stripping the leading \"decision <slug>\".\n const title = extractTitle(input.rest, slug);\n if (!title) {\n throw new Error(\"`/decision` requires a title after the slug.\");\n }\n\n const date = todayIso();\n const dir = join(input.context.dataDir, \"decision-log\");\n const store = new DecisionStore(dir);\n const path = store.pathFor(date, slug);\n\n if (existsSync(path)) {\n throw new Error(`Refusing to overwrite existing entry: ${path}`);\n }\n\n const body = renderTemplate({ date, slug, title });\n await writeFile(path, body, \"utf8\");\n return { path, date, slug };\n },\n};\n\nfunction extractTitle(rest: string, slug: string): string {\n const trimmed = rest.trim();\n if (trimmed.startsWith(slug)) {\n return trimmed.slice(slug.length).trim();\n }\n return trimmed;\n}\n\nfunction todayIso(): string {\n const d = new Date();\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, \"0\");\n const day = String(d.getDate()).padStart(2, \"0\");\n return `${y}-${m}-${day}`;\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { renderIndex, scanDirectory } from \"@vortex-os/index-generator\";\nimport type { Command, CommandInput } from \"@vortex-os/slash-commands\";\n\ninterface ReindexTarget {\n readonly dir: string;\n readonly title: string;\n readonly description: string;\n readonly privacy: \"internal\" | \"personal\";\n readonly recursive: boolean;\n readonly skipPrefixes: readonly string[];\n readonly skipFilenames: readonly string[];\n}\n\nconst TARGETS: readonly ReindexTarget[] = [\n {\n dir: \"_memory\",\n title: \"Memory\",\n description:\n \"세션 간 공유되는 영속 메모리 항목들. MEMORY.md는 본 디렉토리의 원본 인덱스이며, 본 _INDEX.md는 사람·Obsidian 친화 양식의 파생물입니다.\",\n privacy: \"internal\",\n recursive: false,\n skipPrefixes: [],\n skipFilenames: [\"MEMORY.md\"],\n },\n {\n dir: \"til\",\n title: \"TIL\",\n description: \"날짜별 작업 기록. `YYYY/MM/YYYY-MM-DD-keyword.md` 구조.\",\n privacy: \"internal\",\n recursive: true,\n skipPrefixes: [],\n skipFilenames: [],\n },\n {\n dir: \"decision-log\",\n title: \"Decision Log\",\n description: \"개인 의사결정 기록 — 왜 그걸 골랐는지를 남깁니다.\",\n privacy: \"personal\",\n recursive: false,\n skipPrefixes: [\"_TEMPLATE\"],\n skipFilenames: [],\n },\n {\n dir: \"runbooks\",\n title: \"Runbooks\",\n description: \"장애 대응·정기 정비 절차. `last_tested`로 갱신 기한 추적.\",\n privacy: \"internal\",\n recursive: false,\n skipPrefixes: [],\n skipFilenames: [],\n },\n {\n dir: \"hubs\",\n title: \"Hubs\",\n description: \"주제별 진입점 — 관련 자료를 한 곳에서 묶는 인덱스 페이지 모음.\",\n privacy: \"internal\",\n recursive: false,\n skipPrefixes: [],\n skipFilenames: [],\n },\n {\n dir: \"projects\",\n title: \"Projects\",\n description:\n \"진행 중·완료 프로젝트 모음 (Work·Home). 본 _INDEX는 평탄 목록이며, 하위 프로젝트 폴더별 _INDEX가 더 유용할 수 있음 (다음 사이클 검토).\",\n privacy: \"internal\",\n recursive: true,\n skipPrefixes: [],\n skipFilenames: [],\n },\n {\n dir: \"reference\",\n title: \"Reference\",\n description:\n \"AI 규칙·기술 치트시트·장비·스킬 등 레퍼런스 자료 (AI-Rules·Games·Gear·Infra·Org·Skills·Tech).\",\n privacy: \"internal\",\n recursive: true,\n skipPrefixes: [],\n skipFilenames: [],\n },\n {\n dir: \"reports\",\n title: \"Reports\",\n description:\n \"정기 건강검진 리포트 (Service-Health·Homelab-Health). 시점 스냅샷 누적.\",\n privacy: \"internal\",\n recursive: true,\n skipPrefixes: [],\n skipFilenames: [],\n },\n {\n dir: \"inbox\",\n title: \"Inbox\",\n description:\n \"미분류 임시 메모·아이디어·백로그. 정식 분류 시 해당 카테고리로 이동.\",\n privacy: \"internal\",\n recursive: true,\n skipPrefixes: [],\n skipFilenames: [],\n },\n {\n dir: \"_templates\",\n title: \"Templates\",\n description: \"보고용·공유용 자료 템플릿 모음 (Sharing 등).\",\n privacy: \"internal\",\n recursive: true,\n skipPrefixes: [],\n skipFilenames: [],\n },\n];\n\nexport interface ReindexResult {\n readonly dir: string;\n readonly status: \"written\" | \"unchanged\" | \"missing\";\n readonly entries: number;\n readonly bytes: number;\n}\n\n/**\n * `/reindex [dir]` — Regenerate `_INDEX.md` for one or all known data\n * directories. When called with no argument, processes all targets;\n * when called with a directory name, processes only that target.\n *\n * Returns a list of results so the host can summarize. Unchanged\n * indexes are reported as `unchanged` (no write performed); missing\n * directories are reported as `missing` (no write attempted).\n */\nexport const reindexCommand: Command<readonly ReindexResult[]> = {\n name: \"reindex\",\n description:\n \"Regenerate _INDEX.md for one or all data directories (memory, til, decision-log).\",\n args: [\n {\n name: \"dir\",\n description: \"Optional directory name. Omit to reindex all targets.\",\n },\n ],\n handler: async (input: CommandInput): Promise<readonly ReindexResult[]> => {\n const requested = input.args.dir;\n const targets = requested\n ? TARGETS.filter((t) => t.dir === requested)\n : TARGETS;\n\n if (requested && targets.length === 0) {\n throw new Error(\n `Unknown reindex target: \"${requested}\". Known: ${TARGETS.map((t) => t.dir).join(\", \")}`,\n );\n }\n\n const results: ReindexResult[] = [];\n for (const t of targets) {\n const dir = join(input.context.dataDir, t.dir);\n if (!existsSync(dir)) {\n results.push({ dir: t.dir, status: \"missing\", entries: 0, bytes: 0 });\n continue;\n }\n\n const entries = await scanDirectory(dir, {\n recursive: t.recursive,\n skipPrefixes: t.skipPrefixes,\n skipFilenames: t.skipFilenames,\n });\n const body = renderIndex({\n title: t.title,\n description: t.description,\n entries,\n privacy: t.privacy,\n });\n\n const target = join(dir, \"_INDEX.md\");\n let existing;\n try {\n existing = await readFile(target, \"utf8\");\n } catch {\n existing = undefined;\n }\n if (existing === body) {\n results.push({\n dir: t.dir,\n status: \"unchanged\",\n entries: entries.length,\n bytes: body.length,\n });\n continue;\n }\n\n await writeFile(target, body, \"utf8\");\n results.push({\n dir: t.dir,\n status: \"written\",\n entries: entries.length,\n bytes: body.length,\n });\n }\n return results;\n },\n};\n","import { existsSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { Command, CommandInput } from \"@vortex-os/slash-commands\";\n\n/**\n * Output of {@link sessionStartCommand}'s handler. Pure data — the host\n * decides how to display it. Returning structured output rather than\n * printing keeps the command usable from non-CLI hosts (tests, web UIs).\n */\nexport interface SessionStartReport {\n readonly time: string;\n readonly repoRoot: string;\n readonly dataDir: string;\n readonly counts: Readonly<Record<string, number>>;\n readonly missing: readonly string[];\n}\n\nconst COUNTED_DIRS: readonly string[] = [\"_memory\", \"til\", \"decision-log\"];\n\n/**\n * `/session-start` — Emit a small report that anchors a new session.\n * No side effects: reads filesystem counts only.\n *\n * The host (e.g. Claude Code session loop) is expected to display the\n * report and decide what to do next. This command's job is to surface\n * the facts, not to take action.\n */\nexport const sessionStartCommand: Command<SessionStartReport> = {\n name: \"session-start\",\n description: \"Emit a start-of-session report (time + data directory counts).\",\n handler: async (input: CommandInput): Promise<SessionStartReport> => {\n const { dataDir, repoRoot } = input.context;\n const counts: Record<string, number> = {};\n const missing: string[] = [];\n\n for (const name of COUNTED_DIRS) {\n const dir = join(dataDir, name);\n if (!existsSync(dir)) {\n missing.push(name);\n counts[name] = 0;\n continue;\n }\n counts[name] = await countMarkdown(dir, name === \"til\");\n }\n\n return {\n time: new Date().toISOString(),\n repoRoot,\n dataDir,\n counts,\n missing,\n };\n },\n};\n\nasync function countMarkdown(dir: string, recursive: boolean): Promise<number> {\n let total = 0;\n const entries = await readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n if (e.isFile()) {\n if (!e.name.endsWith(\".md\")) continue;\n if (e.name === \"README.md\" || e.name === \"_INDEX.md\" || e.name === \"MEMORY.md\") {\n continue;\n }\n if (e.name.startsWith(\"_TEMPLATE\")) continue;\n total++;\n } else if (e.isDirectory() && recursive) {\n if (e.name.startsWith(\".\") || e.name.startsWith(\"_\")) continue;\n total += await countMarkdown(join(dir, e.name), recursive);\n }\n }\n return total;\n}\n","import type { Command, CommandInput } from \"@vortex-os/slash-commands\";\nimport { TilStore, appendSection } from \"@vortex-os/til\";\n\nexport interface TilAppendResult {\n readonly path: string;\n readonly date: string;\n readonly keyword: string;\n readonly sectionTitle: string;\n}\n\n/**\n * `/til <section-title>` — Append a `## <section-title>` section to today's\n * TIL entry. If no TIL exists for today, the command errors (entry creation\n * with frontmatter is left to the host so it can apply project-specific\n * conventions). The body of the new section is left empty for the caller\n * to fill in.\n *\n * This is a deliberately small command — the goal is to make \"add a quick\n * note to today's TIL\" a one-liner, not to replace a real editor.\n */\nexport const tilCommand: Command<TilAppendResult> = {\n name: \"til\",\n description: \"Append a section to today's TIL entry.\",\n args: [\n {\n name: \"section\",\n description: \"Title for the new `## ` section (rest of the input).\",\n required: true,\n },\n ],\n handler: async (input: CommandInput): Promise<TilAppendResult> => {\n const sectionTitle = input.rest.trim();\n if (!sectionTitle) {\n throw new Error(\"`/til` requires a section title.\");\n }\n\n const date = todayIso();\n const store = new TilStore(`${input.context.dataDir}/til`);\n const todayEntry = await store.get(date);\n if (!todayEntry) {\n throw new Error(\n `No TIL entry exists for ${date}. Create one first; this command only appends sections.`,\n );\n }\n\n await appendSection(todayEntry, sectionTitle, \"\");\n return {\n path: todayEntry.path,\n date: todayEntry.date,\n keyword: todayEntry.keyword,\n sectionTitle,\n };\n },\n};\n\nfunction todayIso(): string {\n const d = new Date();\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, \"0\");\n const day = String(d.getDate()).padStart(2, \"0\");\n return `${y}-${m}-${day}`;\n}\n","import { existsSync } from \"node:fs\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { Command, CommandInput } from \"@vortex-os/slash-commands\";\n\n/**\n * `/vortex <sub>` — Root command for VortEX instance operations.\n *\n * Subcommands:\n * init — first-time setup wizard (creates user profile memory, first TIL, first topic hub)\n * status — (planned) instance state report\n * import — (planned) bring an existing folder into data/imported/\n * doctor — (planned) diagnose common setup issues\n * help — list available subcommands\n *\n * Phase 8 ships `init` and `help` as active; the rest are stubs that\n * advertise their planned name so users can discover them.\n */\n\nconst PLANNED_SUBS = [\"status\", \"import\", \"doctor\"] as const;\ntype PlannedSub = (typeof PLANNED_SUBS)[number];\n\nexport interface VortexInitResult {\n readonly subcommand: \"init\";\n readonly status: \"completed\" | \"needs-input\" | \"already-initialized\";\n readonly created: readonly string[];\n readonly nextActions: readonly string[];\n readonly missingInputs?: readonly { name: string; prompt: string }[];\n}\n\nexport interface VortexPlannedResult {\n readonly subcommand: PlannedSub | \"unknown\";\n readonly status: \"not-implemented\";\n readonly message: string;\n}\n\nexport interface VortexHelpResult {\n readonly subcommand: \"help\";\n readonly status: \"ok\";\n readonly subcommands: readonly {\n readonly name: string;\n readonly description: string;\n readonly state: \"active\" | \"planned\";\n }[];\n}\n\nexport type VortexResult = VortexInitResult | VortexPlannedResult | VortexHelpResult;\n\nexport const vortexCommand: Command<VortexResult> = {\n name: \"vortex\",\n description:\n \"VortEX root command. Subcommands: init | status | import | doctor | help.\",\n args: [\n {\n name: \"sub\",\n description: \"Subcommand (init|status|import|doctor|help).\",\n required: false,\n },\n ],\n handler: async (input: CommandInput): Promise<VortexResult> => {\n const tokens = tokenize(input.rest);\n const sub = (tokens[0] ?? \"help\") as string;\n const restAfterSub = tokens.slice(1);\n\n if (sub === \"init\") return runInit(input, restAfterSub);\n if (sub === \"help\" || sub === \"\") return runHelp();\n if ((PLANNED_SUBS as readonly string[]).includes(sub)) {\n return {\n subcommand: sub as PlannedSub,\n status: \"not-implemented\",\n message:\n `\\`/vortex ${sub}\\` is reserved but not yet implemented. ` +\n `Planned in a future phase. Run \\`/vortex help\\` for available subcommands.`,\n };\n }\n return {\n subcommand: \"unknown\",\n status: \"not-implemented\",\n message: `Unknown subcommand \"${sub}\". Run \\`/vortex help\\` for the list.`,\n };\n },\n};\n\nfunction runHelp(): VortexHelpResult {\n return {\n subcommand: \"help\",\n status: \"ok\",\n subcommands: [\n {\n name: \"init\",\n description:\n \"First-time setup wizard. Creates user profile memory, first TIL, first topic hub.\",\n state: \"active\",\n },\n {\n name: \"status\",\n description:\n \"Show instance state (memory count, latest TIL, missing skeletons).\",\n state: \"planned\",\n },\n {\n name: \"import\",\n description:\n \"Bring an existing folder into data/imported/ for gradual sorting.\",\n state: \"planned\",\n },\n {\n name: \"doctor\",\n description:\n \"Diagnose common setup issues (missing modules, broken links).\",\n state: \"planned\",\n },\n { name: \"help\", description: \"Show this list.\", state: \"active\" },\n ],\n };\n}\n\ninterface InitArgs {\n name?: string;\n role?: string;\n task?: string;\n force?: boolean;\n}\n\nasync function runInit(\n input: CommandInput,\n tokens: readonly string[],\n): Promise<VortexInitResult> {\n const args = parseInitArgs(tokens);\n const { dataDir } = input.context;\n\n const requiredDirs = [\"_memory\", \"til\", \"decision-log\", \"hubs\", \"inbox\"];\n for (const d of requiredDirs) {\n const p = join(dataDir, d);\n if (!existsSync(p)) await mkdir(p, { recursive: true });\n }\n\n const profilePath = join(dataDir, \"_memory\", \"user_profile.md\");\n if (existsSync(profilePath) && !args.force) {\n return {\n subcommand: \"init\",\n status: \"already-initialized\",\n created: [],\n nextActions: [\n `VortEX instance is already initialized (${profilePath} exists).`,\n \"To re-run, pass `--force` (existing user_profile / first TIL / first hub will be overwritten).\",\n \"To check current state, try `/session-start`.\",\n ],\n };\n }\n\n const missing: { name: string; prompt: string }[] = [];\n if (!args.name) {\n missing.push({\n name: \"name\",\n prompt:\n 'What name or handle should VortEX use for you? (e.g. \"Alex\" or \"team-lead\")',\n });\n }\n if (!args.role) {\n missing.push({\n name: \"role\",\n prompt:\n 'What is your main role in one word? (e.g. \"engineer\", \"researcher\", \"writer\")',\n });\n }\n if (!args.task) {\n missing.push({\n name: \"task\",\n prompt:\n \"What is one thing you're working on right now? (one sentence — this becomes your first TIL seed)\",\n });\n }\n\n if (missing.length > 0) {\n return {\n subcommand: \"init\",\n status: \"needs-input\",\n created: [],\n missingInputs: missing,\n nextActions: [\n \"Ask the user the prompts in `missingInputs`, then re-run with the answers:\",\n ' /vortex init --name \"<name>\" --role \"<role>\" --task \"<task>\"',\n \"Optional: append `--force` to overwrite an already-initialized instance.\",\n ],\n };\n }\n\n const today = todayIso();\n const created: string[] = [];\n\n await writeFile(\n profilePath,\n renderUserProfile(args.name!, args.role!, args.task!, today),\n \"utf8\",\n );\n created.push(profilePath);\n\n const [year, month] = today.split(\"-\");\n const tilDir = join(dataDir, \"til\", year!, month!);\n await mkdir(tilDir, { recursive: true });\n const tilPath = join(tilDir, `${today}-vortex-init.md`);\n await writeFile(\n tilPath,\n renderFirstTil(args.name!, args.role!, args.task!, today),\n \"utf8\",\n );\n created.push(tilPath);\n\n const hubSlug = slugify(args.role!);\n const hubPath = join(dataDir, \"hubs\", `_HUB-${hubSlug}.md`);\n await writeFile(\n hubPath,\n renderFirstHub(args.role!, today),\n \"utf8\",\n );\n created.push(hubPath);\n\n return {\n subcommand: \"init\",\n status: \"completed\",\n created,\n nextActions: [\n `Done. Created ${created.length} files.`,\n \"Next 3 things you can try right now:\",\n \" /til <one-line update> — append a section to today's TIL\",\n \" /decision <slug> <title> — record a decision\",\n \" /session-start — daily start-of-session report\",\n `Open ${tilPath} to see your first TIL — it already names \"${args.task!}\".`,\n ],\n };\n}\n\nfunction parseInitArgs(tokens: readonly string[]): InitArgs {\n const args: InitArgs = {};\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i]!;\n if (t === \"--force\") {\n args.force = true;\n continue;\n }\n if (t === \"--name\" && i + 1 < tokens.length) {\n args.name = tokens[++i];\n continue;\n }\n if (t === \"--role\" && i + 1 < tokens.length) {\n args.role = tokens[++i];\n continue;\n }\n if (t === \"--task\" && i + 1 < tokens.length) {\n args.task = tokens[++i];\n continue;\n }\n }\n return args;\n}\n\n/** Quote-aware tokenizer: supports \"double\" and 'single' quotes. */\nfunction tokenize(s: string): string[] {\n const out: string[] = [];\n let i = 0;\n while (i < s.length) {\n while (i < s.length && /\\s/.test(s[i]!)) i++;\n if (i >= s.length) break;\n const ch = s[i]!;\n if (ch === '\"' || ch === \"'\") {\n const quote = ch;\n i++;\n let buf = \"\";\n while (i < s.length && s[i] !== quote) {\n buf += s[i++];\n }\n if (i < s.length) i++;\n out.push(buf);\n } else {\n let buf = \"\";\n while (i < s.length && !/\\s/.test(s[i]!)) {\n buf += s[i++];\n }\n out.push(buf);\n }\n }\n return out;\n}\n\nfunction renderUserProfile(\n name: string,\n role: string,\n task: string,\n date: string,\n): string {\n return `---\nname: user-profile\ndescription: Operator profile captured by /vortex init.\ntype: user\ncreated: ${date}\nupdated: ${date}\n---\n\n# User Profile\n\n- **Name/handle**: ${name}\n- **Role**: ${role}\n- **Initial focus**: ${task}\n\nThis memory was created by \\`/vortex init\\` on ${date}. Edit freely as your role evolves.\n\nLinked: [[_HUB-${slugify(role)}]] — primary topic hub.\n`;\n}\n\nfunction renderFirstTil(\n name: string,\n role: string,\n task: string,\n date: string,\n): string {\n return `---\ntype: til\nstatus: active\ncreated: ${date}\nupdated: ${date}\ntags: [til, onboarding]\n---\n\n# ${date} — VortEX 시작\n\n> First TIL, created by \\`/vortex init\\`. ${name} (${role}). Today's focus: ${task}\n\n## What I'm working on\n\n${task}\n\n## Notes\n\n(append more with \\`/til <section-title>\\`)\n\n## Next\n\n- [ ] Try \\`/decision <slug> <title>\\` for your first decision record\n- [ ] Add a memory by editing \\`data/_memory/user_profile.md\\` or creating new ones\n- [ ] Run \\`/session-start\\` tomorrow to see your accumulated state\n`;\n}\n\nfunction renderFirstHub(role: string, date: string): string {\n return `---\ntype: hub\nstatus: active\nprivacy: internal\ncreated: ${date}\nupdated: ${date}\ntags: [hub, ${slugify(role)}]\n---\n\n# ${role} Hub\n\n> Topic hub for everything related to ${role}. Auto-created by \\`/vortex init\\`. Edit freely.\n\n## Active TILs\n\n- (link your ${role}-related TILs here as you accumulate them)\n\n## Decisions\n\n- (link Decision Log entries here)\n\n## Memories\n\n- (link \\`_memory/*.md\\` entries here)\n\n## External references\n\n- (links, dashboards, repos, etc.)\n`;\n}\n\nfunction slugify(s: string): string {\n return s\n .toLowerCase()\n .replace(/[^a-z0-9가-힣]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\nfunction todayIso(): string {\n const d = new Date();\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, \"0\");\n const day = String(d.getDate()).padStart(2, \"0\");\n return `${y}-${m}-${day}`;\n}\n","import { CommandRegistry } from \"@vortex-os/slash-commands\";\nimport { decisionCommand } from \"./commands/decision.js\";\nimport { reindexCommand } from \"./commands/reindex.js\";\nimport { sessionStartCommand } from \"./commands/session-start.js\";\nimport { tilCommand } from \"./commands/til.js\";\nimport { vortexCommand } from \"./commands/vortex.js\";\n\n/**\n * Build a {@link CommandRegistry} with all ritual commands registered.\n *\n * Hosts that want a subset can register the individual exports instead.\n * This factory exists for the common case — \"give me everything.\"\n */\nexport function createRitualRegistry(): CommandRegistry {\n const registry = new CommandRegistry();\n registry.register(sessionStartCommand);\n registry.register(reindexCommand);\n registry.register(decisionCommand);\n registry.register(tilCommand);\n registry.register(vortexCommand);\n return registry;\n}\n"],"mappings":";;;;;;;AAAA;;;;;;;;;;;;;ACOO,IAAM,UAAU;EACrB,QAAQ;EACR,UAAU;EACV,UAAU;;;;ACVZ,SAAS,SAAS,WAAW,aAAa,qBAAqB;AAG/D,IAAM,QAAQ;AACd,IAAM,MAAM;AAUN,SAAU,iBACd,QAAc;AAEd,QAAM,UAAU,OAAO,WAAW,GAAG,IAAI,OAAO,MAAM,CAAC,IAAI;AAC3D,QAAM,QAAQ,QAAQ,MAAM,KAAK;AACjC,MAAI,CAAC,OAAO;AACV,WAAO;MACL,aAAa,CAAA;MACb,MAAM;;EAEV;AACA,QAAM,OAAO,MAAM,CAAC,KAAK;AACzB,QAAM,OAAO,QAAQ,MAAM,MAAM,CAAC,EAAE,MAAM;AAC1C,MAAI;AACJ,MAAI;AACF,aAAU,UAAU,IAAI,KAAK,CAAA;EAC/B,QAAQ;AAKN,aAAS,CAAA;EACX;AACA,SAAO,EAAE,aAAa,QAAQ,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ile","b","dist_exports","readdir","readFile","join","readdir","basename","extname","join","dist_exports","readdir","readFile","basename","extname","join","b","readdir","join","readFile","basename","extname","dist_exports","readdir","readFile","basename","extname","join","b","readdir","join","readFile","basename","extname","dist_exports","_getDefaults","_defaults","changeDefaults","newDefaults","noopTest","edit","regex","opt","source","obj","name","val","valSource","other","supportsLookbehind","bull","indent","newline","blockCode","fences","hr","heading","bullet","lheadingCore","lheading","lheadingGfm","_paragraph","blockText","_blockLabel","def","list","_tag","_comment","html","paragraph","blockquote","blockNormal","gfmTable","blockGfm","blockPedantic","escape","inlineCode","br","inlineText","_punctuation","_punctuationOrSpace","_notPunctuationOrSpace","punctuation","_punctuationGfmStrongEm","_punctuationOrSpaceGfmStrongEm","_notPunctuationOrSpaceGfmStrongEm","blockSkip","emStrongLDelimCore","emStrongLDelim","emStrongLDelimGfm","emStrongRDelimAstCore","emStrongRDelimAst","emStrongRDelimAstGfm","emStrongRDelimUnd","anyPunctuation","autolink","_inlineComment","tag","_inlineLabel","link","reflink","nolink","reflinkSearch","_caseInsensitiveProtocol","inlineNormal","inlinePedantic","inlineGfm","inlineBreaks","block","inline","escapeReplacements","getEscapeReplacement","ch","encode","cleanUrl","href","splitCells","tableRow","count","row","match","offset","str","escaped","curr","cells","i","rtrim","c","invert","l","suffLen","currChar","findClosingBracket","b","level","outputLink","cap","raw","lexer","rules","title","text","token","indentCodeCompensation","matchIndentToCode","indentToCode","node","matchIndentInNode","indentInNode","_Tokenizer","options","src","trimmed","lines","tokens","inBlockquote","currentLines","currentRaw","currentText","top","lastToken","oldToken","newText","newToken","isordered","itemRegex","endsWithBlankLine","endEarly","itemContents","line","t","nextLine","blankLine","nextBulletRegex","hrRegex","fencesBeginRegex","headingBeginRegex","htmlBeginRegex","rawLine","nextLineWithoutTabs","istask","ischecked","lastItem","spacers","hasMultipleLineBreaks","headers","aligns","rows","item","align","cell","trimmedUrl","rtrimSlash","lastParenIndex","linkLen","links","linkString","maskedSrc","prevChar","lLength","rDelim","rLength","delimTotal","midDelimTotal","endReg","lastCharLength","hasNonSpaceChars","hasSpaceCharsOnBothEnds","prevCapZero","_Lexer","__Lexer","next","lastParagraphClipped","extTokenizer","cutSrc","startIndex","tempSrc","tempStart","getStartIndex","errMsg","keepPrevChar","_Renderer","lang","langString","code","depth","ordered","start","body","j","type","startAttr","itemBody","checkbox","checked","header","k","content","cleanHref","out","_TextRenderer","_Parser","__Parser","anyToken","genericToken","ret","textToken","renderer","_Hooks","markdown","Marked","args","callback","values","tableToken","listToken","childTokens","extensions","pack","opts","ext","prevRenderer","extLevel","prop","rendererProp","rendererFunc","tokenizer","tokenizerProp","tokenizerFunc","prevTokenizer","hooks","hooksProp","hooksFunc","prevHook","arg","walkTokens","packWalktokens","blockType","origOpt","throwError","processedSrc","processedTokens","e","silent","async","msg","markedInstance","marked","setOptions","use","parseInline","parser","_Parser","lexer","_Lexer","dist_exports","readdir","readFile","stat","join","join","b","readdir","stat","readFile","readFile","writeFile","dist_exports","readdir","readFile","stat","join","FILENAME_PATTERN","readdir","join","stat","readFile","b","dist_exports","readdir","readFile","stat","basename","extname","join","b","readdir","join","extname","basename","stat","readFile","m","v","d","y","m","readdir","stat","extname","join","walk","dist_exports","readdir","readFile","stat","extname","join","RESERVED_FILES","readdir","extname","join","stat","readFile","b","dist_exports","readdir","stat","basename","extname","join","relative","walk","readFile","extname","extname","readFile","b","readFile","writeFile","extname","extname","readFile","writeFile","m","dist_exports","writeFile","join","extractTitle","join","writeFile","d","y","m","existsSync","readFile","writeFile","join","join","existsSync","readFile","writeFile","existsSync","readdir","join","todayIso","d","y","m","existsSync","mkdir","writeFile","join","d","today","todayIso","y","m"]}
|