@ubercode/channelvault 0.3.0-rc.2 → 0.3.0-rc.4
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/CHANGELOG.md +52 -0
- package/README.md +66 -14
- package/dist/cli.js +1508 -773
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +46 -4
- package/dist/index.js.map +1 -1
- package/docs/roadmap.md +2 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/xml/index.ts","../src/explode/index.ts","../src/json.ts","../src/client/index.ts","../src/secrets/detect.ts","../src/secrets/index.ts","../src/client/validate.ts"],"sourcesContent":["/**\n * Shared contracts for channelvault.\n *\n * The whole tool is organized around a single in-memory representation called\n * the **canonical config**: a plain JSON object tree that mirrors Mirth's\n * `serverConfiguration` document. Two adapters produce/consume it:\n *\n * - XML adapter (src/xml): backup .xml <-> canonical (dev / offline path)\n * - Mirth client (src/client): live server <-> canonical (GET/PUT /server/configuration)\n *\n * The explode engine (src/explode) projects a canonical config onto a\n * git-friendly directory tree and reverses it, with embedded JavaScript pulled\n * out into sidecar `.js` files.\n */\n\n/** A JSON value as produced by the XML adapter or the live API. */\nexport type Json = string | number | boolean | null | Json[] | { [k: string]: Json };\n\n/** A canonical config object (the `serverConfiguration` payload, unwrapped). */\nexport type CanonicalConfig = { [k: string]: Json };\n\n/**\n * Marker left in a `*.json` file in place of an extracted script/code leaf.\n *\n * During explode, a code-bearing string leaf (e.g. a transformer step's\n * `script`, or a code template's `code`) is written to a sidecar `.js` file and\n * the original string is replaced, in place, with `{ \"@file\": \"<relpath>\" }`.\n * During implode, any object whose only key is `@file` is replaced by the text\n * content of that file. The path is relative to the JSON file holding the marker.\n */\nexport interface FileRef {\n '@file': string;\n}\n\nexport function isFileRef(v: unknown): v is FileRef {\n return (\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n Object.keys(v).length === 1 &&\n typeof (v as Record<string, unknown>)['@file'] === 'string'\n );\n}\n\n/**\n * The set of leaf element keys whose string values are treated as JavaScript\n * and extracted to sidecar `.js` files. Detection is by key name plus a\n * non-trivial-content check (see explode engine).\n */\nexport const CODE_KEYS = ['script', 'code'] as const;\n\n/**\n * Channel-level script keys that live directly on a channel object (no nesting).\n * Extracted into `<channel>/scripts/<name>.js`.\n */\nexport const CHANNEL_SCRIPT_KEYS = [\n 'preprocessingScript',\n 'postprocessingScript',\n 'deployScript',\n 'undeployScript',\n] as const;\n\n// --- XML adapter contract -------------------------------------------------\n\nexport interface XmlAdapter {\n /** Parse a Mirth backup XML string into a canonical config. */\n parse(xml: string): CanonicalConfig;\n /** Serialize a canonical config back to Mirth backup XML. */\n build(config: CanonicalConfig): string;\n}\n\n// --- Explode engine contract ----------------------------------------------\n\nexport interface ExplodeOptions {\n /** Absolute path to the working tree root. */\n root: string;\n}\n\nexport interface ExplodeEngine {\n /** Write a canonical config out as a directory tree under `root`. */\n explode(config: CanonicalConfig, opts: ExplodeOptions): Promise<void>;\n /** Read a directory tree under `root` back into a canonical config. */\n implode(opts: ExplodeOptions): Promise<CanonicalConfig>;\n}\n\n// --- Mirth client contract ------------------------------------------------\n\nexport interface ClientConfig {\n host: string;\n port: number;\n username: string;\n password: string;\n /** default true */\n https?: boolean;\n /** default false; set true for self-signed certs */\n disableTlsCheck?: boolean;\n /**\n * default false. Put the server's response body in error messages. A body\n * can echo the credentials that were sent; it is decoded and has credential\n * fields redacted, but the caller must still scrub known secret values.\n */\n includeResponseBodies?: boolean;\n}\n\nexport interface ApiError {\n status: number;\n statusText: string;\n message: string;\n body?: unknown;\n}\n\nexport interface ApiResponse<T> {\n data: T | null;\n error: ApiError | null;\n}\n\nexport interface MirthClient {\n login(): Promise<void>;\n logout(): Promise<void>;\n isAuthenticated(): boolean;\n /** GET /server/configuration -> canonical config (whole-server snapshot). */\n getServerConfiguration(): Promise<CanonicalConfig>;\n /** PUT /server/configuration <- canonical config. */\n putServerConfiguration(config: CanonicalConfig): Promise<void>;\n}\n","/**\n * XML canonical adapter for Mirth Connect \"Backup Config\" documents.\n *\n * Converts a Mirth `serverConfiguration` XML document to/from the canonical\n * config (a plain JSON object tree). `fast-xml-parser` v5 does the tokenizing in\n * its order-preserving mode; the conversion to the canonical object shape and\n * the serializer are ours, because fxp's object mode is lossy in ways a\n * round-trip test built on the same parser cannot see (it regroups interleaved\n * siblings, concatenates mixed-content text, and renames `__proto__`).\n *\n * Canonical shape (unchanged from the original fxp object-mode shape, so\n * existing exploded trees stay valid):\n *\n * - An element with no attributes and no child elements is its text, as a\n * STRING (`\"\"` when empty). Values are never coerced or trimmed: Mirth ids,\n * ports, `\"0B\"`, leading zeros and script-body whitespace all survive.\n * - Otherwise it is an object: child elements (and `#comment`) keyed by name in\n * first-appearance order, then `#text`, then attributes as `@_<name>`.\n * - Repeated names become arrays; `ALWAYS_ARRAY_TAGS` are arrays even when\n * single, so downstream code never special-cases \"one vs many\".\n * - Whitespace-only text beside child elements is indentation and is dropped.\n * - `#order` records the document order of an element's children ONLY when\n * the default order (keys in order, each array contiguous, `#text` last)\n * would differ from it — e.g. a transformer whose steps interleave\n * `JavaScriptStep` and `MapperStep`. It never appears for ordinary Mirth\n * output, and a stale hint (after hand-editing) degrades gracefully.\n *\n * Text fidelity: we own entity decode/encode. XML end-of-line handling (a\n * literal CRLF or CR in the document is a LF) and attribute-value\n * normalization (a literal tab/newline in an attribute is a space) are applied\n * as a conforming parser — Mirth's — would apply them, so the canonical value is\n * what Mirth actually reads. Characters those rules would destroy (CR, and tab\n * or newline inside attributes) are written back as character references.\n *\n * The acceptance criterion is a semantic, order-preserving round-trip:\n *\n * parse(build(parse(xml))) deep-equals parse(xml)\n *\n * plus document order of the rebuilt XML equal to the source's (see tests).\n */\nimport { XMLParser, XMLValidator } from 'fast-xml-parser';\nimport type { CanonicalConfig, Json, XmlAdapter } from '../types.js';\n\n/**\n * Well-known Mirth collection element tags that must ALWAYS be arrays, even\n * when a document contains only a single instance.\n */\nconst ALWAYS_ARRAY_TAGS: ReadonlySet<string> = new Set<string>([\n 'channel',\n 'connector',\n 'codeTemplate',\n 'codeTemplateLibrary',\n 'channelGroup',\n 'alert',\n 'rule',\n 'entry',\n 'string',\n // Fully-qualified JavaScript step / rule element names (live under <elements>).\n 'com.mirth.connect.plugins.javascriptstep.JavaScriptStep',\n 'com.mirth.connect.plugins.javascriptrule.JavaScriptRule',\n 'com.mirth.connect.plugins.mapper.MapperStep',\n 'com.mirth.connect.plugins.messagebuilder.MessageBuilderStep',\n]);\n\n/** The single top-level wrapper key of a Mirth backup document. */\nconst ROOT_KEY = 'serverConfiguration';\n\nconst TEXT_KEY = '#text';\nconst COMMENT_KEY = '#comment';\nconst CDATA_KEY = '#cdata';\n/** Document-order hint; `#` cannot start an XML name, so it cannot collide. */\nexport const ORDER_KEY = '#order';\nconst ATTR_PREFIX = '@_';\nconst ORDERED_ATTRS = ':@';\nconst INDENT = ' ';\n\n/** An fxp `preserveOrder` node: `{ <name>: children, ':@'?: attrs }`. */\ntype OrderedNode = Record<string, unknown>;\n\nfunction isWhitespaceOnly(s: string): boolean {\n return /^\\s*$/.test(s);\n}\n\n/** Named XML entities (the five predefined) -> their character. */\nconst NAMED_DECODE: Readonly<Record<string, string>> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n};\n\n/**\n * Decode XML entities in a single left-to-right pass: the five predefined named\n * entities plus decimal (` `) and hex (`
`) numeric character\n * references.\n *\n * A single non-overlapping scan is what makes `
` and `&#xd;`\n * distinguishable: `&` is consumed as one token (-> `&`) and its output is\n * not re-scanned, so the trailing `#xd;` stays literal.\n */\nfunction decodeEntities(value: string): string {\n if (!value.includes('&')) return value;\n return value.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g, (whole, body: string) => {\n if (body[0] !== '#') return NAMED_DECODE[body] ?? whole;\n const code =\n body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);\n if (!(code <= 0x10ffff)) {\n throw new Error(`XmlConfigAdapter.parse: invalid character reference ${whole}`);\n }\n return String.fromCodePoint(code);\n });\n}\n\nfunction charRef(ch: string): string {\n return `&#x${ch.charCodeAt(0).toString(16)};`;\n}\n\nconst ESCAPE: Readonly<Record<string, string>> = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\n\n/**\n * Encode text content. Escapes the same set fxp's builder did (so unchanged\n * values serialize byte-identically) and writes CR and the other C0 controls\n * except tab/LF as character references: a literal CR would be read back as LF.\n */\nfunction encodeText(value: string): string {\n // eslint-disable-next-line no-control-regex\n return value.replace(/[&<>\"'\\x00-\\x08\\x0b-\\x1f]/g, (ch) => ESCAPE[ch] ?? charRef(ch));\n}\n\n/** Encode an attribute value; tab and LF must be references there too. */\nfunction encodeAttr(value: string): string {\n // eslint-disable-next-line no-control-regex\n return value.replace(/[&<>\"'\\x00-\\x1f]/g, (ch) => ESCAPE[ch] ?? charRef(ch));\n}\n\n// --- parse -----------------------------------------------------------------\n\nfunction nodeName(node: OrderedNode): string {\n const name = Object.keys(node).find((k) => k !== ORDERED_ATTRS);\n if (name === undefined) throw new Error('XmlConfigAdapter.parse: empty node');\n return name;\n}\n\n/** Concatenated text of a `#comment` / `#cdata` node's children, undecoded. */\nfunction rawInnerText(children: unknown): string {\n return (children as OrderedNode[]).map((c) => String(c[TEXT_KEY] ?? '')).join('');\n}\n\n/** The child sequence the serializer emits for `obj` absent an `#order` hint. */\nfunction defaultOrder(obj: Record<string, Json>): string[] {\n const seq: string[] = [];\n for (const [key, value] of Object.entries(obj)) {\n if (key.startsWith(ATTR_PREFIX) || key === ORDER_KEY) continue;\n const count = Array.isArray(value) ? value.length : 1;\n for (let i = 0; i < count; i += 1) seq.push(key);\n }\n return seq;\n}\n\n/** Convert one element's ordered children + attributes to its canonical value. */\nfunction convertElement(children: OrderedNode[], attrs: Record<string, string> | undefined): Json {\n const hasElementChild = children.some((c) => {\n const n = nodeName(c);\n return n !== TEXT_KEY && n !== CDATA_KEY;\n });\n\n // Merge adjacent text/CDATA runs into text segments (CDATA is literal: no\n // entity decoding), and record the document order of what we keep.\n const groups = new Map<string, Json[]>();\n const order: string[] = [];\n const segments: string[] = [];\n let pending: string | null = null;\n const flushText = (): void => {\n if (pending === null) return;\n if (!hasElementChild || !isWhitespaceOnly(pending)) {\n segments.push(pending);\n order.push(TEXT_KEY);\n }\n pending = null;\n };\n\n for (const child of children) {\n const name = nodeName(child);\n if (name === TEXT_KEY) {\n pending = (pending ?? '') + decodeEntities(String(child[TEXT_KEY]));\n continue;\n }\n if (name === CDATA_KEY) {\n pending = (pending ?? '') + rawInnerText(child[CDATA_KEY]);\n continue;\n }\n flushText();\n // fxp renames this element to `#__proto__`; it cannot be an object key.\n if (name === '#__proto__') {\n throw new Error('XmlConfigAdapter.parse: unsupported element name <__proto__>');\n }\n const value =\n name === COMMENT_KEY\n ? rawInnerText(child[COMMENT_KEY])\n : convertElement(child[name] as OrderedNode[], child[ORDERED_ATTRS] as Record<string, string>);\n const group = groups.get(name);\n if (group) group.push(value);\n else groups.set(name, [value]);\n order.push(name);\n }\n flushText();\n\n const attrEntries = Object.entries(attrs ?? {});\n if (!hasElementChild && attrEntries.length === 0) {\n return segments.join('');\n }\n\n const obj: Record<string, Json> = {};\n for (const [name, values] of groups) {\n obj[name] = values.length > 1 || ALWAYS_ARRAY_TAGS.has(name) ? values : values[0]!;\n }\n if (segments.length === 1) obj[TEXT_KEY] = segments[0]!;\n else if (segments.length > 1) obj[TEXT_KEY] = segments;\n\n for (const [key, raw] of attrEntries) {\n if (key === `${ATTR_PREFIX}__proto__`) {\n throw new Error('XmlConfigAdapter.parse: unsupported attribute name __proto__');\n }\n // Attribute-value normalization: literal tab/LF (CRs are already LFs) read\n // as a space; character references were the way to keep them.\n obj[key] = decodeEntities(String(raw).replace(/[\\t\\n]/g, ' '));\n }\n\n const def = defaultOrder(obj);\n if (def.length !== order.length || def.some((k, i) => k !== order[i])) {\n obj[ORDER_KEY] = order;\n }\n return obj;\n}\n\nconst parser = new XMLParser({\n preserveOrder: true,\n ignoreAttributes: false,\n attributeNamePrefix: ATTR_PREFIX,\n parseTagValue: false,\n parseAttributeValue: false,\n trimValues: false,\n processEntities: false,\n commentPropName: COMMENT_KEY,\n cdataPropName: CDATA_KEY,\n});\n\n// --- build -----------------------------------------------------------------\n\n/**\n * The children of `obj` in emit order: honours an `#order` hint as far as it\n * matches the actual children, then appends anything it didn't mention in\n * default order. So adding, removing or renaming a child by hand never loses it.\n */\nfunction orderedChildren(obj: Record<string, Json>, where: string): Array<[string, Json]> {\n const queues = new Map<string, Json[]>();\n for (const [key, value] of Object.entries(obj)) {\n if (key.startsWith(ATTR_PREFIX) || key === ORDER_KEY) continue;\n queues.set(key, Array.isArray(value) ? [...value] : [value]);\n }\n const out: Array<[string, Json]> = [];\n const hint = obj[ORDER_KEY];\n if (hint !== undefined) {\n if (!Array.isArray(hint) || !hint.every((h) => typeof h === 'string')) {\n throw new Error(`XmlConfigAdapter.build: ${ORDER_KEY} under <${where}> must be an array of names`);\n }\n for (const name of hint as string[]) {\n const next = queues.get(name)?.shift();\n if (next !== undefined) out.push([name, next]);\n }\n }\n for (const [key, rest] of queues) {\n for (const value of rest) out.push([key, value]);\n }\n return out;\n}\n\nfunction scalar(value: Json): string {\n return value === null ? '' : String(value);\n}\n\nfunction serialize(name: string, value: Json, depth: number, pretty: boolean, out: string[]): void {\n const pad = pretty ? INDENT.repeat(depth) : '';\n const nl = pretty ? '\\n' : '';\n\n if (name === COMMENT_KEY) {\n const text = scalar(value);\n if (text.includes('--') || text.endsWith('-')) {\n throw new Error(`XmlConfigAdapter.build: comment text cannot contain \"--\": ${text}`);\n }\n out.push(`${pad}<!--${text}-->${nl}`);\n return;\n }\n if (name === TEXT_KEY) {\n out.push(encodeText(scalar(value)));\n return;\n }\n\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n out.push(`${pad}<${name}>${encodeText(scalar(value))}</${name}>${nl}`);\n return;\n }\n\n const attrs = Object.entries(value)\n .filter(([k]) => k.startsWith(ATTR_PREFIX))\n .map(([k, v]) => ` ${k.slice(ATTR_PREFIX.length)}=\"${encodeAttr(scalar(v))}\"`)\n .join('');\n const children = orderedChildren(value, name);\n const hasElementChild = children.some(([k]) => k !== TEXT_KEY);\n\n if (!hasElementChild) {\n const text = children.map(([, v]) => encodeText(scalar(v))).join('');\n out.push(`${pad}<${name}${attrs}>${text}</${name}>${nl}`);\n return;\n }\n\n // Mixed content can't be indented: the indentation would become part of its\n // text. Emit that element compactly.\n const mixed = children.some(([k]) => k === TEXT_KEY);\n const childPretty = pretty && !mixed;\n out.push(`${pad}<${name}${attrs}>${childPretty ? '\\n' : ''}`);\n for (const [key, child] of children) {\n serialize(key, child, depth + 1, childPretty, out);\n }\n out.push(`${childPretty ? pad : ''}</${name}>${nl}`);\n}\n\n// --- adapter ---------------------------------------------------------------\n\nexport class XmlConfigAdapter implements XmlAdapter {\n /** Parse a Mirth backup XML string into a canonical config. */\n parse(xml: string): CanonicalConfig {\n // XML end-of-line handling, which fxp does not apply.\n const normalized = xml.replace(/\\r\\n?/g, '\\n');\n if (/<!DOCTYPE/i.test(normalized.slice(0, normalized.search(/<[A-Za-z_]/)))) {\n // A DTD could declare entities we would not expand; Mirth never emits one.\n throw new Error('XmlConfigAdapter.parse: DOCTYPE declarations are not supported');\n }\n // fxp's parser accepts unclosed elements, so a truncated backup would read\n // as a smaller, \"valid\" configuration; validate the whole document first.\n const valid = XMLValidator.validate(normalized);\n if (valid !== true) {\n const { line, col, msg } = valid.err;\n throw new Error(`XmlConfigAdapter.parse: not well-formed XML at line ${line}, column ${col}: ${msg}`);\n }\n const nodes = parser.parse(normalized) as OrderedNode[];\n const root = nodes.find((n) => nodeName(n) === ROOT_KEY);\n if (root === undefined) {\n throw new Error(`XmlConfigAdapter.parse: expected a top-level <${ROOT_KEY}> element`);\n }\n const value = convertElement(root[ROOT_KEY] as OrderedNode[], root[ORDERED_ATTRS] as Record<string, string>);\n return (typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {}) as CanonicalConfig;\n }\n\n /** Serialize a canonical config back to Mirth backup XML. */\n build(config: CanonicalConfig): string {\n const out: string[] = [];\n serialize(ROOT_KEY, config, 0, true, out);\n return out.join('');\n }\n}\n","/**\n * Explode / implode engine.\n *\n * Projects a canonical config (the unwrapped Mirth `serverConfiguration`) onto a\n * git-friendly directory tree and reverses it losslessly. The exploded tree is a\n * verbatim *projection* of the config split across files using two marker types:\n *\n * - `{ \"@file\": \"<relpath>\" }` replaces an extracted code/script STRING leaf;\n * the string is written to a sidecar `.js` file (path relative to the JSON\n * file holding the marker).\n * - `{ \"@ref\": \"<relpath>\" }` replaces a whole sub-object split into its own\n * `.json` file (path relative to the JSON file holding the marker).\n *\n * Invariant: `implode(explode(config))` deep-equals `config`.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { existsSync } from 'node:fs';\nimport { lstat, mkdir, readFile, readdir, realpath, writeFile } from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport {\n CHANNEL_SCRIPT_KEYS,\n CODE_KEYS,\n isFileRef,\n type CanonicalConfig,\n type ExplodeEngine,\n type ExplodeOptions,\n type Json,\n} from '../types.js';\nimport { parseJson } from '../json.js';\n\n// --- shared helpers --------------------------------------------------------\n\n/** Coerce a \"container may be object or array depending on count\" value. */\nexport function asArray<T = Json>(x: unknown): T[] {\n return Array.isArray(x) ? (x as T[]) : x == null ? [] : [x as T];\n}\n\n/** Marker left in a `*.json` file in place of an extracted sub-object. */\ninterface RefMarker {\n '@ref': string;\n}\n\nexport function isRefMarker(v: unknown): v is RefMarker {\n return (\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n Object.keys(v).length === 1 &&\n typeof (v as Record<string, unknown>)['@ref'] === 'string'\n );\n}\n\nconst CODE_KEY_SET: ReadonlySet<string> = new Set([...CODE_KEYS, ...CHANNEL_SCRIPT_KEYS]);\n\n/** Map of channel-level script key -> friendly file base name. */\nconst CHANNEL_SCRIPT_FRIENDLY: Record<string, string> = {\n preprocessingScript: 'preprocessor',\n postprocessingScript: 'postprocessor',\n deployScript: 'deploy',\n undeployScript: 'undeploy',\n};\n\nfunction isPlainObject(v: unknown): v is Record<string, Json> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction deepClone<T>(v: T): T {\n return structuredClone(v);\n}\n\n/**\n * Slugify a name into a filesystem-safe segment.\n * Replaces `/ \\ : * ? \" < > |` and control chars, collapses whitespace to `-`,\n * trims leading/trailing separators. Never returns an empty string.\n */\nfunction slug(name: unknown): string {\n let s = typeof name === 'string' ? name : name == null ? '' : String(name);\n // Replace reserved / control characters with a space (later collapsed).\n s = s.replace(/[/\\\\:*?\"<>|]/g, ' ');\n // eslint-disable-next-line no-control-regex\n s = s.replace(/[\\x00-\\x1f\\x7f]/g, ' ');\n // Collapse any run of whitespace to a single dash.\n s = s.replace(/\\s+/g, '-');\n // Trim leading/trailing dashes/dots.\n s = s.replace(/^[-.]+|[-.]+$/g, '');\n if (s.length === 0) return 'unnamed';\n // Windows reserves these device names in every directory.\n return /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(s) ? `${s}-` : s;\n}\n\n/**\n * Deterministically resolve slug collisions within a namespace. Compared\n * case-insensitively: on Windows and macOS `Alpha` and `alpha` are the same\n * directory, and one would silently overwrite the other.\n */\nfunction uniqueSlug(base: string, used: Set<string>): string {\n let candidate = base;\n for (let n = 2; used.has(candidate.toLowerCase()); n += 1) candidate = `${base}-${n}`;\n used.add(candidate.toLowerCase());\n return candidate;\n}\n\n/** POSIX-style relative path for storage inside markers (stable across OS). */\nfunction relPosix(fromDir: string, toFile: string): string {\n return path.relative(fromDir, toFile).split(path.sep).join('/');\n}\n\n/** The real path of the tree being exploded, for the write check below. */\nconst explodeRoot = new AsyncLocalStorage<string>();\n\n/**\n * Refuse a write whose real directory is outside the tree: the names are\n * sanitised, but a symlink or junction already inside the tree could still\n * redirect it.\n */\nasync function assertInsideTree(filePath: string): Promise<void> {\n const root = explodeRoot.getStore();\n if (root === undefined) return;\n // Check the nearest directory that already exists, before creating any:\n // mkdir through a link would already have created directories outside.\n let dir = path.dirname(filePath);\n while (!existsSync(dir) && path.dirname(dir) !== dir) dir = path.dirname(dir);\n const real = await realpath(dir);\n if (real !== root && !real.startsWith(root + path.sep)) {\n throw new Error(`refusing to write outside the working tree: ${filePath}`);\n }\n // A safe parent does not make an existing file link safe to overwrite.\n const existing = await lstat(filePath).catch((err: NodeJS.ErrnoException) => {\n if (err.code !== 'ENOENT') throw err;\n return undefined;\n });\n if (existing?.isSymbolicLink()) throw new Error(`refusing to write through a file link: ${filePath}`);\n}\n\nasync function writeFileMkdir(filePath: string, data: string): Promise<void> {\n await assertInsideTree(filePath);\n await mkdir(path.dirname(filePath), { recursive: true });\n // NO added trailing newline — code strings must round-trip byte-identical.\n await writeFile(filePath, data);\n}\n\nasync function writeJson(filePath: string, value: Json): Promise<void> {\n await assertInsideTree(filePath);\n await mkdir(path.dirname(filePath), { recursive: true });\n await writeFile(filePath, JSON.stringify(value, null, 2));\n}\n\n// --- explode ---------------------------------------------------------------\n\n/**\n * Recursively extract code leaves from a value tree, IN PLACE (caller passes a\n * clone). `jsonDir` is the directory of the JSON file that will hold this tree;\n * `codeDir` is the directory under which sidecar `.js` files for this tree are\n * written; `prefixParts` accumulates the ancestor key/index chain for fallback\n * naming. `usedPaths` dedupes generated file paths within this resource.\n */\nasync function extractCode(\n value: Json,\n ctx: {\n jsonDir: string;\n codeDir: string;\n friendly: string | null; // friendly relative path (no extension) if known\n prefixParts: string[]; // ancestor key chain for fallback naming\n usedPaths: Set<string>;\n },\n): Promise<Json> {\n if (Array.isArray(value)) {\n const out: Json[] = [];\n for (let i = 0; i < value.length; i += 1) {\n out.push(\n await extractCode(value[i] as Json, {\n ...ctx,\n friendly: null,\n prefixParts: [...ctx.prefixParts, String(i)],\n }),\n );\n }\n return out;\n }\n\n if (!isPlainObject(value)) {\n return value;\n }\n\n // Recurse, applying friendly-path recognition for known Mirth structures.\n return extractFromObject(value, ctx);\n}\n\nasync function extractFromObject(\n obj: Record<string, Json>,\n ctx: {\n jsonDir: string;\n codeDir: string;\n friendly: string | null;\n prefixParts: string[];\n usedPaths: Set<string>;\n },\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(obj)) {\n // Code leaf? Only extract plain non-empty string leaves.\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw; // keep empty/whitespace-only inline (no file)\n continue;\n }\n const friendlyBase =\n key in CHANNEL_SCRIPT_FRIENDLY\n ? `scripts/${CHANNEL_SCRIPT_FRIENDLY[key]}`\n : // One filename segment: config keys are untrusted and may hold '/' or '..'.\n ctx.friendly ?? `_code/${slug([...ctx.prefixParts, key].join('.'))}`;\n const filePath = resolveUnique(ctx.codeDir, `${friendlyBase}.js`, ctx.usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(ctx.jsonDir, filePath) };\n continue;\n }\n\n // Recurse into children.\n out[key] = await extractCode(raw as Json, {\n ...ctx,\n friendly: null,\n prefixParts: [...ctx.prefixParts, key],\n });\n }\n\n return out;\n}\n\n/** Resolve a unique absolute file path for a friendly-or-fallback rel path. */\nfunction resolveUnique(baseDir: string, relName: string, used: Set<string>): string {\n const ext = path.extname(relName);\n const dir = path.dirname(relName);\n const stem = path.basename(relName, ext);\n const dirSlug = dir === '.' ? '' : dir;\n // Build slugged segments for the directory portion (preserve structure).\n const segs = dirSlug.split('/').filter(Boolean);\n // Case-insensitive, like uniqueSlug.\n let rel = [...segs, `${stem}${ext}`].join('/');\n for (let n = 2; used.has(rel.toLowerCase()); n += 1) rel = [...segs, `${stem}-${n}${ext}`].join('/');\n used.add(rel.toLowerCase());\n const full = path.resolve(baseDir, ...rel.split('/'));\n if (!full.startsWith(path.resolve(baseDir) + path.sep)) throw new Error(`script path escapes its directory: ${relName}`);\n return full;\n}\n\n/**\n * Walk a channel object giving friendly paths to its scripts and connector\n * transformer/filter steps, extracting code leaves in place. Returns the\n * transformed channel object. `dir` is the channel's directory (also the dir of\n * its `channel.json`). `usedPaths` dedupes within the channel.\n */\nasync function explodeChannelTree(\n channel: Record<string, Json>,\n dir: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(channel)) {\n // Channel-level scripts -> scripts/<friendly>.js\n if (key in CHANNEL_SCRIPT_FRIENDLY && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(dir, `scripts/${CHANNEL_SCRIPT_FRIENDLY[key]}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(dir, filePath) };\n continue;\n }\n\n if (key === 'sourceConnector' && isPlainObject(raw)) {\n out[key] = await explodeConnector(raw, dir, 'source', 'source/receiver', usedPaths);\n continue;\n }\n\n if (key === 'destinationConnectors' && isPlainObject(raw)) {\n out[key] = await explodeDestinationConnectors(raw, dir, usedPaths);\n continue;\n }\n\n // Everything else: generic extraction (covers unknown structures / code).\n out[key] = await extractCode(raw as Json, {\n jsonDir: dir,\n codeDir: dir,\n friendly: null,\n prefixParts: [key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/**\n * Explode a connector (source or a single destination). `baseRel` is the\n * relative directory prefix within the channel dir for this connector's\n * transformer/filter steps (e.g. `source` or `destinations/<slug>`).\n * `scriptFileBase` is the friendly path (no extension) for the connector's own\n * reader/writer code at `properties.script` (e.g. `source/receiver` or\n * `destinations/<slug>/writer`).\n */\nasync function explodeConnector(\n connector: Record<string, Json>,\n channelDir: string,\n baseRel: string,\n scriptFileBase: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(connector)) {\n if (key === 'transformer' && isPlainObject(raw)) {\n out[key] = await explodeStepContainer(raw, channelDir, `${baseRel}/transformer`, usedPaths);\n continue;\n }\n if (key === 'responseTransformer' && isPlainObject(raw)) {\n out[key] = await explodeStepContainer(\n raw,\n channelDir,\n `${baseRel}/responseTransformer`,\n usedPaths,\n );\n continue;\n }\n if (key === 'filter' && isPlainObject(raw)) {\n out[key] = await explodeStepContainer(raw, channelDir, `${baseRel}/filter`, usedPaths);\n continue;\n }\n if (key === 'properties' && isPlainObject(raw)) {\n out[key] = await explodeConnectorProperties(raw, channelDir, scriptFileBase, usedPaths);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/**\n * Explode a connector's `properties` object. The JavaScript Reader/Writer\n * connectors carry their body directly at `properties.script`; extract it to a\n * friendly `<scriptFileBase>.js`. Anything else recurses generically.\n */\nasync function explodeConnectorProperties(\n properties: Record<string, Json>,\n channelDir: string,\n scriptFileBase: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(properties)) {\n if (key === 'script' && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(channelDir, `${scriptFileBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(channelDir, filePath) };\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: ['properties', key],\n usedPaths,\n });\n }\n return out;\n}\n\nasync function explodeDestinationConnectors(\n container: Record<string, Json>,\n channelDir: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n const usedDestSlugs = new Set<string>();\n\n for (const [key, raw] of Object.entries(container)) {\n if (key === 'connector') {\n const connectors = asArray<Record<string, Json>>(raw);\n const wasArray = Array.isArray(raw);\n const transformed: Record<string, Json>[] = [];\n for (const conn of connectors) {\n const name = isPlainObject(conn) ? conn['name'] : undefined;\n const destSlug = uniqueSlug(slug(name), usedDestSlugs);\n transformed.push(\n isPlainObject(conn)\n ? await explodeConnector(\n conn,\n channelDir,\n `destinations/${destSlug}`,\n `destinations/${destSlug}/writer`,\n usedPaths,\n )\n : conn,\n );\n }\n out[key] = wasArray ? transformed : (transformed[0] as Json);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: ['destinationConnectors', key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/**\n * Explode a transformer/filter/responseTransformer container. Mirth nests the\n * actual steps under an `elements` key. In REAL data `elements` is an OBJECT\n * keyed by the step's fully-qualified Java class name (e.g.\n * `com.mirth.connect.plugins.javascriptstep.JavaScriptStep`), whose value is an\n * array of step objects:\n *\n * elements: { \"com.mirth...JavaScriptStep\": [ { name, sequenceNumber, script } ] }\n *\n * An empty transformer/filter serializes `elements` as the empty string `\"\"`.\n * We give each step a friendly `<baseRel>/<n>.<slug(step name)>.js` path, where\n * `n` is `sequenceNumber + 1` (string-parsed) falling back to a running index.\n * Unknown shapes fall back to generic extraction so we never crash.\n */\nasync function explodeStepContainer(\n container: Record<string, Json>,\n channelDir: string,\n baseRel: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(container)) {\n if (key === 'elements' && (Array.isArray(raw) || isPlainObject(raw))) {\n out[key] = await explodeElementsContainer(\n raw as Json[] | Record<string, Json>,\n channelDir,\n baseRel,\n usedPaths,\n );\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/** Does an object look like a single step (carries a code leaf or step metadata)? */\nfunction isStepLike(obj: Record<string, Json>): boolean {\n return (\n typeof obj['script'] === 'string' ||\n typeof obj['code'] === 'string' ||\n 'sequenceNumber' in obj ||\n 'name' in obj\n );\n}\n\n/**\n * Dispatch the `elements` value of a step container, numbering steps globally\n * in encounter order. Handles three shapes:\n * - ARRAY of step objects (a legacy / hand-written form).\n * - a single step OBJECT (`elements` collapsed to one step).\n * - the REAL Mirth form: an OBJECT keyed by fully-qualified class name whose\n * values are arrays (or single objects) of step objects.\n */\nasync function explodeElementsContainer(\n elements: Json[] | Record<string, Json>,\n channelDir: string,\n baseRel: string,\n usedPaths: Set<string>,\n): Promise<Json> {\n const counter = { i: 0 };\n\n if (Array.isArray(elements)) {\n return explodeStepArray(elements, channelDir, baseRel, usedPaths, counter);\n }\n\n // A single step object directly under `elements`.\n if (isStepLike(elements)) {\n return explodeStep(elements, channelDir, baseRel, counter.i++, usedPaths);\n }\n\n // Class-keyed map of step buckets (the real shape).\n const out: Record<string, Json> = {};\n for (const [className, raw] of Object.entries(elements)) {\n // Attributes (`@_...`), adapter metadata (`#order`, `#comment`) and nulls\n // are passed through generically, not numbered as steps.\n if (className.startsWith('@_') || className.startsWith('#') || raw == null) {\n out[className] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, 'elements', className],\n usedPaths,\n });\n continue;\n }\n if (Array.isArray(raw)) {\n out[className] = await explodeStepArray(raw, channelDir, baseRel, usedPaths, counter);\n continue;\n }\n if (isPlainObject(raw) && isStepLike(raw)) {\n out[className] = await explodeStep(raw, channelDir, baseRel, counter.i++, usedPaths);\n continue;\n }\n out[className] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, 'elements', className],\n usedPaths,\n });\n }\n return out;\n}\n\nasync function explodeStepArray(\n steps: Json[],\n channelDir: string,\n baseRel: string,\n usedPaths: Set<string>,\n counter: { i: number },\n): Promise<Json[]> {\n const transformed: Json[] = [];\n for (const step of steps) {\n transformed.push(await explodeStep(step, channelDir, baseRel, counter.i++, usedPaths));\n }\n return transformed;\n}\n\nasync function explodeStep(\n step: Json,\n channelDir: string,\n baseRel: string,\n index: number,\n usedPaths: Set<string>,\n): Promise<Json> {\n if (!isPlainObject(step)) {\n return step;\n }\n\n // Sequence number (Mirth) is 0-based; prefer it, else fall back to index.\n const seqRaw = step['sequenceNumber'];\n let seq = index;\n if (typeof seqRaw === 'number') seq = seqRaw;\n else if (typeof seqRaw === 'string' && seqRaw.trim() !== '' && !Number.isNaN(Number(seqRaw))) {\n seq = Number(seqRaw);\n }\n const n = seq + 1;\n const stepName = step['name'];\n // Many real steps have no `name`; fall back to a bare `<n>` segment so the\n // file reads as e.g. `1.js` rather than `1.unnamed.js`.\n const hasName = typeof stepName === 'string' && stepName.trim().length > 0;\n const friendlyBase = hasName ? `${baseRel}/${n}.${slug(stepName)}` : `${baseRel}/${n}`;\n\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(step)) {\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(channelDir, `${friendlyBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(channelDir, filePath) };\n continue;\n }\n // Recurse generically into anything else (handles nested unknowns).\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, String(index), key],\n usedPaths,\n });\n }\n return out;\n}\n\n/**\n * Split the three known top-level collections into per-resource JSON files,\n * replacing each element with an `@ref` marker (order preserved). Each split-out\n * resource is itself code-extracted under its own directory.\n *\n * Returns the rewritten container value (object or array preserved as-is) with\n * `@ref` markers, or null if the collection was absent.\n */\nasync function splitCollection(\n parent: Record<string, Json>,\n containerKey: string, // e.g. 'channels'\n elementKey: string, // e.g. 'channel'\n root: string,\n serverDir: string, // dir holding configuration.json (markers are relative to it)\n targetFor: (name: unknown, slugName: string) => { jsonFile: string; resourceDir: string },\n usedSlugs: Set<string>,\n explodeResource: (\n el: Record<string, Json>,\n resourceDir: string,\n ) => Promise<Record<string, Json>>,\n): Promise<void> {\n const container = parent[containerKey];\n if (!isPlainObject(container)) return;\n const raw = container[elementKey];\n if (raw == null) return;\n\n const wasArray = Array.isArray(raw);\n const elements = asArray<Json>(raw);\n const refs: Json[] = [];\n\n // Suffixes for colliding names (\"Lab Feed\", \"LAB FEED\") are handed out by\n // name then id, not list order: the server's order can change (a restore\n // reorders it), which would move a resource to another directory.\n const byName = (el: Record<string, Json>) => `${slug(el['name']).toLowerCase()}\\u0000${String(el['id'] ?? '')}`;\n const slugs = new Map<Json, string>();\n for (const el of elements.filter(isPlainObject).sort((a, b) => (byName(a) < byName(b) ? -1 : byName(a) > byName(b) ? 1 : 0))) {\n slugs.set(el, uniqueSlug(slug(el['name']), usedSlugs));\n }\n\n for (const el of elements) {\n if (!isPlainObject(el)) {\n // Non-object element: keep inline (cannot meaningfully split).\n refs.push(el);\n continue;\n }\n const slugName = slugs.get(el)!;\n const { jsonFile, resourceDir } = targetFor(el['name'], slugName);\n const transformed = await explodeResource(el, resourceDir);\n await writeJson(jsonFile, transformed);\n refs.push({ '@ref': relPosix(serverDir, jsonFile) });\n }\n\n // Preserve object-vs-array shape of the element container.\n container[elementKey] = wasArray ? refs : (refs[0] as Json);\n}\n\nasync function explode(config: CanonicalConfig, opts: ExplodeOptions): Promise<void> {\n await mkdir(opts.root, { recursive: true });\n await explodeRoot.run(await realpath(opts.root), () => explodeInto(config, opts));\n}\n\nasync function explodeInto(config: CanonicalConfig, opts: ExplodeOptions): Promise<void> {\n const root = opts.root;\n const serverDir = path.join(root, 'server');\n const skeleton = deepClone(config) as Record<string, Json>;\n\n // 1. channels.channel[] -> channels/<slug>/channel.json\n if (isPlainObject(skeleton['channels'])) {\n const channelSlugs = new Set<string>();\n await splitCollection(\n skeleton,\n 'channels',\n 'channel',\n root,\n serverDir,\n (_name, slugName) => {\n const resourceDir = path.join(root, 'channels', slugName);\n return { jsonFile: path.join(resourceDir, 'channel.json'), resourceDir };\n },\n channelSlugs,\n async (el, resourceDir) => explodeChannelTree(el, resourceDir, new Set<string>()),\n );\n }\n\n // 2. codeTemplateLibraries.codeTemplateLibrary[] -> codeTemplates/<slug>/library.json\n if (isPlainObject(skeleton['codeTemplateLibraries'])) {\n const libSlugs = new Set<string>();\n await splitCollection(\n skeleton,\n 'codeTemplateLibraries',\n 'codeTemplateLibrary',\n root,\n serverDir,\n (_name, slugName) => {\n const resourceDir = path.join(root, 'codeTemplates', slugName);\n return { jsonFile: path.join(resourceDir, 'library.json'), resourceDir };\n },\n libSlugs,\n async (el, resourceDir) => explodeLibrary(el, resourceDir),\n );\n }\n\n // 3. channelGroups.channelGroup[] -> channelGroups/<slug>.json\n if (isPlainObject(skeleton['channelGroups'])) {\n const groupSlugs = new Set<string>();\n await splitCollection(\n skeleton,\n 'channelGroups',\n 'channelGroup',\n root,\n serverDir,\n (_name, slugName) => {\n const resourceDir = path.join(root, 'channelGroups');\n return { jsonFile: path.join(resourceDir, `${slugName}.json`), resourceDir };\n },\n groupSlugs,\n async (el, resourceDir) =>\n // group json lives in channelGroups/; sidecar code (rare) under same dir\n extractCode(el, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['channelGroup'],\n usedPaths: new Set<string>(),\n }) as Promise<Record<string, Json>>,\n );\n }\n\n // 4. Extract code in the remaining skeleton (e.g. globalScripts) and write it.\n const finalSkeleton = await extractCode(skeleton, {\n jsonDir: serverDir,\n codeDir: serverDir,\n friendly: null,\n prefixParts: [],\n usedPaths: new Set<string>(),\n });\n\n await writeJson(path.join(serverDir, 'configuration.json'), finalSkeleton);\n}\n\n/**\n * Explode a code template library: split-out resource. Each template's `code`\n * leaf -> `<slug(template name)>.js` next to library.json (resourceDir).\n */\nasync function explodeLibrary(\n library: Record<string, Json>,\n resourceDir: string,\n): Promise<Record<string, Json>> {\n const used = new Set<string>();\n const usedTemplateSlugs = new Set<string>();\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(library)) {\n if (key === 'codeTemplates' && isPlainObject(raw)) {\n out[key] = await explodeLibraryTemplates(raw, resourceDir, usedTemplateSlugs, used);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: [key],\n usedPaths: used,\n });\n }\n return out;\n}\n\nasync function explodeLibraryTemplates(\n container: Record<string, Json>,\n resourceDir: string,\n usedTemplateSlugs: Set<string>,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(container)) {\n if (key === 'codeTemplate' && raw != null) {\n const wasArray = Array.isArray(raw);\n const templates = asArray<Json>(raw);\n const transformed: Json[] = [];\n for (const t of templates) {\n transformed.push(\n await explodeCodeTemplate(t, resourceDir, usedTemplateSlugs, usedPaths),\n );\n }\n out[key] = wasArray ? transformed : (transformed[0] as Json);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['codeTemplates', key],\n usedPaths,\n });\n }\n return out;\n}\n\nasync function explodeCodeTemplate(\n template: Json,\n resourceDir: string,\n usedTemplateSlugs: Set<string>,\n usedPaths: Set<string>,\n): Promise<Json> {\n if (!isPlainObject(template)) return template;\n const friendlyBase = uniqueSlug(slug(template['name']), usedTemplateSlugs);\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(template)) {\n // In real Mirth data the body lives at `properties.code`; handle that and\n // (defensively) a `code`/`script` leaf directly on the template object.\n if (key === 'properties' && isPlainObject(raw)) {\n out[key] = await explodeTemplateProperties(raw, resourceDir, friendlyBase, usedPaths);\n continue;\n }\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(resourceDir, `${friendlyBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(resourceDir, filePath) };\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['codeTemplate', key],\n usedPaths,\n });\n }\n return out;\n}\n\n/**\n * Explode a code template's `properties` object, whose `code` leaf is the\n * template body -> friendly `<friendlyBase>.js` next to library.json.\n */\nasync function explodeTemplateProperties(\n properties: Record<string, Json>,\n resourceDir: string,\n friendlyBase: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(properties)) {\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(resourceDir, `${friendlyBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(resourceDir, filePath) };\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['codeTemplate', 'properties', key],\n usedPaths,\n });\n }\n return out;\n}\n\n// --- implode ---------------------------------------------------------------\n\n/**\n * Resolve a marker path relative to `jsonDir` and assert it stays inside the\n * working-tree `root`. Legitimate markers DO use `..` (e.g. `server/`'s config\n * references `../channelGroups/*.json`), so `..` is allowed — only escaping the\n * tree root is rejected. Working trees are shared/cloned git repos, so marker\n * values are attacker-influenceable input; without this check a crafted\n * `{\"@file\": \"../../../../etc/passwd\"}` would be read into the imploded config\n * (and, via `push`, uploaded to a live server).\n */\nfunction resolveWithinRoot(root: string, jsonDir: string, rel: string): string {\n const target = path.resolve(jsonDir, rel);\n if (target !== root && !target.startsWith(root + path.sep)) {\n throw new Error(`marker path escapes the working tree: ${rel}`);\n }\n return target;\n}\n\n/**\n * Read a marker target, re-checking containment on the real path: the text\n * check above can't see a symlink or junction inside the tree that points\n * outside it.\n */\nasync function readWithinRoot(root: string, target: string, rel: string): Promise<string> {\n const [realRoot, realTarget] = await Promise.all([realpath(root), realpath(target)]);\n if (realTarget !== realRoot && !realTarget.startsWith(realRoot + path.sep)) {\n throw new Error(`marker path escapes the working tree through a link: ${rel}`);\n }\n return readFile(realTarget, 'utf8');\n}\n\n/**\n * Recursively resolve markers in a parsed JSON value. `jsonDir` is the directory\n * of the JSON file this value came from (markers are relative to it); `root` is\n * the working-tree root that every marker target must stay within.\n */\nconst pathKey = (file: string): string => process.platform === 'win32' ? file.toLowerCase() : file;\n\nasync function resolveMarkers(value: Json, jsonDir: string, root: string, referenced: Set<string>): Promise<Json> {\n if (Array.isArray(value)) {\n const out: Json[] = [];\n for (const item of value) {\n // A collection member whose file is gone was deleted from the tree\n // (e.g. `rm -r channels/<name>`), so it is dropped, not an error.\n if (isRefMarker(item) && !existsSync(resolveWithinRoot(root, jsonDir, item['@ref']))) continue;\n out.push(await resolveMarkers(item, jsonDir, root, referenced));\n }\n return out;\n }\n\n if (isFileRef(value)) {\n const target = resolveWithinRoot(root, jsonDir, value['@file']);\n // Raw read, NO trimming — byte-identical round-trip.\n return readWithinRoot(root, target, value['@file']);\n }\n\n if (isRefMarker(value)) {\n const target = resolveWithinRoot(root, jsonDir, value['@ref']);\n const text = await readWithinRoot(root, target, value['@ref']);\n referenced.add(pathKey(await realpath(target)));\n const parsed = parseJson<Json>(text, target);\n return resolveMarkers(parsed, path.dirname(target), root, referenced);\n }\n\n if (isPlainObject(value)) {\n const out: Record<string, Json> = {};\n for (const [k, v] of Object.entries(value)) {\n // Same for a one-member collection, which explode stores as a bare marker.\n if (isRefMarker(v) && !existsSync(resolveWithinRoot(root, jsonDir, v['@ref']))) continue;\n out[k] = await resolveMarkers(v, jsonDir, root, referenced);\n }\n return out;\n }\n\n return value;\n}\n\n/** Canonical resource files are discoverable, so additions and directory renames cannot disappear. */\nasync function discoverResources(config: CanonicalConfig, root: string, referenced: Set<string>): Promise<void> {\n const realRoot = await realpath(root);\n const contained = async (file: string): Promise<string> => {\n const real = await realpath(file);\n if (real !== realRoot && !real.startsWith(realRoot + path.sep)) throw new Error(`resource path escapes the working tree through a link: ${file}`);\n return real;\n };\n const layouts = [\n { folder: 'channels', filename: 'channel.json', container: 'channels', member: 'channel' },\n { folder: 'codeTemplates', filename: 'library.json', container: 'codeTemplateLibraries', member: 'codeTemplateLibrary' },\n { folder: 'channelGroups', filename: null, container: 'channelGroups', member: 'channelGroup' },\n ];\n for (const layout of layouts) {\n const dir = path.join(root, layout.folder);\n if (!existsSync(dir)) continue;\n await contained(dir);\n const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);\n const additions: Json[] = [];\n for (const entry of entries) {\n let file = path.join(dir, entry.name);\n if (layout.filename) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;\n await contained(file);\n file = path.join(file, layout.filename);\n if (!existsSync(file)) continue;\n } else if (!entry.name.endsWith('.json')) continue;\n const real = await contained(file);\n if (referenced.has(pathKey(real))) continue;\n const parsed = parseJson<Json>(await readWithinRoot(root, file, file), file);\n const resource = await resolveMarkers(parsed, path.dirname(file), root, referenced);\n if (!isPlainObject(resource) || typeof resource['id'] !== 'string' || !resource['id'].trim() || typeof resource['name'] !== 'string' || !resource['name'].trim()) {\n throw new Error(`new resource ${file} needs a nonempty id and name`);\n }\n additions.push(resource);\n referenced.add(pathKey(real));\n }\n if (!additions.length) continue;\n const container = isPlainObject(config[layout.container]) ? config[layout.container] as Record<string, Json> : {};\n const old = container[layout.member];\n const members = [...(old == null || old === '' ? [] : asArray<Json>(old)), ...additions];\n const ids = new Set<string>();\n for (const member of members.filter(isPlainObject)) {\n const id = String(member['id']);\n if (ids.has(id)) throw new Error(`duplicate ${layout.member} id ${id}: a copied resource keeps its source's id; give each copy a new UUID`);\n ids.add(id);\n }\n config[layout.container] = { ...container, [layout.member]: members.length === 1 ? members[0]! : members };\n }\n}\n\nasync function implode(opts: ExplodeOptions): Promise<CanonicalConfig> {\n const root = path.resolve(opts.root);\n if (existsSync(path.join(root, '.channelvault-transaction.json'))) {\n throw new Error('working tree has a pending replacement; run a channelvault CLI command with the original --dotenv selection to recover it before reading');\n }\n const serverDir = path.join(root, 'server');\n const configPath = path.join(serverDir, 'configuration.json');\n const parsed = parseJson<Json>(await readWithinRoot(root, configPath, configPath), configPath);\n const referenced = new Set<string>();\n const resolved = await resolveMarkers(parsed, serverDir, root, referenced);\n if (!isPlainObject(resolved)) throw new Error('server/configuration.json must hold a configuration object');\n await discoverResources(resolved, root, referenced);\n return resolved as CanonicalConfig;\n}\n\n// --- factory ---------------------------------------------------------------\n\nexport function createExplodeEngine(): ExplodeEngine {\n return { explode, implode };\n}\n","import { readFile } from 'node:fs/promises';\n\n/** JSON.parse, naming the file in the error: a tree has hundreds of JSON files. */\nexport function parseJson<T = unknown>(text: string, file: string): T {\n try {\n return JSON.parse(text) as T;\n } catch (err) {\n throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nexport async function readJson<T = unknown>(file: string): Promise<T> {\n return parseJson<T>(await readFile(file, 'utf8'), file);\n}\n","/**\n * Live Mirth transport client.\n *\n * Talks to a running Mirth Connect (a.k.a. NextGen Connect / OIE / BridgeLink)\n * server over its REST API and produces/consumes the canonical config (the\n * unwrapped `serverConfiguration` document) — the same logical document the XML\n * adapter parses from a backup file.\n *\n * The transport (login, cookie jar, TLS bypass, 401 re-auth, single-flight\n * login) is ported from the proven `baseClient.ts` in the sibling\n * `integration-engine-api` project. We deliberately do NOT carry over the\n * OpenAPI-generated typing layers: payloads are opaque `CanonicalConfig` JSON.\n *\n * Wrapping behavior for the two endpoints:\n *\n * - GET /server/configuration returns a Jackson-style document wrapped in a\n * single top-level key (`serverConfiguration`), with `@version` / `@class`\n * metadata sprinkled throughout. `getServerConfiguration()` unwraps the\n * single top-level key and returns its contents.\n * - PUT /server/configuration expects the same wrapper, so\n * `putServerConfiguration()` re-wraps as `{ serverConfiguration: config }`.\n */\nimport { CookieJar } from 'tough-cookie';\nimport { Agent } from 'undici';\nimport { redactSecretsInText } from '../secrets/detect.js';\nimport { isSecretKey } from '../secrets/index.js';\nimport type { ApiError, CanonicalConfig, ClientConfig, MirthClient } from '../types.js';\nimport { liveConfiguration } from './validate.js';\n\n/** TLS verification failures, typically a self-signed or privately issued server certificate. */\nexport const UNTRUSTED_CERT_CODES: ReadonlySet<string> = new Set([\n 'DEPTH_ZERO_SELF_SIGNED_CERT',\n 'SELF_SIGNED_CERT_IN_CHAIN',\n 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',\n // Not an expired certificate or a host-name mismatch: turning verification\n // off is the wrong advice for those, and their messages already say why.\n]);\n\n/**\n * fetch reports every network failure as \"fetch failed\" and keeps the reason\n * (ECONNREFUSED, a certificate error) in `cause`; surface it, with its code.\n */\nfunction connectionError(url: string, err: unknown): Error & { code?: string } {\n let cause = err instanceof Error ? (err.cause as (Error & { code?: string; errors?: unknown[] }) | undefined) : undefined;\n // Several addresses tried (IPv4 and IPv6): report the first attempt.\n if (cause instanceof AggregateError && cause.errors[0] instanceof Error) cause = cause.errors[0] as Error & { code?: string };\n const detail = cause?.message || (err instanceof Error ? err.message : String(err));\n const code = cause?.code;\n const error = new Error(\n `cannot reach ${new URL(url).origin}: ${detail}${code && !detail.includes(code) ? ` (${code})` : ''}`,\n { cause: err },\n ) as Error & { code?: string };\n error.code = code;\n return error;\n}\n\n/** Optional flags accepted by `putServerConfiguration` (Mirth query params). */\nexport interface PutServerConfigurationOptions {\n /** Redeploy all channels after applying the configuration. */\n deploy?: boolean;\n /** Overwrite the global configuration map. */\n overwriteConfigMap?: boolean;\n}\n\n/**\n * The public client type. It satisfies the declared {@link MirthClient}\n * contract but widens `putServerConfiguration` to accept the optional Mirth\n * query-param flags. The widened signature is structurally assignable to the\n * one-arg contract (the extra parameter is optional), so a `MirthClientExt`\n * is a valid `MirthClient` wherever the bare contract is expected.\n */\nexport interface MirthClientExt extends MirthClient {\n putServerConfiguration(config: CanonicalConfig, options?: PutServerConfigurationOptions): Promise<void>;\n /** GET /server/id: the installation's ID, which a configuration restore does not change (verified on 4.5.2). */\n getServerId(): Promise<string>;\n /** GET /server/configuration as the server's own XML (the Administrator's Backup Config document). */\n getServerConfigurationXml(): Promise<string>;\n /** PUT /server/configuration from backup XML, as the Administrator's Restore Config does. */\n putServerConfigurationXml(xml: string, options?: PutServerConfigurationOptions): Promise<void>;\n /** GET /channels/{id}, unwrapped; includes the tag and dependency data the server configuration omits. */\n getChannel(id: string): Promise<Record<string, unknown> | null>;\n /** Standalone templates remain readable after being removed from a library. */\n getCodeTemplate(id: string): Promise<Record<string, unknown> | null>;\n /** PUT /channels/{id}; creates the channel if the id is new. */\n putChannel(channel: Record<string, unknown>): Promise<void>;\n /** Release pooled connections so the process can exit promptly. */\n close(): Promise<void>;\n deleteChannel(id: string): Promise<void>;\n /** PUT /codeTemplates/{id}; creates the template if the id is new. */\n putCodeTemplate(template: Record<string, unknown>): Promise<void>;\n deleteCodeTemplate(id: string): Promise<void>;\n /** PUT /codeTemplateLibraries: replaces the whole list (membership and library settings). */\n putCodeTemplateLibraries(libraries: Record<string, unknown>[]): Promise<void>;\n /** PUT /server/globalScripts, from the `globalScripts` value of a server configuration. */\n putGlobalScripts(globalScripts: unknown): Promise<void>;\n /** POST /channels/{id}/_deploy; throws if deployment fails. */\n deployChannel(id: string): Promise<void>;\n /** Ids of the channels currently deployed (GET /channels/statuses). */\n getDeployedChannelIds(): Promise<Set<string>>;\n}\n\n/** Internal HTTP verbs we use. */\ntype HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n\n/** Options for the low-level authenticated request helper. */\ninterface RequestOptions {\n /** Already-serialized request body. */\n body?: string;\n /** Query parameters appended to the URL. */\n query?: Record<string, unknown>;\n /** Additional headers merged over the defaults. */\n headers?: Record<string, string>;\n}\n\n/** Shape of the (unwrapped) Mirth login status payload we read. */\ninterface LoginStatusPayload {\n status?: string;\n message?: string | null;\n}\n\n/** The single top-level wrapper key of a Mirth backup / server config document. */\nconst SERVER_CONFIG_KEY = 'serverConfiguration';\n\n/**\n * Unwrap a Jackson-style single-key wrapper. Mirth wraps many responses in a\n * single top-level namespace key. If the value has exactly one top-level key we\n * unwrap it; otherwise we return it unchanged (defensive against the wrapper\n * being named differently or absent).\n */\nfunction unwrapSingleKey(value: Record<string, unknown>): unknown {\n const keys = Object.keys(value);\n if (keys.length === 1) {\n return value[keys[0] as string];\n }\n return value;\n}\n\n/**\n * MirthClient implementation. Created via {@link createMirthClient}.\n */\nclass MirthClientImpl implements MirthClientExt {\n private readonly config: ClientConfig;\n private readonly baseUrl: string;\n private readonly cookieJar: CookieJar;\n /** Our own pool (not the global one) so `close()` can release it. */\n private readonly dispatcher: Agent;\n\n private authenticated = false;\n /** Single in-flight login promise (concurrency guard). */\n private loginPromise: Promise<void> | null = null;\n\n constructor(config: ClientConfig) {\n this.config = config;\n const protocol = config.https !== false ? 'https' : 'http';\n this.baseUrl = `${protocol}://${config.host}:${config.port}/api`;\n this.cookieJar = new CookieJar();\n\n this.dispatcher = new Agent(config.disableTlsCheck ? { connect: { rejectUnauthorized: false } } : {});\n }\n\n isAuthenticated(): boolean {\n return this.authenticated;\n }\n\n /**\n * Establish a session. Concurrent calls share a single in-flight login.\n */\n async login(): Promise<void> {\n if (this.loginPromise) {\n return this.loginPromise;\n }\n\n this.loginPromise = (async () => {\n try {\n const loginUrl = `${this.baseUrl}/users/_login`;\n\n const body = new URLSearchParams({\n username: this.config.username,\n password: this.config.password,\n });\n\n const response = await this.send(loginUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-Requested-With': 'XMLHttpRequest',\n Accept: 'application/json',\n },\n body: body.toString(),\n });\n\n await this.storeCookies(response, this.baseUrl);\n\n if (!response.ok) {\n // Not the body: a login endpoint's error page can echo the request.\n await response.body?.cancel();\n throw new Error(`Login failed: HTTP ${response.status} ${response.statusText}`.trimEnd());\n }\n\n const result = (await response.json()) as Record<string, unknown>;\n\n // Mirth wraps the result, e.g.\n // { 'com.mirth.connect.model.LoginStatus': { status: 'SUCCESS', message: null } }\n const payload = unwrapSingleKey(result) as LoginStatusPayload;\n\n if (payload.status !== 'SUCCESS') {\n throw new Error(`Login failed: ${payload.status} - ${payload.message ?? 'Unknown error'}`);\n }\n\n this.authenticated = true;\n } finally {\n this.loginPromise = null;\n }\n })();\n\n return this.loginPromise;\n }\n\n /**\n * End the session and clear local auth state + cookies.\n */\n async logout(): Promise<void> {\n if (!this.authenticated) {\n return;\n }\n\n try {\n const logoutUrl = `${this.baseUrl}/users/_logout`;\n const cookieString = await this.cookieJar.getCookieString(logoutUrl);\n await this.send(logoutUrl, {\n method: 'POST',\n headers: {\n 'X-Requested-With': 'XMLHttpRequest',\n ...(cookieString ? { Cookie: cookieString } : {}),\n },\n });\n } finally {\n this.authenticated = false;\n await this.cookieJar.removeAllCookies();\n }\n }\n\n /**\n * GET /server/configuration -> canonical config.\n *\n * Requests JSON and validates the envelope and core resource collections\n * before this snapshot can be used to replace a tree or plan server writes.\n */\n async getServerConfiguration(): Promise<CanonicalConfig> {\n const response = await this.request('GET', '/server/configuration', {\n headers: { Accept: 'application/json' },\n });\n\n let json: unknown;\n try { json = await response.json(); }\n catch { throw new Error('invalid server configuration response: expected JSON'); }\n return liveConfiguration(json);\n }\n\n /**\n * PUT /server/configuration <- canonical config.\n *\n * Re-wraps the canonical config as `{ serverConfiguration: config }` and\n * forwards the optional `deploy` / `overwriteConfigMap` flags as query params.\n */\n async putServerConfiguration(config: CanonicalConfig, options: PutServerConfigurationOptions = {}): Promise<void> {\n const query: Record<string, unknown> = {};\n if (options.deploy !== undefined) {\n query.deploy = options.deploy;\n }\n if (options.overwriteConfigMap !== undefined) {\n query.overwriteConfigMap = options.overwriteConfigMap;\n }\n\n const wrapped = { [SERVER_CONFIG_KEY]: config };\n\n await this.request('PUT', '/server/configuration', {\n query,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify(wrapped),\n });\n }\n\n async getServerId(): Promise<string> {\n // JSON is refused (406); the ID comes as plain text. Mirth generates a UUID but reads it from\n // appdata/server.id, which admins can set to any name (one 4.5.0 server answers \"mirth-gov\").\n // It is only compared and printed, so accept one printable line and refuse control and\n // format characters (terminal escapes, newlines, bidi overrides).\n const response = await this.request('GET', '/server/id', { headers: { Accept: 'text/plain' } });\n const id = (await response.text()).trim();\n if (!/^[^\\p{Cc}\\p{Cf}]{1,255}$/u.test(id)) throw new Error('the server returned an invalid installation ID');\n return id;\n }\n\n async getServerConfigurationXml(): Promise<string> {\n const response = await this.request('GET', '/server/configuration', { headers: { Accept: 'application/xml' } });\n return response.text();\n }\n\n async putServerConfigurationXml(xml: string, options: PutServerConfigurationOptions = {}): Promise<void> {\n await this.request('PUT', '/server/configuration', {\n query: { deploy: options.deploy, overwriteConfigMap: options.overwriteConfigMap },\n headers: { 'Content-Type': 'application/xml', Accept: 'application/json' },\n body: xml,\n });\n }\n\n // --- per-resource ---------------------------------------------------------\n // Override is on: Mirth does not reject a stale revision anyway (verified on\n // 4.5.2), so conflict detection happens in the push planner instead.\n\n async getChannel(id: string): Promise<Record<string, unknown> | null> {\n return this.getResource(`/channels/${encodeURIComponent(id)}`);\n }\n\n async getCodeTemplate(id: string): Promise<Record<string, unknown> | null> {\n return this.getResource(`/codeTemplates/${encodeURIComponent(id)}`);\n }\n\n private async getResource(resourcePath: string): Promise<Record<string, unknown> | null> {\n const response = await this.request('GET', resourcePath, {\n headers: { Accept: 'application/json' },\n }).catch((err: Error & ApiError) => {\n if (err.status === 404) return null;\n throw err;\n });\n if (!response) return null;\n const text = await response.text();\n if (text.trim() === '') return null;\n const parsed = JSON.parse(text) as Record<string, unknown> | null;\n return parsed === null ? null : unwrapSingleKey(parsed) as Record<string, unknown> | null;\n }\n\n async close(): Promise<void> {\n await this.dispatcher.close();\n }\n\n async putChannel(channel: Record<string, unknown>): Promise<void> {\n await this.sendJson('PUT', `/channels/${encodeURIComponent(String(channel.id))}`, { channel }, { override: true });\n }\n\n async deleteChannel(id: string): Promise<void> {\n await this.request('DELETE', `/channels/${encodeURIComponent(id)}`);\n }\n\n async putCodeTemplate(template: Record<string, unknown>): Promise<void> {\n await this.sendJson('PUT', `/codeTemplates/${encodeURIComponent(String(template.id))}`, { codeTemplate: template }, { override: true });\n }\n\n async deleteCodeTemplate(id: string): Promise<void> {\n await this.request('DELETE', `/codeTemplates/${encodeURIComponent(id)}`);\n }\n\n async putCodeTemplateLibraries(libraries: Record<string, unknown>[]): Promise<void> {\n await this.sendJson('PUT', '/codeTemplateLibraries', { list: { codeTemplateLibrary: libraries } }, { override: true });\n }\n\n async putGlobalScripts(globalScripts: unknown): Promise<void> {\n await this.sendJson('PUT', '/server/globalScripts', { map: globalScripts });\n }\n\n async getDeployedChannelIds(): Promise<Set<string>> {\n const response = await this.request('GET', '/channels/statuses', { headers: { Accept: 'application/json' } });\n const text = await response.text();\n const ids = new Set<string>();\n // Undeployed channels have no status entry; collect every channelId present.\n for (const m of text.matchAll(/\"channelId\"\\s*:\\s*\"([^\"]+)\"/g)) ids.add(m[1]!);\n return ids;\n }\n\n async deployChannel(id: string): Promise<void> {\n await this.request('POST', `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });\n }\n\n /** Send a JSON body; Mirth answers some updates with `{\"boolean\": false}` instead of an error status. */\n private async sendJson(method: HttpMethod, path: string, body: unknown, query?: Record<string, unknown>): Promise<void> {\n const response = await this.request(method, path, {\n query,\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify(body),\n });\n const text = await response.text();\n if (/^\\s*\\{\\s*\"boolean\"\\s*:\\s*false\\s*\\}\\s*$/.test(text)) {\n throw new Error(`${method} ${path}: the server refused the update`);\n }\n }\n\n // --- internal transport ---------------------------------------------------\n\n /**\n * Make an authenticated request. Ensures login, attaches/stores cookies, and\n * on a 401 while authenticated resets auth, re-logs in once, and retries.\n * Throws an {@link ApiError}-shaped error on a non-2xx response.\n */\n private async request(method: HttpMethod, path: string, options: RequestOptions = {}, isRetry = false): Promise<Response> {\n if (!this.authenticated) {\n await this.login();\n }\n\n const url = this.buildUrl(path, options.query);\n\n const headers: Record<string, string> = {\n 'X-Requested-With': 'XMLHttpRequest',\n ...options.headers,\n };\n\n const cookieString = await this.cookieJar.getCookieString(url);\n if (cookieString) {\n headers.Cookie = cookieString;\n }\n\n const response = await this.send(url, { method, headers, body: options.body });\n\n await this.storeCookies(response, url);\n\n // 401 while authenticated -> reset auth, re-login once, retry exactly once.\n if (response.status === 401 && this.authenticated && !isRetry) {\n this.authenticated = false;\n await this.login();\n return this.request(method, path, options, true);\n }\n\n if (!response.ok) {\n throw await this.toApiError(response);\n }\n\n return response;\n }\n\n /** fetch through this client's pool, with network failures explained. */\n private async send(url: string, init: RequestInit): Promise<Response> {\n try {\n return await fetch(url, {\n ...init,\n // @ts-expect-error - dispatcher is a Node.js/undici specific option\n dispatcher: this.dispatcher,\n });\n } catch (err) {\n throw connectionError(url, err);\n }\n }\n\n /** Build an absolute URL with an optional query string. */\n private buildUrl(path: string, query?: Record<string, unknown>): string {\n const url = `${this.baseUrl}${path}`;\n if (!query || Object.keys(query).length === 0) {\n return url;\n }\n\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) {\n continue;\n }\n searchParams.append(key, String(value));\n }\n\n const qs = searchParams.toString();\n return qs ? `${url}?${qs}` : url;\n }\n\n /** Persist any `set-cookie` from a response into the jar. */\n private async storeCookies(response: Response, url: string): Promise<void> {\n // One entry per header: get('set-cookie') joins them with \", \", which also\n // appears inside a cookie's Expires date.\n for (const cookie of response.headers.getSetCookie()) {\n await this.cookieJar.setCookie(cookie, url);\n }\n }\n\n /** Build an ApiError-shaped Error from a non-2xx response. */\n private async toApiError(response: Response): Promise<Error & ApiError> {\n let body: unknown;\n try {\n body = await response.text();\n } catch {\n // ignore body read errors\n }\n\n // An error body can echo the payload sent, credentials included, in any\n // form (escaped, truncated, reformatted), so no redaction of it is\n // complete: it is left out unless asked for. When included it is whole and\n // unnormalized, so the caller's scrub of known values can still match.\n const text = typeof body === 'string' ? redactSecretsInText(readableBody(body)).trim() : '';\n const reason =\n text === '' ? '' : this.config.includeResponseBodies ? `: ${text}` : ' (server response withheld; it may echo credentials)';\n const message = `HTTP ${response.status}: ${response.statusText}${reason}`;\n const error = new Error(message) as Error & ApiError;\n error.status = response.status;\n error.statusText = response.statusText;\n error.message = message;\n error.body = text;\n return error;\n }\n}\n\nconst XML_ENTITIES: Readonly<Record<string, string>> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" };\n\n/**\n * An error body as the text a person reads: JSON as its decoded values, XML as\n * its decoded text. Anything that redacts by value (the CLI knows the secrets\n * sent) then sees a secret as it was sent, not escaped as `\\\"` or `&`.\n * Credential fields are replaced while their names are still known.\n */\nexport function readableBody(body: string): string {\n const trimmed = body.trim();\n // Any JSON value: a bare string can carry \\u escapes too.\n if (/^[[{\"]/.test(trimmed)) {\n try {\n return flattenJson(JSON.parse(trimmed) as unknown);\n } catch {\n // not JSON after all\n }\n }\n if (!trimmed.startsWith('<')) return trimmed;\n // Mirth's HTML error pages say only \"Request failed.\", so they add nothing.\n if (/^<(!doctype|html)/i.test(trimmed)) return '';\n // A marker that survives removing the tags.\n const REDACTED = '\\u0000redacted\\u0000';\n return trimmed\n .replace(/<([\\w.:-]+)>[^<]*<\\/\\1>/g, (whole, key: string) => (isSecretKey(key) ? ` ${key}: ${REDACTED} ` : whole))\n .replace(/<[^>]*>/g, ' ')\n .split(REDACTED)\n .join('<redacted>')\n .replace(/&(#x[0-9a-f]+|#[0-9]+|amp|lt|gt|quot|apos);/gi, (whole, e: string) =>\n e[0] === '#'\n ? String.fromCodePoint(e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10))\n : (XML_ENTITIES[e.toLowerCase()] ?? whole),\n );\n}\n\nfunction flattenJson(value: unknown, key = ''): string {\n if (typeof value === 'string') return key !== '' && isSecretKey(key) && value !== '' ? '<redacted>' : value;\n if (Array.isArray(value)) return value.map((v) => flattenJson(v, key)).join('; ');\n if (value !== null && typeof value === 'object') {\n return Object.entries(value).map(([k, v]) => `${k}: ${flattenJson(v, k)}`).join(', ');\n }\n return String(value);\n}\n\n/**\n * Factory for the live Mirth transport client.\n */\nexport function createMirthClient(config: ClientConfig): MirthClientExt {\n return new MirthClientImpl(config);\n}\n","/**\n * Find secrets that the key-name rules in `templatize` miss: credentials\n * embedded in URLs and connection strings, authorization headers, password\n * assignments in scripts, private keys and well-known token formats.\n *\n * Findings are reported by location and kind only; a secret value is never\n * printed. `extract` replaces just the secret part of each string with an\n * `{{env:NAME}}` placeholder, so the surrounding script or URL stays readable.\n */\nimport { createHash } from 'node:crypto';\n\nimport { CHANNEL_SCRIPT_KEYS, CODE_KEYS, type CanonicalConfig } from '../types.js';\nimport { derivedName, hasPlaceholder, isSecretKey, mapLeaves, placeholder, type Env, type Leaf } from './index.js';\n\nexport type SecretKind =\n | 'private-key'\n | 'url-credentials'\n | 'connection-string'\n | 'authorization-header'\n | 'db-connection-call'\n | 'assignment'\n | 'setter-call'\n | 'aws-access-key'\n | 'jwt'\n | 'github-token'\n | 'slack-token';\n\n/** A secret's position in a string. */\ninterface Span {\n start: number;\n end: number;\n}\n\ninterface Rule {\n kind: SecretKind;\n /** Suffix for the env variable name. */\n suffix: string;\n /** `script`: the value is JavaScript (a step, template or channel script). */\n spans(value: string, script: boolean): Span[];\n}\n\n/** Spans of capture group `group` (0 = whole match) of every match of `re`. */\nfunction regexSpans(re: RegExp, group: number): (value: string) => Span[] {\n return (value) => {\n const out: Span[] = [];\n for (const m of value.matchAll(re)) {\n const secret = m[group];\n if (secret === undefined) continue;\n // The secret is the last occurrence of its text within the match.\n const start = m.index + m[0].lastIndexOf(secret);\n out.push({ start, end: start + secret.length });\n }\n return out;\n };\n}\n\n/**\n * The fourth argument of `createDatabaseConnection(driver, url, user, password)`\n * when it is a string literal. Arguments are split at top-level commas, so\n * calls like `$('driver')` in earlier arguments don't throw it off.\n */\nfunction dbConnectionSpans(value: string): Span[] {\n const out: Span[] = [];\n for (const m of value.matchAll(/createDatabaseConnection\\s*\\(/g)) {\n let depth = 0;\n let quote: string | null = null;\n let argStart = m.index + m[0].length;\n const args: Span[] = [];\n for (let i = argStart; i < value.length; i += 1) {\n const c = value[i]!;\n if (quote) {\n if (c === '\\\\') i += 1;\n else if (c === quote) quote = null;\n continue;\n }\n if (c === '\"' || c === \"'\") quote = c;\n else if (c === '(' || c === '[' || c === '{') depth += 1;\n else if ((c === ')' || c === ']' || c === '}') && depth > 0) depth -= 1;\n else if ((c === ',' && depth === 0) || c === ')') {\n args.push({ start: argStart, end: i });\n argStart = i + 1;\n if (c === ')') break;\n }\n }\n const pw = args[3];\n if (!pw) continue;\n const literal = /^\\s*([\"'])(.+)\\1\\s*$/s.exec(value.slice(pw.start, pw.end));\n if (literal) {\n const start = value.indexOf(literal[2]!, pw.start);\n out.push({ start, end: start + literal[2]!.length });\n }\n }\n return out;\n}\n\n/**\n * The tail of `name = 'literal'` / `name: \"literal\"`: an optional default-value\n * prefix (`name || `, `name ?? `), then a quoted literal of 4+ characters on one\n * line. Braces are excluded so `${var}` templates and placeholders don't match. A\n * literal with spaces must also hold a digit or symbol, so prose such as\n * `secret = 'Not configured yet'` is not a secret.\n */\nconst ASSIGNED = String.raw`[\"']?\\s*[:=]\\s*(?:[\\w$.[\\]'\"]+\\s*(?:\\|\\||\\?\\?)\\s*)?([\"'])((?=\\S)(?:[^\"'{}\\s]{4,}|(?=[^\"'{}\\n]*[0-9@#$%^&*+=~|\\\\/<>_])[^\"'{}\\n]{4,}))\\1`;\n\n/** A connection-string value: up to the next delimiter, without surrounding spaces. */\nconst CONN_VALUE = String.raw`([^;&'\"\\s](?:[^;&'\"\\n]*[^;&'\"\\s])?)`;\n\n/**\n * String literals and comments of a script: where a connection string can\n * appear as text. Regex literals are not recognised, so a quote inside one\n * can shift what counts as a literal.\n */\nfunction textSpans(code: string): Span[] {\n const out: Span[] = [];\n let i = 0;\n while (i < code.length) {\n const c = code[i]!;\n const next = code[i + 1];\n if (c === '/' && (next === '/' || next === '*')) {\n const close = next === '/' ? code.indexOf('\\n', i) : code.indexOf('*/', i + 2);\n const end = close < 0 ? code.length : close;\n out.push({ start: i + 2, end });\n i = end + 2;\n } else if (c === '\"' || c === \"'\" || c === '`') {\n let j = i + 1;\n while (j < code.length && code[j] !== c && (c === '`' || code[j] !== '\\n')) j += code[j] === '\\\\' ? 2 : 1;\n out.push({ start: i + 1, end: Math.min(j, code.length) });\n i = j + 1;\n } else {\n i += 1;\n }\n }\n return out;\n}\n\n/** Apply `spans` to a whole data value, but only to the text parts of a script. */\nfunction outsideCode(spans: (value: string) => Span[]): (value: string, script: boolean) => Span[] {\n return (value, script) =>\n script\n ? textSpans(value).flatMap((t) => spans(value.slice(t.start, t.end)).map((s) => ({ start: s.start + t.start, end: s.end + t.start })))\n : spans(value);\n}\n\n// Earlier rules win where spans overlap: a private key block may contain text\n// other rules match, and `token = 'ghp_…'` is one secret, not two.\nconst RULES: Rule[] = [\n {\n kind: 'private-key',\n suffix: 'PRIVATE_KEY',\n spans: regexSpans(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, 0),\n },\n { kind: 'aws-access-key', suffix: 'AWS_ACCESS_KEY', spans: regexSpans(/\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b/g, 0) },\n { kind: 'jwt', suffix: 'TOKEN', spans: regexSpans(/\\beyJ[A-Za-z0-9_-]{8,}\\.eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}/g, 0) },\n { kind: 'github-token', suffix: 'TOKEN', spans: regexSpans(/\\b(?:ghp|gho|ghs|ghu|github_pat)_[A-Za-z0-9_]{20,}/g, 0) },\n { kind: 'slack-token', suffix: 'TOKEN', spans: regexSpans(/\\bxox[abprs]-[A-Za-z0-9-]{10,}/g, 0) },\n // user:password@host. The user part stops at ';', '?' and '&' so a JDBC\n // parameter like `user=svc@srv` is not mistaken for credentials.\n { kind: 'url-credentials', suffix: 'PASSWORD', spans: regexSpans(/\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s:/@'\";?&]+:([^\\s@'\"/;?&]+)@/gi, 1) },\n // Drivers trim around `=` and the value, so spaces are allowed there. In a\n // script only string literals and comments are searched: `pwd=$('x')` is code.\n {\n kind: 'connection-string',\n suffix: 'PASSWORD',\n spans: outsideCode(regexSpans(new RegExp(String.raw`[;?&]\\s*(?:password|pwd)\\s*=\\s*${CONN_VALUE}`, 'gi'), 1)),\n },\n // Leading the whole value (`Password=…;Server=…`), when another key=value follows.\n {\n kind: 'connection-string',\n suffix: 'PASSWORD',\n spans: outsideCode(regexSpans(new RegExp(String.raw`^\\s*(?:password|pwd)\\s*=\\s*${CONN_VALUE}(?=\\s*;\\s*[\\w ]+=)`, 'gi'), 1)),\n },\n // Case-sensitive, and the credential must contain a digit or a base64/token\n // symbol, so prose like \"Basic authentication\" does not match.\n {\n kind: 'authorization-header',\n suffix: 'TOKEN',\n spans: regexSpans(/\\b(?:Basic|Bearer)\\s+((?=[A-Za-z0-9+/=._~-]*[0-9+/=])[A-Za-z0-9+/=._~-]{12,})/g, 1),\n },\n { kind: 'db-connection-call', suffix: 'DB_PASSWORD', spans: dbConnectionSpans },\n // name = 'literal' where the name ends in a secret word: password, dbPassword,\n // db_password, DB_PASSWORD, apiKey, authToken… (not tokenizer, not ==).\n // Also the default-value idiom: apiKey = apiKey || 'literal' (or ??).\n {\n kind: 'assignment',\n suffix: 'PASSWORD',\n spans: regexSpans(new RegExp(`(?<![\\\\w$])[\\\\w$]*?(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?key|token)${ASSIGNED}`, 'gi'), 2),\n },\n // `pass` as a whole name or a word boundary within one (pass, dbPass,\n // DB_PASS, sftp_pass), case-sensitive so bypass and compass don't match,\n // and not after words that make it an ordinary noun (byPass, firstPass).\n {\n kind: 'assignment',\n suffix: 'PASSWORD',\n spans: regexSpans(new RegExp(`(?<![\\\\w$])(?:pass|PASS|[\\\\w$]*[a-z0-9](?<!(?:[bB]y|[fF]irst|[sS]econd|[tT]hird|[lL]ast|[nN]ext|[oO]ne|[sS]ingle|[mM]ulti|[eE]very|[cC]om|[sS]ur|[oO]ver|[uU]nder))(?:Pass|PASS)|[\\\\w$]*_(?:pass|PASS))${ASSIGNED}`, 'g'), 2),\n },\n // conn.setPassword('literal'), props.setApiKey(\"literal\")…\n {\n kind: 'setter-call',\n suffix: 'PASSWORD',\n spans: regexSpans(/\\bset[A-Za-z]*(?:Password|Passwd|Passphrase|Secret|Token|ApiKey)\\s*\\(\\s*([\"'])([^\"'\\n]{4,})\\1\\s*\\)/g, 2),\n },\n];\n\n/** A Mirth `${variable}` or one of our placeholders is a reference, not a secret. */\nfunction isReference(secret: string): boolean {\n return secret.includes('${') || hasPlaceholder(secret);\n}\n\nexport interface Finding {\n location: string;\n kind: SecretKind;\n /** Where it is, for people: enclosing channel/connector names and the field. */\n where: string;\n /** Identifies the surrounding text (secret removed), for allow entries. */\n context: string;\n}\n\n/**\n * A known false positive. `context` ties it to the surrounding text as well as\n * the location, so an entry for a transformer step at index 2 stops matching\n * if a different step moves into that index.\n */\nexport interface AllowEntry {\n location: string;\n kind: SecretKind;\n context: string;\n note?: string;\n}\n\nexport type ScanMode = 'find' | 'extract' | 'redact';\n\nexport interface ScanResult {\n config: CanonicalConfig;\n findings: Finding[];\n /** extract mode: values for the env file (only ones it doesn't already hold). Never print these. */\n envUpdates: Record<string, string>;\n}\n\ninterface Hit extends Span {\n rule: Rule;\n}\n\n/** Every secret span in `value`, earlier rules winning overlaps, in position order. */\nfunction hitsIn(value: string, script = false): Hit[] {\n const taken: Hit[] = [];\n for (const rule of RULES) {\n for (const span of rule.spans(value, script)) {\n if (span.end <= span.start || isReference(value.slice(span.start, span.end))) continue;\n if (taken.some((t) => span.start < t.end && t.start < span.end)) continue;\n taken.push({ ...span, rule });\n }\n }\n return taken.sort((a, b) => a.start - b.start);\n}\n\nconst SCRIPT_KEYS: ReadonlySet<string> = new Set<string>([...CODE_KEYS, ...CHANNEL_SCRIPT_KEYS]);\n\n/** Script leaves: step, template and channel code, and the global scripts. */\nfunction isScript(leaf: Leaf): boolean {\n return SCRIPT_KEYS.has(leaf.key) || leaf.section === 'globalScripts';\n}\n\n/** `value` with every secret a rule recognises replaced by a marker, for messages. */\nexport function redactSecretsInText(text: string): string {\n // Credential fields echoed as JSON (\"passcode\": \"…\") or XML (<keyPW>…</keyPW>),\n // by the field names `templatize` extracts, then the value rules.\n const value = text\n .replace(/(\"([\\w.-]+)\"\\s*:\\s*\")((?:[^\"\\\\]|\\\\.)+)\"/g, (whole, head: string, key: string) => (isSecretKey(key) ? `${head}<redacted>\"` : whole))\n .replace(/<([\\w.:-]+)>([^<]+)<\\/\\1>/g, (whole, key: string) => (isSecretKey(key) ? `<${key}><redacted></${key}>` : whole));\n let out = '';\n let at = 0;\n for (const h of hitsIn(value)) {\n out += `${value.slice(at, h.start)}<redacted ${h.rule.kind}>`;\n at = h.end;\n }\n return out + value.slice(at);\n}\n\n/** Hash of the string with every secret removed: stable while its text is, and holds no secret. */\nfunction contextOf(value: string, hits: Hit[]): string {\n let redacted = '';\n let at = 0;\n for (const h of hits) {\n redacted += `${value.slice(at, h.start)}\\u0000${h.rule.kind}\\u0000`;\n at = h.end;\n }\n redacted += value.slice(at);\n return createHash('sha256').update(redacted).digest('hex').slice(0, 16);\n}\n\n/**\n * Scan every string leaf. `find` reports only; `extract` swaps each secret\n * for a placeholder and returns the values; `redact` swaps it for a marker\n * (for display, e.g. in `diff`).\n */\nexport function scanSecrets(config: CanonicalConfig, opts: { mode: ScanMode; allow?: AllowEntry[]; env?: Env }): ScanResult {\n const allowed = new Set((opts.allow ?? []).map((a) => `${a.location}#${a.kind}#${a.context}`));\n const env = opts.env ?? {};\n const findings: Finding[] = [];\n const envUpdates: Record<string, string> = {};\n const assigned = new Map<string, string>(); // name -> value, this run\n\n // Names placeholders already use belong to their locations; each new\n // placeholder gets its own name, so rotating one secret never changes another.\n const inUse = new Set<string>();\n mapLeaves(config, (value) => {\n for (const m of value.matchAll(/\\{\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}\\}/g)) inUse.add(m[1]!);\n return value;\n });\n const nameFor = (leaf: Leaf, rule: Rule, value: string): string => {\n const base = `${derivedName(leaf)}__${rule.suffix}`;\n for (let n = 1; ; n += 1) {\n const name = n === 1 ? base : `${base}_${n}`;\n if (assigned.has(name) || inUse.has(name)) continue;\n if (env[name] === undefined || env[name] === value) {\n assigned.set(name, value);\n // A value the environment already holds (the file, or CI's process\n // environment) is not written to the file again.\n if (env[name] !== value) envUpdates[name] = value;\n return name;\n }\n }\n };\n\n const out = mapLeaves(config, (value, leaf) => {\n const hits = hitsIn(value, isScript(leaf));\n if (hits.length === 0) return value;\n const context = contextOf(value, hits);\n let result = '';\n let at = 0;\n for (const h of hits) {\n if (allowed.has(`${leaf.location}#${h.rule.kind}#${context}`)) continue;\n findings.push({ location: leaf.location, kind: h.rule.kind, where: [...leaf.labels, leaf.key].join(' › '), context });\n if (opts.mode === 'find') continue;\n const secret = value.slice(h.start, h.end);\n const replacement = opts.mode === 'extract' ? placeholder(nameFor(leaf, h.rule, secret)) : `<redacted ${h.rule.kind}>`;\n result += value.slice(at, h.start) + replacement;\n at = h.end;\n }\n return opts.mode === 'find' ? value : result + value.slice(at);\n });\n\n return { config: out, findings, envUpdates };\n}\n\n/**\n * Known secret values that still appear verbatim somewhere in `config`: a\n * repeat no rule recognised (a default argument, a URL fragment). Values\n * shorter than 8 characters are skipped; short ones such as a database name\n * reused as a password match too much ordinary text.\n */\nexport function findEchoes(config: CanonicalConfig, secrets: Env): Array<{ name: string; where: string }> {\n const values = Object.entries(secrets).filter((e): e is [string, string] => typeof e[1] === 'string' && e[1].length >= 8);\n const out: Array<{ name: string; where: string }> = [];\n if (values.length === 0) return out;\n mapLeaves(config, (value, leaf) => {\n for (const [name, secret] of values) {\n if (value.includes(secret)) out.push({ name, where: [...leaf.labels, leaf.key].join(' › ') });\n }\n return value;\n });\n return out;\n}\n\nexport function formatFindings(findings: Finding[]): string {\n return findings\n .map((f) => ` ${f.kind.padEnd(20)} ${f.where}\\n ${''.padEnd(20)} at ${f.location} context ${f.context}`)\n .join('\\n');\n}\n","/**\n * Keep secrets and per-environment values out of the working tree.\n *\n * A string in the tree may contain `{{env:NAME}}` placeholders. `render`\n * replaces them from an environment (a `.env` file plus `process.env`) before\n * anything is sent to Mirth or written as XML. `templatize` goes the other way\n * on `pull`/`explode`: it swaps credential values for placeholders, returning\n * the values so the caller can store them in `.env`.\n *\n * The syntax is not Mirth's `${...}`, which connector fields already use for\n * Velocity variables (`${message.encodedData}`).\n */\nimport type { CanonicalConfig, Json } from '../types.js';\n\nexport type Env = Readonly<Record<string, string | undefined>>;\n\nconst PLACEHOLDER = /\\{\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}\\}/g;\n\n/**\n * Credential-bearing keys: `password`, `smtpPassword`, `passPhrase`, `apiToken`,\n * and the DICOM connector's `passcode`, `keyPW`, `keyStorePW`, `trustStorePW`.\n */\nconst SECRET_KEY = /(password|passwd|passphrase|passcode|secret|token|pw|pwd|(?:api|access|secret|private)[_-]?key)$/i;\n\n/** Mirth's configuration-map entry value holder (XML and live shapes). */\nconst CONFIG_PROPERTY = 'com.mirth.connect.util.ConfigurationProperty';\n\nexport function placeholder(name: string): string {\n return `{{env:${name}}}`;\n}\n\nexport function hasPlaceholder(value: string): boolean {\n PLACEHOLDER.lastIndex = 0;\n return PLACEHOLDER.test(value);\n}\n\n/** Fill every placeholder in `value`; names with no value are collected in `missing`. */\nfunction fill(value: string, env: Env, missing: Set<string>): string {\n return value.replace(PLACEHOLDER, (whole, name: string) => {\n const v = env[name];\n if (v === undefined) {\n missing.add(name);\n return whole;\n }\n return v;\n });\n}\n\n/**\n * Replace every placeholder in the config. Throws, naming every missing\n * variable, rather than sending a literal `{{env:…}}` to a server.\n */\nexport function render(config: CanonicalConfig, env: Env): CanonicalConfig {\n const missing = new Set<string>();\n const walk = (node: Json): Json => {\n if (typeof node === 'string') return fill(node, env, missing);\n if (Array.isArray(node)) return node.map(walk);\n if (node && typeof node === 'object') {\n const out: Record<string, Json> = {};\n for (const [k, v] of Object.entries(node)) out[k] = walk(v);\n return out;\n }\n return node;\n };\n const out = walk(config) as CanonicalConfig;\n if (missing.size > 0) {\n throw new Error(\n `missing values for ${[...missing].sort().join(', ')} (set them in the env file or the environment)`,\n );\n }\n return out;\n}\n\n// --- locations -------------------------------------------------------------\n\ntype Segment = string;\n\n/**\n * A stable address for a value: array elements are identified by `id` or\n * `metaDataId` when they have one, and configuration-map entries by their key,\n * so removing, reordering or adding elements does not move an existing\n * placeholder to a different value.\n */\nfunction elementSegment(el: Json, index: number): Segment {\n if (el && typeof el === 'object' && !Array.isArray(el)) {\n const id = el['id'] ?? el['metaDataId'];\n if (typeof id === 'string' || typeof id === 'number') return `[${String(id)}]`;\n const mapKey = CONFIG_PROPERTY in el ? configMapKeyOf(el) : undefined;\n if (mapKey !== undefined) return `[${mapKey}]`;\n }\n return `[${index}]`;\n}\n\nfunction configMapKeyOf(entry: Record<string, Json>): string | undefined {\n const key = entry['string'];\n if (typeof key === 'string') return key;\n return Array.isArray(key) && typeof key[0] === 'string' ? key[0] : undefined;\n}\n\nexport interface Leaf {\n location: string;\n key: string;\n /** `name`s of enclosing objects (channel, connector), outermost first. */\n labels: string[];\n /** Top-level section the leaf lives in (`serverSettings`, `channels`, …). */\n section: string;\n /** The configuration-map key when this leaf is a map entry's value. */\n configMapKey?: string;\n}\n\n/** Visit every string leaf, allowing the visitor to replace it. */\nexport function mapLeaves(config: CanonicalConfig, visit: (value: string, leaf: Leaf) => string): CanonicalConfig {\n const walk = (node: Json, key: string, path: Segment[], labels: string[], section: string, cmKey?: string): Json => {\n if (typeof node === 'string') {\n return visit(node, { location: path.join('/'), key, labels, section, configMapKey: cmKey });\n }\n if (Array.isArray(node)) {\n return node.map((el, i) => walk(el, key, [...path.slice(0, -1), `${path[path.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));\n }\n if (node && typeof node === 'object') {\n const name = node['name'];\n const inner = typeof name === 'string' && name.trim() !== '' ? [...labels, name] : labels;\n // A configuration-map entry: { string: key | [key], ConfigurationProperty: { value, comment } }.\n const mapKey = section === 'configurationMap' && CONFIG_PROPERTY in node ? configMapKeyOf(node) : cmKey;\n const out: Record<string, Json> = {};\n for (const [k, v] of Object.entries(node)) {\n out[k] = walk(v, k, [...path, k], inner, section || k, mapKey);\n }\n return out;\n }\n return node;\n };\n return walk(config, '', [], [], '') as CanonicalConfig;\n}\n\n/** A field name that holds a credential (see {@link SECRET_KEY}). */\nexport function isSecretKey(key: string): boolean {\n return SECRET_KEY.test(key);\n}\n\nfunction isSecret(leaf: Leaf): boolean {\n if (leaf.section === 'configurationMap') return leaf.configMapKey !== undefined && leaf.key === 'value';\n return SECRET_KEY.test(leaf.key);\n}\n\nexport function envName(parts: string[]): string {\n return parts\n .map((p) => p.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, ''))\n .filter(Boolean)\n .join('__')\n .replace(/^(?=[0-9])/, '_');\n}\n\nexport function derivedName(leaf: Leaf): string {\n if (leaf.configMapKey !== undefined) return envName(['CONFIG_MAP', leaf.configMapKey]);\n const context = leaf.labels.length > 0 ? leaf.labels : [leaf.section];\n return envName([...context, leaf.key]);\n}\n\n/**\n * Replace every literal credential (by field name, as `templatize` finds them)\n * with a marker, for display. `diff` uses it so a password typed into the\n * tree by hand is never printed.\n */\nexport function redactKnownSecrets(config: CanonicalConfig): CanonicalConfig {\n return mapLeaves(config, (value, leaf) => (isSecret(leaf) && value !== '' && !hasPlaceholder(value) ? '<redacted>' : value));\n}\n\n// --- templatize ------------------------------------------------------------\n\nexport interface TemplatizeResult {\n config: CanonicalConfig;\n /** Values to write to the env file (new or changed on the server). Never print these. */\n envUpdates: Record<string, string>;\n /** Human-readable notes: placeholders dropped, secrets updated from the server. */\n notes: string[];\n}\n\n/** Placeholder-bearing strings in a previously pulled (un-rendered) tree, by location. */\nfunction templatesOf(config: CanonicalConfig | null): Map<string, string> {\n const out = new Map<string, string>();\n if (config) {\n mapLeaves(config, (value, leaf) => {\n if (hasPlaceholder(value)) out.set(leaf.location, value);\n return value;\n });\n }\n return out;\n}\n\n/**\n * Read `value` as `template` with its placeholders filled in: returns each\n * placeholder's value, or null if the text around them differs. A name used\n * twice must match the same text both times.\n */\nfunction matchTemplate(template: string, value: string): Map<string, string> | null {\n const names: string[] = [];\n let pattern = '^';\n let at = 0;\n for (const m of template.matchAll(PLACEHOLDER)) {\n pattern += template.slice(at, m.index).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const seen = names.indexOf(m[1]!);\n if (seen >= 0) {\n pattern += `\\\\${seen + 1}`;\n } else {\n names.push(m[1]!);\n pattern += '([\\\\s\\\\S]*?)';\n }\n at = m.index + m[0].length;\n }\n pattern += `${template.slice(at).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}$`;\n const match = new RegExp(pattern).exec(value);\n return match ? new Map(names.map((n, i) => [n, match[i + 1]!])) : null;\n}\n\n/**\n * Replace credentials in a freshly fetched config with placeholders.\n *\n * `previous` is the existing tree (un-rendered), so placeholders the user\n * added by hand survive a re-pull as long as they still render to what the\n * server holds. `env` is what they render with.\n */\nexport function templatize(remote: CanonicalConfig, previous: CanonicalConfig | null, env: Env): TemplatizeResult {\n const templates = templatesOf(previous);\n const envUpdates: Record<string, string> = {};\n const notes: string[] = [];\n const assigned = new Map<string, string>(); // name -> value, this run\n const reserved = new Set<string>();\n for (const t of templates.values()) {\n for (const m of t.matchAll(PLACEHOLDER)) reserved.add(m[1]!);\n }\n\n /** A name no location uses yet, bound to `value`. Placeholders are never shared between locations. */\n const fresh = (base: string, value: string): string => {\n let name = base;\n for (let n = 2; assigned.has(name) || reserved.has(name); n += 1) name = `${base}_${n}`;\n assigned.set(name, value);\n if (env[name] !== value) envUpdates[name] = value;\n return name;\n };\n\n /**\n * Bind this location's placeholder values. A name another location already\n * holds with a different value (a shared placeholder whose credentials have\n * diverged) is split off under a new name, so rotating one credential never\n * changes another.\n */\n const bind = (template: string, values: Map<string, string>, rotated: boolean): string => {\n let out = template;\n for (const [name, value] of values) {\n const bound = assigned.get(name);\n if (bound !== undefined && bound !== value) {\n reserved.delete(name);\n const renamed = fresh(name, value);\n out = out.split(placeholder(name)).join(placeholder(renamed));\n notes.push(`${renamed}: split from ${name}, which another location holds with a different value`);\n continue;\n }\n assigned.set(name, value);\n if (env[name] !== value) {\n envUpdates[name] = value;\n if (rotated) notes.push(`${name}: server value differs from the env file; env file updated`);\n }\n }\n return out;\n };\n const envValues = (template: string): Map<string, string> =>\n new Map([...template.matchAll(PLACEHOLDER)].map((m) => [m[1]!, env[m[1]!]!] as const));\n\n const config = mapLeaves(remote, (value, leaf) => {\n const template = templates.get(leaf.location);\n if (template !== undefined) {\n const missing = new Set<string>();\n if (fill(template, env, missing) === value && missing.size === 0) return bind(template, envValues(template), false);\n // Same text around the placeholders, new values (a rotated secret):\n // keep the template and take the new values.\n const captured = matchTemplate(template, value);\n if (captured) return bind(template, captured, true);\n // Text edited elsewhere, secrets unchanged: put the placeholders back\n // where their values still appear. Lossless, since rendering restores\n // exactly this text.\n let restored = value;\n for (const m of template.matchAll(PLACEHOLDER)) {\n const v = env[m[1]!];\n if (v !== undefined && v.length >= 4) restored = restored.split(v).join(placeholder(m[1]!));\n }\n if (restored !== value) return bind(restored, envValues(restored), false);\n notes.push(`${leaf.location}: placeholder no longer matches the server; replaced with the server value`);\n return value;\n }\n if (isSecret(leaf) && value !== '' && !hasPlaceholder(value)) {\n return placeholder(fresh(derivedName(leaf), value));\n }\n return value;\n });\n\n return { config, envUpdates, notes };\n}\n","import type { CanonicalConfig } from '../types.js';\n\nconst object = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** Validate the live API envelope and core collections without dropping plugin fields. */\nexport function liveConfiguration(payload: unknown): CanonicalConfig {\n const bad = (detail: string): never => { throw new Error(`invalid server configuration response: ${detail}; nothing should be written from this snapshot`); };\n if (!object(payload) || Object.keys(payload).length !== 1 || !('serverConfiguration' in payload)) bad('expected the serverConfiguration wrapper');\n const config = (payload as Record<string, unknown>)['serverConfiguration'];\n if (!object(config)) bad('expected a configuration object');\n const c = config as Record<string, unknown>;\n if (typeof c['@version'] !== 'string' || !/^\\d+\\.\\d+(?:\\.\\d+)*(?:[-+][A-Za-z0-9.-]+)?$/.test(c['@version'])) bad('missing or invalid engine version');\n if (!('channels' in c)) bad('missing channels collection');\n const collection = (container: unknown, key: string, where: string): Record<string, unknown>[] => {\n if (container == null || container === '') return [];\n if (!object(container)) bad(`invalid ${where} collection`);\n if (!(key in (container as Record<string, unknown>)) && Object.keys(container as object).some(k => !k.startsWith('@'))) bad(`missing resource list in ${where}`);\n const raw = (container as Record<string, unknown>)[key];\n if (raw == null || raw === '') return [];\n const items = Array.isArray(raw) ? raw : [raw];\n for (const item of items) {\n if (!object(item) || typeof item.id !== 'string' || !item.id.trim() || typeof item.name !== 'string' || !item.name.trim()) bad(`invalid resource in ${where}`);\n if ('revision' in item && (!Number.isSafeInteger(item.revision) || Number(item.revision) < 0)) bad(`invalid revision in ${where}`);\n }\n return items as Record<string, unknown>[];\n };\n collection(c.channels, 'channel', 'channels');\n if ('codeTemplateLibraries' in c) {\n for (const library of collection(c.codeTemplateLibraries, 'codeTemplateLibrary', 'code template libraries')) {\n if ('codeTemplates' in library) collection(library.codeTemplates, 'codeTemplate', 'code templates');\n }\n }\n if ('channelGroups' in c) collection(c.channelGroups, 'channelGroup', 'channel groups');\n return c as CanonicalConfig;\n}\n"],"mappings":";AAkCO,SAAS,UAAU,GAA0B;AAClD,SACE,OAA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,WAAW,GAAG,EAAG,QAAO;AAErC,MAAI,qBAAqB,KAAK,OAAO,EAAG,QAAO;AAE/C,QAAM,WAAW;AACjB,SAAO,QACJ,QAAQ,4BAA4B,CAAC,OAAO,QAAiB,YAAY,GAAG,IAAI,IAAI,GAAG,KAAK,QAAQ,MAAM,KAAM,EAChH,QAAQ,YAAY,GAAG,EACvB,MAAM,QAAQ,EACd,KAAK,YAAY,EACjB;AAAA,IAAQ;AAAA,IAAiD,CAAC,OAAO,MAChE,EAAE,CAAC,MAAM,MACL,OAAO,cAAc,EAAE,CAAC,MAAM,OAAO,EAAE,CAAC,MAAM,MAAM,SAAS,EAAE,MAAM,CAAC,GAAG,EAAE,IAAI,SAAS,EAAE,MAAM,CAAC,GAAG,EAAE,CAAC,IACtG,aAAa,EAAE,YAAY,CAAC,KAAK;AAAA,EACxC;AACJ;AAEA,SAAS,YAAY,OAAgB,MAAM,IAAY;AACrD,MAAI,OAAO,UAAU,SAAU,QAAO,QAAQ,MAAM,YAAY,GAAG,KAAK,UAAU,KAAK,eAAe;AACtG,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,CAAC,MAAM,YAAY,GAAG,GAAG,CAAC,EAAE,KAAK,IAAI;AAChF,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,KAAK,YAAY,GAAG,CAAC,CAAC,EAAE,EAAE,KAAK,IAAI;AAAA,EACtF;AACA,SAAO,OAAO,KAAK;AACrB;AAKO,SAAS,kBAAkB,QAAsC;AACtE,SAAO,IAAI,gBAAgB,MAAM;AACnC;","names":["readFile","readFile","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/xml/index.ts","../src/explode/index.ts","../src/json.ts","../src/client/index.ts","../src/secrets/detect.ts","../src/secrets/index.ts","../src/client/validate.ts"],"sourcesContent":["/**\n * Shared contracts for channelvault.\n *\n * The whole tool is organized around a single in-memory representation called\n * the **canonical config**: a plain JSON object tree that mirrors Mirth's\n * `serverConfiguration` document. Two adapters produce/consume it:\n *\n * - XML adapter (src/xml): backup .xml <-> canonical (dev / offline path)\n * - Mirth client (src/client): live server <-> canonical (GET/PUT /server/configuration)\n *\n * The explode engine (src/explode) projects a canonical config onto a\n * git-friendly directory tree and reverses it, with embedded JavaScript pulled\n * out into sidecar `.js` files.\n */\n\n/** A JSON value as produced by the XML adapter or the live API. */\nexport type Json = string | number | boolean | null | Json[] | { [k: string]: Json };\n\n/** A canonical config object (the `serverConfiguration` payload, unwrapped). */\nexport type CanonicalConfig = { [k: string]: Json };\n\n/**\n * Marker left in a `*.json` file in place of an extracted script/code leaf.\n *\n * During explode, a code-bearing string leaf (e.g. a transformer step's\n * `script`, or a code template's `code`) is written to a sidecar `.js` file and\n * the original string is replaced, in place, with `{ \"@file\": \"<relpath>\" }`.\n * During implode, any object whose only key is `@file` is replaced by the text\n * content of that file. The path is relative to the JSON file holding the marker.\n */\nexport interface FileRef {\n '@file': string;\n}\n\nexport function isFileRef(v: unknown): v is FileRef {\n return (\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n Object.keys(v).length === 1 &&\n typeof (v as Record<string, unknown>)['@file'] === 'string'\n );\n}\n\n/**\n * The set of leaf element keys whose string values are treated as JavaScript\n * and extracted to sidecar `.js` files. Detection is by key name plus a\n * non-trivial-content check (see explode engine).\n */\nexport const CODE_KEYS = ['script', 'code'] as const;\n\n/**\n * Channel-level script keys that live directly on a channel object (no nesting).\n * Extracted into `<channel>/scripts/<name>.js`.\n */\nexport const CHANNEL_SCRIPT_KEYS = [\n 'preprocessingScript',\n 'postprocessingScript',\n 'deployScript',\n 'undeployScript',\n] as const;\n\n// --- XML adapter contract -------------------------------------------------\n\nexport interface XmlAdapter {\n /** Parse a Mirth backup XML string into a canonical config. */\n parse(xml: string): CanonicalConfig;\n /** Serialize a canonical config back to Mirth backup XML. */\n build(config: CanonicalConfig): string;\n}\n\n// --- Explode engine contract ----------------------------------------------\n\nexport interface ExplodeOptions {\n /** Absolute path to the working tree root. */\n root: string;\n}\n\nexport interface ExplodeEngine {\n /** Write a canonical config out as a directory tree under `root`. */\n explode(config: CanonicalConfig, opts: ExplodeOptions): Promise<void>;\n /** Read a directory tree under `root` back into a canonical config. */\n implode(opts: ExplodeOptions): Promise<CanonicalConfig>;\n}\n\n// --- Mirth client contract ------------------------------------------------\n\nexport interface ClientConfig {\n host: string;\n port: number;\n username: string;\n password: string;\n /** default true */\n https?: boolean;\n /** default false; set true for self-signed certs */\n disableTlsCheck?: boolean;\n /** SHA-256 of the only certificate accepted, 64 lowercase hex digits; replaces CA verification. */\n tlsFingerprint?: string;\n /**\n * default false. Put the server's response body in error messages. A body\n * can echo the credentials that were sent; it is decoded and has credential\n * fields redacted, but the caller must still scrub known secret values.\n */\n includeResponseBodies?: boolean;\n}\n\nexport interface ApiError {\n status: number;\n statusText: string;\n message: string;\n body?: unknown;\n}\n\nexport interface ApiResponse<T> {\n data: T | null;\n error: ApiError | null;\n}\n\nexport interface MirthClient {\n login(): Promise<void>;\n logout(): Promise<void>;\n isAuthenticated(): boolean;\n /** GET /server/configuration -> canonical config (whole-server snapshot). */\n getServerConfiguration(): Promise<CanonicalConfig>;\n /** PUT /server/configuration <- canonical config. */\n putServerConfiguration(config: CanonicalConfig): Promise<void>;\n}\n","/**\n * XML canonical adapter for Mirth Connect \"Backup Config\" documents.\n *\n * Converts a Mirth `serverConfiguration` XML document to/from the canonical\n * config (a plain JSON object tree). `fast-xml-parser` v5 does the tokenizing in\n * its order-preserving mode; the conversion to the canonical object shape and\n * the serializer are ours, because fxp's object mode is lossy in ways a\n * round-trip test built on the same parser cannot see (it regroups interleaved\n * siblings, concatenates mixed-content text, and renames `__proto__`).\n *\n * Canonical shape (unchanged from the original fxp object-mode shape, so\n * existing exploded trees stay valid):\n *\n * - An element with no attributes and no child elements is its text, as a\n * STRING (`\"\"` when empty). Values are never coerced or trimmed: Mirth ids,\n * ports, `\"0B\"`, leading zeros and script-body whitespace all survive.\n * - Otherwise it is an object: child elements (and `#comment`) keyed by name in\n * first-appearance order, then `#text`, then attributes as `@_<name>`.\n * - Repeated names become arrays; `ALWAYS_ARRAY_TAGS` are arrays even when\n * single, so downstream code never special-cases \"one vs many\".\n * - Whitespace-only text beside child elements is indentation and is dropped.\n * - `#order` records the document order of an element's children ONLY when\n * the default order (keys in order, each array contiguous, `#text` last)\n * would differ from it — e.g. a transformer whose steps interleave\n * `JavaScriptStep` and `MapperStep`. It never appears for ordinary Mirth\n * output, and a stale hint (after hand-editing) degrades gracefully.\n *\n * Text fidelity: we own entity decode/encode. XML end-of-line handling (a\n * literal CRLF or CR in the document is a LF) and attribute-value\n * normalization (a literal tab/newline in an attribute is a space) are applied\n * as a conforming parser — Mirth's — would apply them, so the canonical value is\n * what Mirth actually reads. Characters those rules would destroy (CR, and tab\n * or newline inside attributes) are written back as character references.\n *\n * The acceptance criterion is a semantic, order-preserving round-trip:\n *\n * parse(build(parse(xml))) deep-equals parse(xml)\n *\n * plus document order of the rebuilt XML equal to the source's (see tests).\n */\nimport { XMLParser, XMLValidator } from 'fast-xml-parser';\nimport type { CanonicalConfig, Json, XmlAdapter } from '../types.js';\n\n/**\n * Well-known Mirth collection element tags that must ALWAYS be arrays, even\n * when a document contains only a single instance.\n */\nconst ALWAYS_ARRAY_TAGS: ReadonlySet<string> = new Set<string>([\n 'channel',\n 'connector',\n 'codeTemplate',\n 'codeTemplateLibrary',\n 'channelGroup',\n 'alert',\n 'rule',\n 'entry',\n 'string',\n // Fully-qualified JavaScript step / rule element names (live under <elements>).\n 'com.mirth.connect.plugins.javascriptstep.JavaScriptStep',\n 'com.mirth.connect.plugins.javascriptrule.JavaScriptRule',\n 'com.mirth.connect.plugins.mapper.MapperStep',\n 'com.mirth.connect.plugins.messagebuilder.MessageBuilderStep',\n]);\n\n/** The single top-level wrapper key of a Mirth backup document. */\nconst ROOT_KEY = 'serverConfiguration';\n\nconst TEXT_KEY = '#text';\nconst COMMENT_KEY = '#comment';\nconst CDATA_KEY = '#cdata';\n/** Document-order hint; `#` cannot start an XML name, so it cannot collide. */\nexport const ORDER_KEY = '#order';\nconst ATTR_PREFIX = '@_';\nconst ORDERED_ATTRS = ':@';\nconst INDENT = ' ';\n\n/** An fxp `preserveOrder` node: `{ <name>: children, ':@'?: attrs }`. */\ntype OrderedNode = Record<string, unknown>;\n\nfunction isWhitespaceOnly(s: string): boolean {\n return /^\\s*$/.test(s);\n}\n\n/** Named XML entities (the five predefined) -> their character. */\nconst NAMED_DECODE: Readonly<Record<string, string>> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n};\n\n/**\n * Decode XML entities in a single left-to-right pass: the five predefined named\n * entities plus decimal (` `) and hex (`
`) numeric character\n * references.\n *\n * A single non-overlapping scan is what makes `
` and `&#xd;`\n * distinguishable: `&` is consumed as one token (-> `&`) and its output is\n * not re-scanned, so the trailing `#xd;` stays literal.\n */\nfunction decodeEntities(value: string): string {\n if (!value.includes('&')) return value;\n return value.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g, (whole, body: string) => {\n if (body[0] !== '#') return NAMED_DECODE[body] ?? whole;\n const code =\n body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);\n if (!(code <= 0x10ffff)) {\n throw new Error(`XmlConfigAdapter.parse: invalid character reference ${whole}`);\n }\n return String.fromCodePoint(code);\n });\n}\n\nfunction charRef(ch: string): string {\n return `&#x${ch.charCodeAt(0).toString(16)};`;\n}\n\nconst ESCAPE: Readonly<Record<string, string>> = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\n\n/**\n * Encode text content. Escapes the same set fxp's builder did (so unchanged\n * values serialize byte-identically) and writes CR and the other C0 controls\n * except tab/LF as character references: a literal CR would be read back as LF.\n */\nfunction encodeText(value: string): string {\n // eslint-disable-next-line no-control-regex\n return value.replace(/[&<>\"'\\x00-\\x08\\x0b-\\x1f]/g, (ch) => ESCAPE[ch] ?? charRef(ch));\n}\n\n/** Encode an attribute value; tab and LF must be references there too. */\nfunction encodeAttr(value: string): string {\n // eslint-disable-next-line no-control-regex\n return value.replace(/[&<>\"'\\x00-\\x1f]/g, (ch) => ESCAPE[ch] ?? charRef(ch));\n}\n\n// --- parse -----------------------------------------------------------------\n\nfunction nodeName(node: OrderedNode): string {\n const name = Object.keys(node).find((k) => k !== ORDERED_ATTRS);\n if (name === undefined) throw new Error('XmlConfigAdapter.parse: empty node');\n return name;\n}\n\n/** Concatenated text of a `#comment` / `#cdata` node's children, undecoded. */\nfunction rawInnerText(children: unknown): string {\n return (children as OrderedNode[]).map((c) => String(c[TEXT_KEY] ?? '')).join('');\n}\n\n/** The child sequence the serializer emits for `obj` absent an `#order` hint. */\nfunction defaultOrder(obj: Record<string, Json>): string[] {\n const seq: string[] = [];\n for (const [key, value] of Object.entries(obj)) {\n if (key.startsWith(ATTR_PREFIX) || key === ORDER_KEY) continue;\n const count = Array.isArray(value) ? value.length : 1;\n for (let i = 0; i < count; i += 1) seq.push(key);\n }\n return seq;\n}\n\n/** Convert one element's ordered children + attributes to its canonical value. */\nfunction convertElement(children: OrderedNode[], attrs: Record<string, string> | undefined): Json {\n const hasElementChild = children.some((c) => {\n const n = nodeName(c);\n return n !== TEXT_KEY && n !== CDATA_KEY;\n });\n\n // Merge adjacent text/CDATA runs into text segments (CDATA is literal: no\n // entity decoding), and record the document order of what we keep.\n const groups = new Map<string, Json[]>();\n const order: string[] = [];\n const segments: string[] = [];\n let pending: string | null = null;\n const flushText = (): void => {\n if (pending === null) return;\n if (!hasElementChild || !isWhitespaceOnly(pending)) {\n segments.push(pending);\n order.push(TEXT_KEY);\n }\n pending = null;\n };\n\n for (const child of children) {\n const name = nodeName(child);\n if (name === TEXT_KEY) {\n pending = (pending ?? '') + decodeEntities(String(child[TEXT_KEY]));\n continue;\n }\n if (name === CDATA_KEY) {\n pending = (pending ?? '') + rawInnerText(child[CDATA_KEY]);\n continue;\n }\n flushText();\n // fxp renames this element to `#__proto__`; it cannot be an object key.\n if (name === '#__proto__') {\n throw new Error('XmlConfigAdapter.parse: unsupported element name <__proto__>');\n }\n const value =\n name === COMMENT_KEY\n ? rawInnerText(child[COMMENT_KEY])\n : convertElement(child[name] as OrderedNode[], child[ORDERED_ATTRS] as Record<string, string>);\n const group = groups.get(name);\n if (group) group.push(value);\n else groups.set(name, [value]);\n order.push(name);\n }\n flushText();\n\n const attrEntries = Object.entries(attrs ?? {});\n if (!hasElementChild && attrEntries.length === 0) {\n return segments.join('');\n }\n\n const obj: Record<string, Json> = {};\n for (const [name, values] of groups) {\n obj[name] = values.length > 1 || ALWAYS_ARRAY_TAGS.has(name) ? values : values[0]!;\n }\n if (segments.length === 1) obj[TEXT_KEY] = segments[0]!;\n else if (segments.length > 1) obj[TEXT_KEY] = segments;\n\n for (const [key, raw] of attrEntries) {\n if (key === `${ATTR_PREFIX}__proto__`) {\n throw new Error('XmlConfigAdapter.parse: unsupported attribute name __proto__');\n }\n // Attribute-value normalization: literal tab/LF (CRs are already LFs) read\n // as a space; character references were the way to keep them.\n obj[key] = decodeEntities(String(raw).replace(/[\\t\\n]/g, ' '));\n }\n\n const def = defaultOrder(obj);\n if (def.length !== order.length || def.some((k, i) => k !== order[i])) {\n obj[ORDER_KEY] = order;\n }\n return obj;\n}\n\nconst parser = new XMLParser({\n preserveOrder: true,\n ignoreAttributes: false,\n attributeNamePrefix: ATTR_PREFIX,\n parseTagValue: false,\n parseAttributeValue: false,\n trimValues: false,\n processEntities: false,\n commentPropName: COMMENT_KEY,\n cdataPropName: CDATA_KEY,\n});\n\n// --- build -----------------------------------------------------------------\n\n/**\n * The children of `obj` in emit order: honours an `#order` hint as far as it\n * matches the actual children, then appends anything it didn't mention in\n * default order. So adding, removing or renaming a child by hand never loses it.\n */\nfunction orderedChildren(obj: Record<string, Json>, where: string): Array<[string, Json]> {\n const queues = new Map<string, Json[]>();\n for (const [key, value] of Object.entries(obj)) {\n if (key.startsWith(ATTR_PREFIX) || key === ORDER_KEY) continue;\n queues.set(key, Array.isArray(value) ? [...value] : [value]);\n }\n const out: Array<[string, Json]> = [];\n const hint = obj[ORDER_KEY];\n if (hint !== undefined) {\n if (!Array.isArray(hint) || !hint.every((h) => typeof h === 'string')) {\n throw new Error(`XmlConfigAdapter.build: ${ORDER_KEY} under <${where}> must be an array of names`);\n }\n for (const name of hint as string[]) {\n const next = queues.get(name)?.shift();\n if (next !== undefined) out.push([name, next]);\n }\n }\n for (const [key, rest] of queues) {\n for (const value of rest) out.push([key, value]);\n }\n return out;\n}\n\nfunction scalar(value: Json): string {\n return value === null ? '' : String(value);\n}\n\nfunction serialize(name: string, value: Json, depth: number, pretty: boolean, out: string[]): void {\n const pad = pretty ? INDENT.repeat(depth) : '';\n const nl = pretty ? '\\n' : '';\n\n if (name === COMMENT_KEY) {\n const text = scalar(value);\n if (text.includes('--') || text.endsWith('-')) {\n throw new Error(`XmlConfigAdapter.build: comment text cannot contain \"--\": ${text}`);\n }\n out.push(`${pad}<!--${text}-->${nl}`);\n return;\n }\n if (name === TEXT_KEY) {\n out.push(encodeText(scalar(value)));\n return;\n }\n\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n out.push(`${pad}<${name}>${encodeText(scalar(value))}</${name}>${nl}`);\n return;\n }\n\n const attrs = Object.entries(value)\n .filter(([k]) => k.startsWith(ATTR_PREFIX))\n .map(([k, v]) => ` ${k.slice(ATTR_PREFIX.length)}=\"${encodeAttr(scalar(v))}\"`)\n .join('');\n const children = orderedChildren(value, name);\n const hasElementChild = children.some(([k]) => k !== TEXT_KEY);\n\n if (!hasElementChild) {\n const text = children.map(([, v]) => encodeText(scalar(v))).join('');\n out.push(`${pad}<${name}${attrs}>${text}</${name}>${nl}`);\n return;\n }\n\n // Mixed content can't be indented: the indentation would become part of its\n // text. Emit that element compactly.\n const mixed = children.some(([k]) => k === TEXT_KEY);\n const childPretty = pretty && !mixed;\n out.push(`${pad}<${name}${attrs}>${childPretty ? '\\n' : ''}`);\n for (const [key, child] of children) {\n serialize(key, child, depth + 1, childPretty, out);\n }\n out.push(`${childPretty ? pad : ''}</${name}>${nl}`);\n}\n\n// --- adapter ---------------------------------------------------------------\n\nexport class XmlConfigAdapter implements XmlAdapter {\n /** Parse a Mirth backup XML string into a canonical config. */\n parse(xml: string): CanonicalConfig {\n // XML end-of-line handling, which fxp does not apply.\n const normalized = xml.replace(/\\r\\n?/g, '\\n');\n if (/<!DOCTYPE/i.test(normalized.slice(0, normalized.search(/<[A-Za-z_]/)))) {\n // A DTD could declare entities we would not expand; Mirth never emits one.\n throw new Error('XmlConfigAdapter.parse: DOCTYPE declarations are not supported');\n }\n // fxp's parser accepts unclosed elements, so a truncated backup would read\n // as a smaller, \"valid\" configuration; validate the whole document first.\n const valid = XMLValidator.validate(normalized);\n if (valid !== true) {\n const { line, col, msg } = valid.err;\n throw new Error(`XmlConfigAdapter.parse: not well-formed XML at line ${line}, column ${col}: ${msg}`);\n }\n const nodes = parser.parse(normalized) as OrderedNode[];\n const root = nodes.find((n) => nodeName(n) === ROOT_KEY);\n if (root === undefined) {\n throw new Error(`XmlConfigAdapter.parse: expected a top-level <${ROOT_KEY}> element`);\n }\n const value = convertElement(root[ROOT_KEY] as OrderedNode[], root[ORDERED_ATTRS] as Record<string, string>);\n return (typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {}) as CanonicalConfig;\n }\n\n /** Serialize a canonical config back to Mirth backup XML. */\n build(config: CanonicalConfig): string {\n const out: string[] = [];\n serialize(ROOT_KEY, config, 0, true, out);\n return out.join('');\n }\n}\n","/**\n * Explode / implode engine.\n *\n * Projects a canonical config (the unwrapped Mirth `serverConfiguration`) onto a\n * git-friendly directory tree and reverses it losslessly. The exploded tree is a\n * verbatim *projection* of the config split across files using two marker types:\n *\n * - `{ \"@file\": \"<relpath>\" }` replaces an extracted code/script STRING leaf;\n * the string is written to a sidecar `.js` file (path relative to the JSON\n * file holding the marker).\n * - `{ \"@ref\": \"<relpath>\" }` replaces a whole sub-object split into its own\n * `.json` file (path relative to the JSON file holding the marker).\n *\n * Invariant: `implode(explode(config))` deep-equals `config`.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { existsSync } from 'node:fs';\nimport { lstat, mkdir, readFile, readdir, realpath, writeFile } from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport {\n CHANNEL_SCRIPT_KEYS,\n CODE_KEYS,\n isFileRef,\n type CanonicalConfig,\n type ExplodeEngine,\n type ExplodeOptions,\n type Json,\n} from '../types.js';\nimport { parseJson } from '../json.js';\n\n// --- shared helpers --------------------------------------------------------\n\n/** Coerce a \"container may be object or array depending on count\" value. */\nexport function asArray<T = Json>(x: unknown): T[] {\n return Array.isArray(x) ? (x as T[]) : x == null ? [] : [x as T];\n}\n\n/** Marker left in a `*.json` file in place of an extracted sub-object. */\ninterface RefMarker {\n '@ref': string;\n}\n\nexport function isRefMarker(v: unknown): v is RefMarker {\n return (\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n Object.keys(v).length === 1 &&\n typeof (v as Record<string, unknown>)['@ref'] === 'string'\n );\n}\n\nconst CODE_KEY_SET: ReadonlySet<string> = new Set([...CODE_KEYS, ...CHANNEL_SCRIPT_KEYS]);\n\n/** Map of channel-level script key -> friendly file base name. */\nconst CHANNEL_SCRIPT_FRIENDLY: Record<string, string> = {\n preprocessingScript: 'preprocessor',\n postprocessingScript: 'postprocessor',\n deployScript: 'deploy',\n undeployScript: 'undeploy',\n};\n\nfunction isPlainObject(v: unknown): v is Record<string, Json> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction deepClone<T>(v: T): T {\n return structuredClone(v);\n}\n\n/**\n * Slugify a name into a filesystem-safe segment.\n * Replaces `/ \\ : * ? \" < > |` and control chars, collapses whitespace to `-`,\n * trims leading/trailing separators. Never returns an empty string.\n */\nfunction slug(name: unknown): string {\n let s = typeof name === 'string' ? name : name == null ? '' : String(name);\n // Replace reserved / control characters with a space (later collapsed).\n s = s.replace(/[/\\\\:*?\"<>|]/g, ' ');\n // eslint-disable-next-line no-control-regex\n s = s.replace(/[\\x00-\\x1f\\x7f]/g, ' ');\n // Collapse any run of whitespace to a single dash.\n s = s.replace(/\\s+/g, '-');\n // Trim leading/trailing dashes/dots.\n s = s.replace(/^[-.]+|[-.]+$/g, '');\n if (s.length === 0) return 'unnamed';\n // Windows reserves these device names in every directory.\n return /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(s) ? `${s}-` : s;\n}\n\n/**\n * Deterministically resolve slug collisions within a namespace. Compared\n * case-insensitively: on Windows and macOS `Alpha` and `alpha` are the same\n * directory, and one would silently overwrite the other.\n */\nfunction uniqueSlug(base: string, used: Set<string>): string {\n let candidate = base;\n for (let n = 2; used.has(candidate.toLowerCase()); n += 1) candidate = `${base}-${n}`;\n used.add(candidate.toLowerCase());\n return candidate;\n}\n\n/** POSIX-style relative path for storage inside markers (stable across OS). */\nfunction relPosix(fromDir: string, toFile: string): string {\n return path.relative(fromDir, toFile).split(path.sep).join('/');\n}\n\n/** The real path of the tree being exploded, for the write check below. */\nconst explodeRoot = new AsyncLocalStorage<string>();\n\n/**\n * Refuse a write whose real directory is outside the tree: the names are\n * sanitised, but a symlink or junction already inside the tree could still\n * redirect it.\n */\nasync function assertInsideTree(filePath: string): Promise<void> {\n const root = explodeRoot.getStore();\n if (root === undefined) return;\n // Check the nearest directory that already exists, before creating any:\n // mkdir through a link would already have created directories outside.\n let dir = path.dirname(filePath);\n while (!existsSync(dir) && path.dirname(dir) !== dir) dir = path.dirname(dir);\n const real = await realpath(dir);\n if (real !== root && !real.startsWith(root + path.sep)) {\n throw new Error(`refusing to write outside the working tree: ${filePath}`);\n }\n // A safe parent does not make an existing file link safe to overwrite.\n const existing = await lstat(filePath).catch((err: NodeJS.ErrnoException) => {\n if (err.code !== 'ENOENT') throw err;\n return undefined;\n });\n if (existing?.isSymbolicLink()) throw new Error(`refusing to write through a file link: ${filePath}`);\n}\n\nasync function writeFileMkdir(filePath: string, data: string): Promise<void> {\n await assertInsideTree(filePath);\n await mkdir(path.dirname(filePath), { recursive: true });\n // NO added trailing newline — code strings must round-trip byte-identical.\n await writeFile(filePath, data);\n}\n\nasync function writeJson(filePath: string, value: Json): Promise<void> {\n await assertInsideTree(filePath);\n await mkdir(path.dirname(filePath), { recursive: true });\n await writeFile(filePath, JSON.stringify(value, null, 2));\n}\n\n// --- explode ---------------------------------------------------------------\n\n/**\n * Recursively extract code leaves from a value tree, IN PLACE (caller passes a\n * clone). `jsonDir` is the directory of the JSON file that will hold this tree;\n * `codeDir` is the directory under which sidecar `.js` files for this tree are\n * written; `prefixParts` accumulates the ancestor key/index chain for fallback\n * naming. `usedPaths` dedupes generated file paths within this resource.\n */\nasync function extractCode(\n value: Json,\n ctx: {\n jsonDir: string;\n codeDir: string;\n friendly: string | null; // friendly relative path (no extension) if known\n prefixParts: string[]; // ancestor key chain for fallback naming\n usedPaths: Set<string>;\n },\n): Promise<Json> {\n if (Array.isArray(value)) {\n const out: Json[] = [];\n for (let i = 0; i < value.length; i += 1) {\n out.push(\n await extractCode(value[i] as Json, {\n ...ctx,\n friendly: null,\n prefixParts: [...ctx.prefixParts, String(i)],\n }),\n );\n }\n return out;\n }\n\n if (!isPlainObject(value)) {\n return value;\n }\n\n // Recurse, applying friendly-path recognition for known Mirth structures.\n return extractFromObject(value, ctx);\n}\n\nasync function extractFromObject(\n obj: Record<string, Json>,\n ctx: {\n jsonDir: string;\n codeDir: string;\n friendly: string | null;\n prefixParts: string[];\n usedPaths: Set<string>;\n },\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(obj)) {\n // Code leaf? Only extract plain non-empty string leaves.\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw; // keep empty/whitespace-only inline (no file)\n continue;\n }\n const friendlyBase =\n key in CHANNEL_SCRIPT_FRIENDLY\n ? `scripts/${CHANNEL_SCRIPT_FRIENDLY[key]}`\n : // One filename segment: config keys are untrusted and may hold '/' or '..'.\n ctx.friendly ?? `_code/${slug([...ctx.prefixParts, key].join('.'))}`;\n const filePath = resolveUnique(ctx.codeDir, `${friendlyBase}.js`, ctx.usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(ctx.jsonDir, filePath) };\n continue;\n }\n\n // Recurse into children.\n out[key] = await extractCode(raw as Json, {\n ...ctx,\n friendly: null,\n prefixParts: [...ctx.prefixParts, key],\n });\n }\n\n return out;\n}\n\n/** Resolve a unique absolute file path for a friendly-or-fallback rel path. */\nfunction resolveUnique(baseDir: string, relName: string, used: Set<string>): string {\n const ext = path.extname(relName);\n const dir = path.dirname(relName);\n const stem = path.basename(relName, ext);\n const dirSlug = dir === '.' ? '' : dir;\n // Build slugged segments for the directory portion (preserve structure).\n const segs = dirSlug.split('/').filter(Boolean);\n // Case-insensitive, like uniqueSlug.\n let rel = [...segs, `${stem}${ext}`].join('/');\n for (let n = 2; used.has(rel.toLowerCase()); n += 1) rel = [...segs, `${stem}-${n}${ext}`].join('/');\n used.add(rel.toLowerCase());\n const full = path.resolve(baseDir, ...rel.split('/'));\n if (!full.startsWith(path.resolve(baseDir) + path.sep)) throw new Error(`script path escapes its directory: ${relName}`);\n return full;\n}\n\n/**\n * Walk a channel object giving friendly paths to its scripts and connector\n * transformer/filter steps, extracting code leaves in place. Returns the\n * transformed channel object. `dir` is the channel's directory (also the dir of\n * its `channel.json`). `usedPaths` dedupes within the channel.\n */\nasync function explodeChannelTree(\n channel: Record<string, Json>,\n dir: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(channel)) {\n // Channel-level scripts -> scripts/<friendly>.js\n if (key in CHANNEL_SCRIPT_FRIENDLY && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(dir, `scripts/${CHANNEL_SCRIPT_FRIENDLY[key]}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(dir, filePath) };\n continue;\n }\n\n if (key === 'sourceConnector' && isPlainObject(raw)) {\n out[key] = await explodeConnector(raw, dir, 'source', 'source/receiver', usedPaths);\n continue;\n }\n\n if (key === 'destinationConnectors' && isPlainObject(raw)) {\n out[key] = await explodeDestinationConnectors(raw, dir, usedPaths);\n continue;\n }\n\n // Everything else: generic extraction (covers unknown structures / code).\n out[key] = await extractCode(raw as Json, {\n jsonDir: dir,\n codeDir: dir,\n friendly: null,\n prefixParts: [key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/**\n * Explode a connector (source or a single destination). `baseRel` is the\n * relative directory prefix within the channel dir for this connector's\n * transformer/filter steps (e.g. `source` or `destinations/<slug>`).\n * `scriptFileBase` is the friendly path (no extension) for the connector's own\n * reader/writer code at `properties.script` (e.g. `source/receiver` or\n * `destinations/<slug>/writer`).\n */\nasync function explodeConnector(\n connector: Record<string, Json>,\n channelDir: string,\n baseRel: string,\n scriptFileBase: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(connector)) {\n if (key === 'transformer' && isPlainObject(raw)) {\n out[key] = await explodeStepContainer(raw, channelDir, `${baseRel}/transformer`, usedPaths);\n continue;\n }\n if (key === 'responseTransformer' && isPlainObject(raw)) {\n out[key] = await explodeStepContainer(\n raw,\n channelDir,\n `${baseRel}/responseTransformer`,\n usedPaths,\n );\n continue;\n }\n if (key === 'filter' && isPlainObject(raw)) {\n out[key] = await explodeStepContainer(raw, channelDir, `${baseRel}/filter`, usedPaths);\n continue;\n }\n if (key === 'properties' && isPlainObject(raw)) {\n out[key] = await explodeConnectorProperties(raw, channelDir, scriptFileBase, usedPaths);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/**\n * Explode a connector's `properties` object. The JavaScript Reader/Writer\n * connectors carry their body directly at `properties.script`; extract it to a\n * friendly `<scriptFileBase>.js`. Anything else recurses generically.\n */\nasync function explodeConnectorProperties(\n properties: Record<string, Json>,\n channelDir: string,\n scriptFileBase: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(properties)) {\n if (key === 'script' && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(channelDir, `${scriptFileBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(channelDir, filePath) };\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: ['properties', key],\n usedPaths,\n });\n }\n return out;\n}\n\nasync function explodeDestinationConnectors(\n container: Record<string, Json>,\n channelDir: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n const usedDestSlugs = new Set<string>();\n\n for (const [key, raw] of Object.entries(container)) {\n if (key === 'connector') {\n const connectors = asArray<Record<string, Json>>(raw);\n const wasArray = Array.isArray(raw);\n const transformed: Record<string, Json>[] = [];\n for (const conn of connectors) {\n const name = isPlainObject(conn) ? conn['name'] : undefined;\n const destSlug = uniqueSlug(slug(name), usedDestSlugs);\n transformed.push(\n isPlainObject(conn)\n ? await explodeConnector(\n conn,\n channelDir,\n `destinations/${destSlug}`,\n `destinations/${destSlug}/writer`,\n usedPaths,\n )\n : conn,\n );\n }\n out[key] = wasArray ? transformed : (transformed[0] as Json);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: ['destinationConnectors', key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/**\n * Explode a transformer/filter/responseTransformer container. Mirth nests the\n * actual steps under an `elements` key. In REAL data `elements` is an OBJECT\n * keyed by the step's fully-qualified Java class name (e.g.\n * `com.mirth.connect.plugins.javascriptstep.JavaScriptStep`), whose value is an\n * array of step objects:\n *\n * elements: { \"com.mirth...JavaScriptStep\": [ { name, sequenceNumber, script } ] }\n *\n * An empty transformer/filter serializes `elements` as the empty string `\"\"`.\n * We give each step a friendly `<baseRel>/<n>.<slug(step name)>.js` path, where\n * `n` is `sequenceNumber + 1` (string-parsed) falling back to a running index.\n * Unknown shapes fall back to generic extraction so we never crash.\n */\nasync function explodeStepContainer(\n container: Record<string, Json>,\n channelDir: string,\n baseRel: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(container)) {\n if (key === 'elements' && (Array.isArray(raw) || isPlainObject(raw))) {\n out[key] = await explodeElementsContainer(\n raw as Json[] | Record<string, Json>,\n channelDir,\n baseRel,\n usedPaths,\n );\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/** Does an object look like a single step (carries a code leaf or step metadata)? */\nfunction isStepLike(obj: Record<string, Json>): boolean {\n return (\n typeof obj['script'] === 'string' ||\n typeof obj['code'] === 'string' ||\n 'sequenceNumber' in obj ||\n 'name' in obj\n );\n}\n\n/**\n * Dispatch the `elements` value of a step container, numbering steps globally\n * in encounter order. Handles three shapes:\n * - ARRAY of step objects (a legacy / hand-written form).\n * - a single step OBJECT (`elements` collapsed to one step).\n * - the REAL Mirth form: an OBJECT keyed by fully-qualified class name whose\n * values are arrays (or single objects) of step objects.\n */\nasync function explodeElementsContainer(\n elements: Json[] | Record<string, Json>,\n channelDir: string,\n baseRel: string,\n usedPaths: Set<string>,\n): Promise<Json> {\n const counter = { i: 0 };\n\n if (Array.isArray(elements)) {\n return explodeStepArray(elements, channelDir, baseRel, usedPaths, counter);\n }\n\n // A single step object directly under `elements`.\n if (isStepLike(elements)) {\n return explodeStep(elements, channelDir, baseRel, counter.i++, usedPaths);\n }\n\n // Class-keyed map of step buckets (the real shape).\n const out: Record<string, Json> = {};\n for (const [className, raw] of Object.entries(elements)) {\n // Attributes (`@_...`), adapter metadata (`#order`, `#comment`) and nulls\n // are passed through generically, not numbered as steps.\n if (className.startsWith('@_') || className.startsWith('#') || raw == null) {\n out[className] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, 'elements', className],\n usedPaths,\n });\n continue;\n }\n if (Array.isArray(raw)) {\n out[className] = await explodeStepArray(raw, channelDir, baseRel, usedPaths, counter);\n continue;\n }\n if (isPlainObject(raw) && isStepLike(raw)) {\n out[className] = await explodeStep(raw, channelDir, baseRel, counter.i++, usedPaths);\n continue;\n }\n out[className] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, 'elements', className],\n usedPaths,\n });\n }\n return out;\n}\n\nasync function explodeStepArray(\n steps: Json[],\n channelDir: string,\n baseRel: string,\n usedPaths: Set<string>,\n counter: { i: number },\n): Promise<Json[]> {\n const transformed: Json[] = [];\n for (const step of steps) {\n transformed.push(await explodeStep(step, channelDir, baseRel, counter.i++, usedPaths));\n }\n return transformed;\n}\n\nasync function explodeStep(\n step: Json,\n channelDir: string,\n baseRel: string,\n index: number,\n usedPaths: Set<string>,\n): Promise<Json> {\n if (!isPlainObject(step)) {\n return step;\n }\n\n // Sequence number (Mirth) is 0-based; prefer it, else fall back to index.\n const seqRaw = step['sequenceNumber'];\n let seq = index;\n if (typeof seqRaw === 'number') seq = seqRaw;\n else if (typeof seqRaw === 'string' && seqRaw.trim() !== '' && !Number.isNaN(Number(seqRaw))) {\n seq = Number(seqRaw);\n }\n const n = seq + 1;\n const stepName = step['name'];\n // Many real steps have no `name`; fall back to a bare `<n>` segment so the\n // file reads as e.g. `1.js` rather than `1.unnamed.js`.\n const hasName = typeof stepName === 'string' && stepName.trim().length > 0;\n const friendlyBase = hasName ? `${baseRel}/${n}.${slug(stepName)}` : `${baseRel}/${n}`;\n\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(step)) {\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(channelDir, `${friendlyBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(channelDir, filePath) };\n continue;\n }\n // Recurse generically into anything else (handles nested unknowns).\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, String(index), key],\n usedPaths,\n });\n }\n return out;\n}\n\n/**\n * Split the three known top-level collections into per-resource JSON files,\n * replacing each element with an `@ref` marker (order preserved). Each split-out\n * resource is itself code-extracted under its own directory.\n *\n * Returns the rewritten container value (object or array preserved as-is) with\n * `@ref` markers, or null if the collection was absent.\n */\nasync function splitCollection(\n parent: Record<string, Json>,\n containerKey: string, // e.g. 'channels'\n elementKey: string, // e.g. 'channel'\n root: string,\n serverDir: string, // dir holding configuration.json (markers are relative to it)\n targetFor: (name: unknown, slugName: string) => { jsonFile: string; resourceDir: string },\n usedSlugs: Set<string>,\n explodeResource: (\n el: Record<string, Json>,\n resourceDir: string,\n ) => Promise<Record<string, Json>>,\n): Promise<void> {\n const container = parent[containerKey];\n if (!isPlainObject(container)) return;\n const raw = container[elementKey];\n if (raw == null) return;\n\n const wasArray = Array.isArray(raw);\n const elements = asArray<Json>(raw);\n const refs: Json[] = [];\n\n // Suffixes for colliding names (\"Lab Feed\", \"LAB FEED\") are handed out by\n // name then id, not list order: the server's order can change (a restore\n // reorders it), which would move a resource to another directory.\n const byName = (el: Record<string, Json>) => `${slug(el['name']).toLowerCase()}\\u0000${String(el['id'] ?? '')}`;\n const slugs = new Map<Json, string>();\n for (const el of elements.filter(isPlainObject).sort((a, b) => (byName(a) < byName(b) ? -1 : byName(a) > byName(b) ? 1 : 0))) {\n slugs.set(el, uniqueSlug(slug(el['name']), usedSlugs));\n }\n\n for (const el of elements) {\n if (!isPlainObject(el)) {\n // Non-object element: keep inline (cannot meaningfully split).\n refs.push(el);\n continue;\n }\n const slugName = slugs.get(el)!;\n const { jsonFile, resourceDir } = targetFor(el['name'], slugName);\n const transformed = await explodeResource(el, resourceDir);\n await writeJson(jsonFile, transformed);\n refs.push({ '@ref': relPosix(serverDir, jsonFile) });\n }\n\n // Preserve object-vs-array shape of the element container.\n container[elementKey] = wasArray ? refs : (refs[0] as Json);\n}\n\nasync function explode(config: CanonicalConfig, opts: ExplodeOptions): Promise<void> {\n await mkdir(opts.root, { recursive: true });\n await explodeRoot.run(await realpath(opts.root), () => explodeInto(config, opts));\n}\n\nasync function explodeInto(config: CanonicalConfig, opts: ExplodeOptions): Promise<void> {\n const root = opts.root;\n const serverDir = path.join(root, 'server');\n const skeleton = deepClone(config) as Record<string, Json>;\n\n // 1. channels.channel[] -> channels/<slug>/channel.json\n if (isPlainObject(skeleton['channels'])) {\n const channelSlugs = new Set<string>();\n await splitCollection(\n skeleton,\n 'channels',\n 'channel',\n root,\n serverDir,\n (_name, slugName) => {\n const resourceDir = path.join(root, 'channels', slugName);\n return { jsonFile: path.join(resourceDir, 'channel.json'), resourceDir };\n },\n channelSlugs,\n async (el, resourceDir) => explodeChannelTree(el, resourceDir, new Set<string>()),\n );\n }\n\n // 2. codeTemplateLibraries.codeTemplateLibrary[] -> codeTemplates/<slug>/library.json\n if (isPlainObject(skeleton['codeTemplateLibraries'])) {\n const libSlugs = new Set<string>();\n await splitCollection(\n skeleton,\n 'codeTemplateLibraries',\n 'codeTemplateLibrary',\n root,\n serverDir,\n (_name, slugName) => {\n const resourceDir = path.join(root, 'codeTemplates', slugName);\n return { jsonFile: path.join(resourceDir, 'library.json'), resourceDir };\n },\n libSlugs,\n async (el, resourceDir) => explodeLibrary(el, resourceDir),\n );\n }\n\n // 3. channelGroups.channelGroup[] -> channelGroups/<slug>.json\n if (isPlainObject(skeleton['channelGroups'])) {\n const groupSlugs = new Set<string>();\n await splitCollection(\n skeleton,\n 'channelGroups',\n 'channelGroup',\n root,\n serverDir,\n (_name, slugName) => {\n const resourceDir = path.join(root, 'channelGroups');\n return { jsonFile: path.join(resourceDir, `${slugName}.json`), resourceDir };\n },\n groupSlugs,\n async (el, resourceDir) =>\n // group json lives in channelGroups/; sidecar code (rare) under same dir\n extractCode(el, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['channelGroup'],\n usedPaths: new Set<string>(),\n }) as Promise<Record<string, Json>>,\n );\n }\n\n // 4. Extract code in the remaining skeleton (e.g. globalScripts) and write it.\n const finalSkeleton = await extractCode(skeleton, {\n jsonDir: serverDir,\n codeDir: serverDir,\n friendly: null,\n prefixParts: [],\n usedPaths: new Set<string>(),\n });\n\n await writeJson(path.join(serverDir, 'configuration.json'), finalSkeleton);\n}\n\n/**\n * Explode a code template library: split-out resource. Each template's `code`\n * leaf -> `<slug(template name)>.js` next to library.json (resourceDir).\n */\nasync function explodeLibrary(\n library: Record<string, Json>,\n resourceDir: string,\n): Promise<Record<string, Json>> {\n const used = new Set<string>();\n const usedTemplateSlugs = new Set<string>();\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(library)) {\n if (key === 'codeTemplates' && isPlainObject(raw)) {\n out[key] = await explodeLibraryTemplates(raw, resourceDir, usedTemplateSlugs, used);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: [key],\n usedPaths: used,\n });\n }\n return out;\n}\n\nasync function explodeLibraryTemplates(\n container: Record<string, Json>,\n resourceDir: string,\n usedTemplateSlugs: Set<string>,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(container)) {\n if (key === 'codeTemplate' && raw != null) {\n const wasArray = Array.isArray(raw);\n const templates = asArray<Json>(raw);\n const transformed: Json[] = [];\n for (const t of templates) {\n transformed.push(\n await explodeCodeTemplate(t, resourceDir, usedTemplateSlugs, usedPaths),\n );\n }\n out[key] = wasArray ? transformed : (transformed[0] as Json);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['codeTemplates', key],\n usedPaths,\n });\n }\n return out;\n}\n\nasync function explodeCodeTemplate(\n template: Json,\n resourceDir: string,\n usedTemplateSlugs: Set<string>,\n usedPaths: Set<string>,\n): Promise<Json> {\n if (!isPlainObject(template)) return template;\n const friendlyBase = uniqueSlug(slug(template['name']), usedTemplateSlugs);\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(template)) {\n // In real Mirth data the body lives at `properties.code`; handle that and\n // (defensively) a `code`/`script` leaf directly on the template object.\n if (key === 'properties' && isPlainObject(raw)) {\n out[key] = await explodeTemplateProperties(raw, resourceDir, friendlyBase, usedPaths);\n continue;\n }\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(resourceDir, `${friendlyBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(resourceDir, filePath) };\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['codeTemplate', key],\n usedPaths,\n });\n }\n return out;\n}\n\n/**\n * Explode a code template's `properties` object, whose `code` leaf is the\n * template body -> friendly `<friendlyBase>.js` next to library.json.\n */\nasync function explodeTemplateProperties(\n properties: Record<string, Json>,\n resourceDir: string,\n friendlyBase: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(properties)) {\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(resourceDir, `${friendlyBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(resourceDir, filePath) };\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['codeTemplate', 'properties', key],\n usedPaths,\n });\n }\n return out;\n}\n\n// --- implode ---------------------------------------------------------------\n\n/**\n * Resolve a marker path relative to `jsonDir` and assert it stays inside the\n * working-tree `root`. Legitimate markers DO use `..` (e.g. `server/`'s config\n * references `../channelGroups/*.json`), so `..` is allowed — only escaping the\n * tree root is rejected. Working trees are shared/cloned git repos, so marker\n * values are attacker-influenceable input; without this check a crafted\n * `{\"@file\": \"../../../../etc/passwd\"}` would be read into the imploded config\n * (and, via `push`, uploaded to a live server).\n */\nfunction resolveWithinRoot(root: string, jsonDir: string, rel: string): string {\n const target = path.resolve(jsonDir, rel);\n if (target !== root && !target.startsWith(root + path.sep)) {\n throw new Error(`marker path escapes the working tree: ${rel}`);\n }\n return target;\n}\n\n/**\n * Read a marker target, re-checking containment on the real path: the text\n * check above can't see a symlink or junction inside the tree that points\n * outside it.\n */\nasync function readWithinRoot(root: string, target: string, rel: string): Promise<string> {\n const [realRoot, realTarget] = await Promise.all([realpath(root), realpath(target)]);\n if (realTarget !== realRoot && !realTarget.startsWith(realRoot + path.sep)) {\n throw new Error(`marker path escapes the working tree through a link: ${rel}`);\n }\n return readFile(realTarget, 'utf8');\n}\n\n/**\n * Recursively resolve markers in a parsed JSON value. `jsonDir` is the directory\n * of the JSON file this value came from (markers are relative to it); `root` is\n * the working-tree root that every marker target must stay within.\n */\nconst pathKey = (file: string): string => process.platform === 'win32' ? file.toLowerCase() : file;\n\nasync function resolveMarkers(value: Json, jsonDir: string, root: string, referenced: Set<string>): Promise<Json> {\n if (Array.isArray(value)) {\n const out: Json[] = [];\n for (const item of value) {\n // A collection member whose file is gone was deleted from the tree\n // (e.g. `rm -r channels/<name>`), so it is dropped, not an error.\n if (isRefMarker(item) && !existsSync(resolveWithinRoot(root, jsonDir, item['@ref']))) continue;\n out.push(await resolveMarkers(item, jsonDir, root, referenced));\n }\n return out;\n }\n\n if (isFileRef(value)) {\n const target = resolveWithinRoot(root, jsonDir, value['@file']);\n // Raw read, NO trimming — byte-identical round-trip.\n return readWithinRoot(root, target, value['@file']);\n }\n\n if (isRefMarker(value)) {\n const target = resolveWithinRoot(root, jsonDir, value['@ref']);\n const text = await readWithinRoot(root, target, value['@ref']);\n referenced.add(pathKey(await realpath(target)));\n const parsed = parseJson<Json>(text, target);\n return resolveMarkers(parsed, path.dirname(target), root, referenced);\n }\n\n if (isPlainObject(value)) {\n const out: Record<string, Json> = {};\n for (const [k, v] of Object.entries(value)) {\n // Same for a one-member collection, which explode stores as a bare marker.\n if (isRefMarker(v) && !existsSync(resolveWithinRoot(root, jsonDir, v['@ref']))) continue;\n out[k] = await resolveMarkers(v, jsonDir, root, referenced);\n }\n return out;\n }\n\n return value;\n}\n\n/** Canonical resource files are discoverable, so additions and directory renames cannot disappear. */\nasync function discoverResources(config: CanonicalConfig, root: string, referenced: Set<string>): Promise<void> {\n const realRoot = await realpath(root);\n const contained = async (file: string): Promise<string> => {\n const real = await realpath(file);\n if (real !== realRoot && !real.startsWith(realRoot + path.sep)) throw new Error(`resource path escapes the working tree through a link: ${file}`);\n return real;\n };\n const layouts = [\n { folder: 'channels', filename: 'channel.json', container: 'channels', member: 'channel' },\n { folder: 'codeTemplates', filename: 'library.json', container: 'codeTemplateLibraries', member: 'codeTemplateLibrary' },\n { folder: 'channelGroups', filename: null, container: 'channelGroups', member: 'channelGroup' },\n ];\n for (const layout of layouts) {\n const dir = path.join(root, layout.folder);\n if (!existsSync(dir)) continue;\n await contained(dir);\n const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);\n const additions: Json[] = [];\n for (const entry of entries) {\n let file = path.join(dir, entry.name);\n if (layout.filename) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;\n await contained(file);\n file = path.join(file, layout.filename);\n if (!existsSync(file)) continue;\n } else if (!entry.name.endsWith('.json')) continue;\n const real = await contained(file);\n if (referenced.has(pathKey(real))) continue;\n const parsed = parseJson<Json>(await readWithinRoot(root, file, file), file);\n const resource = await resolveMarkers(parsed, path.dirname(file), root, referenced);\n if (!isPlainObject(resource) || typeof resource['id'] !== 'string' || !resource['id'].trim() || typeof resource['name'] !== 'string' || !resource['name'].trim()) {\n throw new Error(`new resource ${file} needs a nonempty id and name`);\n }\n additions.push(resource);\n referenced.add(pathKey(real));\n }\n if (!additions.length) continue;\n const container = isPlainObject(config[layout.container]) ? config[layout.container] as Record<string, Json> : {};\n const old = container[layout.member];\n const members = [...(old == null || old === '' ? [] : asArray<Json>(old)), ...additions];\n const ids = new Set<string>();\n for (const member of members.filter(isPlainObject)) {\n const id = String(member['id']);\n if (ids.has(id)) throw new Error(`duplicate ${layout.member} id ${id}: a copied resource keeps its source's id; give each copy a new UUID`);\n ids.add(id);\n }\n config[layout.container] = { ...container, [layout.member]: members.length === 1 ? members[0]! : members };\n }\n}\n\nasync function implode(opts: ExplodeOptions): Promise<CanonicalConfig> {\n const root = path.resolve(opts.root);\n if (existsSync(path.join(root, '.channelvault-transaction.json'))) {\n throw new Error('working tree has a pending replacement; run a channelvault CLI command with the original --dotenv selection to recover it before reading');\n }\n const serverDir = path.join(root, 'server');\n const configPath = path.join(serverDir, 'configuration.json');\n const parsed = parseJson<Json>(await readWithinRoot(root, configPath, configPath), configPath);\n const referenced = new Set<string>();\n const resolved = await resolveMarkers(parsed, serverDir, root, referenced);\n if (!isPlainObject(resolved)) throw new Error('server/configuration.json must hold a configuration object');\n await discoverResources(resolved, root, referenced);\n return resolved as CanonicalConfig;\n}\n\n// --- factory ---------------------------------------------------------------\n\nexport function createExplodeEngine(): ExplodeEngine {\n return { explode, implode };\n}\n","import { readFile } from 'node:fs/promises';\n\n/** JSON.parse, naming the file in the error: a tree has hundreds of JSON files. */\nexport function parseJson<T = unknown>(text: string, file: string): T {\n try {\n return JSON.parse(text) as T;\n } catch (err) {\n throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nexport async function readJson<T = unknown>(file: string): Promise<T> {\n return parseJson<T>(await readFile(file, 'utf8'), file);\n}\n","/**\n * Live Mirth transport client.\n *\n * Talks to a running Mirth Connect (a.k.a. NextGen Connect / OIE / BridgeLink)\n * server over its REST API and produces/consumes the canonical config (the\n * unwrapped `serverConfiguration` document) — the same logical document the XML\n * adapter parses from a backup file.\n *\n * The transport (login, cookie jar, TLS bypass, 401 re-auth, single-flight\n * login) is ported from the proven `baseClient.ts` in the sibling\n * `integration-engine-api` project. We deliberately do NOT carry over the\n * OpenAPI-generated typing layers: payloads are opaque `CanonicalConfig` JSON.\n *\n * Wrapping behavior for the two endpoints:\n *\n * - GET /server/configuration returns a Jackson-style document wrapped in a\n * single top-level key (`serverConfiguration`), with `@version` / `@class`\n * metadata sprinkled throughout. `getServerConfiguration()` unwraps the\n * single top-level key and returns its contents.\n * - PUT /server/configuration expects the same wrapper, so\n * `putServerConfiguration()` re-wraps as `{ serverConfiguration: config }`.\n */\nimport { CookieJar } from 'tough-cookie';\nimport { isIP } from 'node:net';\nimport { connect as tlsConnect, type TLSSocket } from 'node:tls';\nimport { Agent, buildConnector } from 'undici';\nimport { redactSecretsInText } from '../secrets/detect.js';\nimport { isSecretKey } from '../secrets/index.js';\nimport type { ApiError, CanonicalConfig, ClientConfig, MirthClient } from '../types.js';\nimport { liveConfiguration } from './validate.js';\n\n/** TLS verification failures, typically a self-signed or privately issued server certificate. */\nexport const UNTRUSTED_CERT_CODES: ReadonlySet<string> = new Set([\n 'DEPTH_ZERO_SELF_SIGNED_CERT',\n 'SELF_SIGNED_CERT_IN_CHAIN',\n 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',\n // Not an expired certificate or a host-name mismatch: turning verification\n // off is the wrong advice for those, and their messages already say why.\n]);\n\n/**\n * fetch reports every network failure as \"fetch failed\" and keeps the reason\n * (ECONNREFUSED, a certificate error) in `cause`; surface it, with its code.\n */\nfunction connectionError(url: string, err: unknown): Error & { code?: string } {\n let cause = err instanceof Error ? (err.cause as (Error & { code?: string; errors?: unknown[] }) | undefined) : undefined;\n // Several addresses tried (IPv4 and IPv6): report the first attempt.\n if (cause instanceof AggregateError && cause.errors[0] instanceof Error) cause = cause.errors[0] as Error & { code?: string };\n const detail = cause?.message || (err instanceof Error ? err.message : String(err));\n const code = cause?.code;\n const error = new Error(\n `cannot reach ${new URL(url).origin}: ${detail}${code && !detail.includes(code) ? ` (${code})` : ''}`,\n { cause: err },\n ) as Error & { code?: string };\n error.code = code;\n return error;\n}\n\n/** The SHA-256 fingerprint a TLS socket's peer presented, as 64 lowercase hex digits. */\nfunction fingerprintOf(socket: TLSSocket): string {\n return (socket.getPeerCertificate().fingerprint256 ?? '').replace(/:/g, '').toLowerCase();\n}\n\n/**\n * Connects without CA verification and accepts only the certificate whose\n * SHA-256 is `pin`. `checkServerIdentity` never runs when\n * `rejectUnauthorized` is false, so the check has to be here; it runs on the\n * handshake, before the request (and the login) is written.\n */\nfunction pinnedConnector(pin: string): buildConnector.connector {\n const base = buildConnector({ rejectUnauthorized: false, maxCachedSessions: 0 });\n return (options, callback) => {\n base(options, (err, socket) => {\n if (err) return callback(err, null);\n const presented = fingerprintOf(socket as TLSSocket);\n if (presented === pin) return callback(null, socket);\n socket.destroy();\n const mismatch = new Error(\n `the server presented certificate SHA-256 ${presented || '(none)'}, but the pinned fingerprint is ${pin}; nothing was sent`,\n ) as Error & { code: string; presented: string };\n mismatch.code = 'TLS_PIN_MISMATCH';\n mismatch.presented = presented;\n callback(mismatch, null);\n });\n };\n}\n\n/**\n * The SHA-256 fingerprint of the certificate `host:port` presents, without\n * verifying it or sending anything over the connection.\n */\nexport function presentedFingerprint(host: string, port: number, timeoutMs = 10_000): Promise<string> {\n return new Promise((resolve, reject) => {\n const socket = tlsConnect({ host, port, rejectUnauthorized: false, ...(isIP(host) ? {} : { servername: host }) });\n socket.setTimeout(timeoutMs, () => socket.destroy(new Error(`no TLS handshake from ${host}:${port} within ${timeoutMs / 1000} s`)));\n socket.once('secureConnect', () => {\n const fp = fingerprintOf(socket);\n socket.end();\n resolve(fp);\n });\n socket.once('error', reject);\n });\n}\n\n/** `, to <origin>` for a redirect's Location; only the origin, since a path or query can carry a token. */\nfunction redirectTarget(url: string, response: Response): string {\n const location = response.headers.get('location');\n if (!location) return '';\n try { return `, to ${new URL(location, url).origin}`; }\n catch { return ''; }\n}\n\n/** Optional flags accepted by `putServerConfiguration` (Mirth query params). */\nexport interface PutServerConfigurationOptions {\n /** Redeploy all channels after applying the configuration. */\n deploy?: boolean;\n /** Overwrite the global configuration map. */\n overwriteConfigMap?: boolean;\n}\n\n/**\n * The public client type. It satisfies the declared {@link MirthClient}\n * contract but widens `putServerConfiguration` to accept the optional Mirth\n * query-param flags. The widened signature is structurally assignable to the\n * one-arg contract (the extra parameter is optional), so a `MirthClientExt`\n * is a valid `MirthClient` wherever the bare contract is expected.\n */\nexport interface MirthClientExt extends MirthClient {\n putServerConfiguration(config: CanonicalConfig, options?: PutServerConfigurationOptions): Promise<void>;\n /** GET /server/id: the installation's ID, which a configuration restore does not change (verified on 4.5.2). */\n getServerId(): Promise<string>;\n /** GET /server/configuration as the server's own XML (the Administrator's Backup Config document). */\n getServerConfigurationXml(): Promise<string>;\n /** PUT /server/configuration from backup XML, as the Administrator's Restore Config does. */\n putServerConfigurationXml(xml: string, options?: PutServerConfigurationOptions): Promise<void>;\n /** GET /channels/{id}, unwrapped; includes the tag and dependency data the server configuration omits. */\n getChannel(id: string): Promise<Record<string, unknown> | null>;\n /** Standalone templates remain readable after being removed from a library. */\n getCodeTemplate(id: string): Promise<Record<string, unknown> | null>;\n /** PUT /channels/{id}; creates the channel if the id is new. */\n putChannel(channel: Record<string, unknown>): Promise<void>;\n /** Release pooled connections so the process can exit promptly. */\n close(): Promise<void>;\n deleteChannel(id: string): Promise<void>;\n /** PUT /codeTemplates/{id}; creates the template if the id is new. */\n putCodeTemplate(template: Record<string, unknown>): Promise<void>;\n deleteCodeTemplate(id: string): Promise<void>;\n /** PUT /codeTemplateLibraries: replaces the whole list (membership and library settings). */\n putCodeTemplateLibraries(libraries: Record<string, unknown>[]): Promise<void>;\n /** PUT /server/globalScripts, from the `globalScripts` value of a server configuration. */\n putGlobalScripts(globalScripts: unknown): Promise<void>;\n /** POST /channels/{id}/_deploy; throws if deployment fails. */\n deployChannel(id: string): Promise<void>;\n /** Ids of the channels currently deployed (GET /channels/statuses). */\n getDeployedChannelIds(): Promise<Set<string>>;\n}\n\n/** Internal HTTP verbs we use. */\ntype HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n\n/** Options for the low-level authenticated request helper. */\ninterface RequestOptions {\n /** Already-serialized request body. */\n body?: string;\n /** Query parameters appended to the URL. */\n query?: Record<string, unknown>;\n /** Additional headers merged over the defaults. */\n headers?: Record<string, string>;\n}\n\n/** Shape of the (unwrapped) Mirth login status payload we read. */\ninterface LoginStatusPayload {\n status?: string;\n message?: string | null;\n}\n\n/** The single top-level wrapper key of a Mirth backup / server config document. */\nconst SERVER_CONFIG_KEY = 'serverConfiguration';\n\n/**\n * Unwrap a Jackson-style single-key wrapper. Mirth wraps many responses in a\n * single top-level namespace key. If the value has exactly one top-level key we\n * unwrap it; otherwise we return it unchanged (defensive against the wrapper\n * being named differently or absent).\n */\nfunction unwrapSingleKey(value: Record<string, unknown>): unknown {\n const keys = Object.keys(value);\n if (keys.length === 1) {\n return value[keys[0] as string];\n }\n return value;\n}\n\n/**\n * MirthClient implementation. Created via {@link createMirthClient}.\n */\nclass MirthClientImpl implements MirthClientExt {\n private readonly config: ClientConfig;\n private readonly baseUrl: string;\n private readonly cookieJar: CookieJar;\n /** Our own pool (not the global one) so `close()` can release it. */\n private readonly dispatcher: Agent;\n\n private authenticated = false;\n /** Single in-flight login promise (concurrency guard). */\n private loginPromise: Promise<void> | null = null;\n\n constructor(config: ClientConfig) {\n this.config = config;\n const protocol = config.https !== false ? 'https' : 'http';\n this.baseUrl = `${protocol}://${config.host}:${config.port}/api`;\n this.cookieJar = new CookieJar();\n\n this.dispatcher = new Agent(config.tlsFingerprint\n ? { connect: pinnedConnector(config.tlsFingerprint) }\n : config.disableTlsCheck ? { connect: { rejectUnauthorized: false } } : {});\n }\n\n isAuthenticated(): boolean {\n return this.authenticated;\n }\n\n /**\n * Establish a session. Concurrent calls share a single in-flight login.\n */\n async login(): Promise<void> {\n if (this.loginPromise) {\n return this.loginPromise;\n }\n\n this.loginPromise = (async () => {\n try {\n const loginUrl = `${this.baseUrl}/users/_login`;\n\n const body = new URLSearchParams({\n username: this.config.username,\n password: this.config.password,\n });\n\n const response = await this.send(loginUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-Requested-With': 'XMLHttpRequest',\n Accept: 'application/json',\n },\n body: body.toString(),\n });\n\n await this.storeCookies(response, this.baseUrl);\n\n if (!response.ok) {\n // Not the body: a login endpoint's error page can echo the request.\n await response.body?.cancel();\n throw new Error(`Login failed: HTTP ${response.status} ${response.statusText}`.trimEnd());\n }\n\n const result = (await response.json()) as Record<string, unknown>;\n\n // Mirth wraps the result, e.g.\n // { 'com.mirth.connect.model.LoginStatus': { status: 'SUCCESS', message: null } }\n const payload = unwrapSingleKey(result) as LoginStatusPayload;\n\n if (payload.status !== 'SUCCESS') {\n throw new Error(`Login failed: ${payload.status} - ${payload.message ?? 'Unknown error'}`);\n }\n\n this.authenticated = true;\n } finally {\n this.loginPromise = null;\n }\n })();\n\n return this.loginPromise;\n }\n\n /**\n * End the session and clear local auth state + cookies.\n */\n async logout(): Promise<void> {\n if (!this.authenticated) {\n return;\n }\n\n try {\n const logoutUrl = `${this.baseUrl}/users/_logout`;\n const cookieString = await this.cookieJar.getCookieString(logoutUrl);\n await this.send(logoutUrl, {\n method: 'POST',\n headers: {\n 'X-Requested-With': 'XMLHttpRequest',\n ...(cookieString ? { Cookie: cookieString } : {}),\n },\n });\n } finally {\n this.authenticated = false;\n await this.cookieJar.removeAllCookies();\n }\n }\n\n /**\n * GET /server/configuration -> canonical config.\n *\n * Requests JSON and validates the envelope and core resource collections\n * before this snapshot can be used to replace a tree or plan server writes.\n */\n async getServerConfiguration(): Promise<CanonicalConfig> {\n const response = await this.request('GET', '/server/configuration', {\n headers: { Accept: 'application/json' },\n });\n\n let json: unknown;\n try { json = await response.json(); }\n catch { throw new Error('invalid server configuration response: expected JSON'); }\n return liveConfiguration(json);\n }\n\n /**\n * PUT /server/configuration <- canonical config.\n *\n * Re-wraps the canonical config as `{ serverConfiguration: config }` and\n * forwards the optional `deploy` / `overwriteConfigMap` flags as query params.\n */\n async putServerConfiguration(config: CanonicalConfig, options: PutServerConfigurationOptions = {}): Promise<void> {\n const query: Record<string, unknown> = {};\n if (options.deploy !== undefined) {\n query.deploy = options.deploy;\n }\n if (options.overwriteConfigMap !== undefined) {\n query.overwriteConfigMap = options.overwriteConfigMap;\n }\n\n const wrapped = { [SERVER_CONFIG_KEY]: config };\n\n await this.request('PUT', '/server/configuration', {\n query,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify(wrapped),\n });\n }\n\n async getServerId(): Promise<string> {\n // JSON is refused (406); the ID comes as plain text. Mirth generates a UUID but reads it from\n // appdata/server.id, which admins can set to any name (one 4.5.0 server answers \"mirth-gov\").\n // It is only compared and printed, so accept one printable line and refuse control and\n // format characters (terminal escapes, newlines, bidi overrides).\n const response = await this.request('GET', '/server/id', { headers: { Accept: 'text/plain' } });\n const id = (await response.text()).trim();\n if (!/^[^\\p{Cc}\\p{Cf}]{1,255}$/u.test(id)) throw new Error('the server returned an invalid installation ID');\n return id;\n }\n\n async getServerConfigurationXml(): Promise<string> {\n const response = await this.request('GET', '/server/configuration', { headers: { Accept: 'application/xml' } });\n return response.text();\n }\n\n async putServerConfigurationXml(xml: string, options: PutServerConfigurationOptions = {}): Promise<void> {\n await this.request('PUT', '/server/configuration', {\n query: { deploy: options.deploy, overwriteConfigMap: options.overwriteConfigMap },\n headers: { 'Content-Type': 'application/xml', Accept: 'application/json' },\n body: xml,\n });\n }\n\n // --- per-resource ---------------------------------------------------------\n // Override is on: Mirth does not reject a stale revision anyway (verified on\n // 4.5.2), so conflict detection happens in the push planner instead.\n\n async getChannel(id: string): Promise<Record<string, unknown> | null> {\n return this.getResource(`/channels/${encodeURIComponent(id)}`);\n }\n\n async getCodeTemplate(id: string): Promise<Record<string, unknown> | null> {\n return this.getResource(`/codeTemplates/${encodeURIComponent(id)}`);\n }\n\n private async getResource(resourcePath: string): Promise<Record<string, unknown> | null> {\n const response = await this.request('GET', resourcePath, {\n headers: { Accept: 'application/json' },\n }).catch((err: Error & ApiError) => {\n if (err.status === 404) return null;\n throw err;\n });\n if (!response) return null;\n const text = await response.text();\n if (text.trim() === '') return null;\n const parsed = JSON.parse(text) as Record<string, unknown> | null;\n return parsed === null ? null : unwrapSingleKey(parsed) as Record<string, unknown> | null;\n }\n\n async close(): Promise<void> {\n await this.dispatcher.close();\n }\n\n async putChannel(channel: Record<string, unknown>): Promise<void> {\n await this.sendJson('PUT', `/channels/${encodeURIComponent(String(channel.id))}`, { channel }, { override: true });\n }\n\n async deleteChannel(id: string): Promise<void> {\n await this.request('DELETE', `/channels/${encodeURIComponent(id)}`);\n }\n\n async putCodeTemplate(template: Record<string, unknown>): Promise<void> {\n await this.sendJson('PUT', `/codeTemplates/${encodeURIComponent(String(template.id))}`, { codeTemplate: template }, { override: true });\n }\n\n async deleteCodeTemplate(id: string): Promise<void> {\n await this.request('DELETE', `/codeTemplates/${encodeURIComponent(id)}`);\n }\n\n async putCodeTemplateLibraries(libraries: Record<string, unknown>[]): Promise<void> {\n await this.sendJson('PUT', '/codeTemplateLibraries', { list: { codeTemplateLibrary: libraries } }, { override: true });\n }\n\n async putGlobalScripts(globalScripts: unknown): Promise<void> {\n await this.sendJson('PUT', '/server/globalScripts', { map: globalScripts });\n }\n\n async getDeployedChannelIds(): Promise<Set<string>> {\n const response = await this.request('GET', '/channels/statuses', { headers: { Accept: 'application/json' } });\n const text = await response.text();\n const ids = new Set<string>();\n // Undeployed channels have no status entry; collect every channelId present.\n for (const m of text.matchAll(/\"channelId\"\\s*:\\s*\"([^\"]+)\"/g)) ids.add(m[1]!);\n return ids;\n }\n\n async deployChannel(id: string): Promise<void> {\n await this.request('POST', `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });\n }\n\n /** Send a JSON body; Mirth answers some updates with `{\"boolean\": false}` instead of an error status. */\n private async sendJson(method: HttpMethod, path: string, body: unknown, query?: Record<string, unknown>): Promise<void> {\n const response = await this.request(method, path, {\n query,\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify(body),\n });\n const text = await response.text();\n if (/^\\s*\\{\\s*\"boolean\"\\s*:\\s*false\\s*\\}\\s*$/.test(text)) {\n throw new Error(`${method} ${path}: the server refused the update`);\n }\n }\n\n // --- internal transport ---------------------------------------------------\n\n /**\n * Make an authenticated request. Ensures login, attaches/stores cookies, and\n * on a 401 while authenticated resets auth, re-logs in once, and retries.\n * Throws an {@link ApiError}-shaped error on a non-2xx response.\n */\n private async request(method: HttpMethod, path: string, options: RequestOptions = {}, isRetry = false): Promise<Response> {\n if (!this.authenticated) {\n await this.login();\n }\n\n const url = this.buildUrl(path, options.query);\n\n const headers: Record<string, string> = {\n 'X-Requested-With': 'XMLHttpRequest',\n ...options.headers,\n };\n\n const cookieString = await this.cookieJar.getCookieString(url);\n if (cookieString) {\n headers.Cookie = cookieString;\n }\n\n const response = await this.send(url, { method, headers, body: options.body });\n\n await this.storeCookies(response, url);\n\n // 401 while authenticated -> reset auth, re-login once, retry exactly once.\n if (response.status === 401 && this.authenticated && !isRetry) {\n this.authenticated = false;\n await this.login();\n return this.request(method, path, options, true);\n }\n\n if (!response.ok) {\n throw await this.toApiError(response);\n }\n\n return response;\n }\n\n /**\n * fetch through this client's pool, with network failures explained. Never\n * follows a redirect: fetch re-sends a 307/308 body, so a redirected login\n * would post the username and password to wherever the server points.\n */\n private async send(url: string, init: RequestInit): Promise<Response> {\n let response: Response;\n try {\n response = await fetch(url, {\n ...init,\n redirect: 'manual',\n // @ts-expect-error - dispatcher is a Node.js/undici specific option\n dispatcher: this.dispatcher,\n });\n } catch (err) {\n throw connectionError(url, err);\n }\n if (response.status >= 300 && response.status < 400) {\n await response.body?.cancel();\n throw new Error(`the server answered ${new URL(url).pathname} with a redirect (HTTP ${response.status}${redirectTarget(url, response)}); ` +\n 'channelvault does not follow redirects, so credentials and session cookies are never sent elsewhere. Connect to the address it redirects to: check https vs --no-https, --host and --port (or MIRTH_HOST/MIRTH_PORT)');\n }\n return response;\n }\n\n /** Build an absolute URL with an optional query string. */\n private buildUrl(path: string, query?: Record<string, unknown>): string {\n const url = `${this.baseUrl}${path}`;\n if (!query || Object.keys(query).length === 0) {\n return url;\n }\n\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) {\n continue;\n }\n searchParams.append(key, String(value));\n }\n\n const qs = searchParams.toString();\n return qs ? `${url}?${qs}` : url;\n }\n\n /** Persist any `set-cookie` from a response into the jar. */\n private async storeCookies(response: Response, url: string): Promise<void> {\n // One entry per header: get('set-cookie') joins them with \", \", which also\n // appears inside a cookie's Expires date.\n for (const cookie of response.headers.getSetCookie()) {\n await this.cookieJar.setCookie(cookie, url);\n }\n }\n\n /** Build an ApiError-shaped Error from a non-2xx response. */\n private async toApiError(response: Response): Promise<Error & ApiError> {\n let body: unknown;\n try {\n body = await response.text();\n } catch {\n // ignore body read errors\n }\n\n // An error body can echo the payload sent, credentials included, in any\n // form (escaped, truncated, reformatted), so no redaction of it is\n // complete: it is left out unless asked for. When included it is whole and\n // unnormalized, so the caller's scrub of known values can still match.\n const text = typeof body === 'string' ? redactSecretsInText(readableBody(body)).trim() : '';\n const reason =\n text === '' ? '' : this.config.includeResponseBodies ? `: ${text}` : ' (server response withheld; it may echo credentials)';\n const message = `HTTP ${response.status}: ${response.statusText}${reason}`;\n const error = new Error(message) as Error & ApiError;\n error.status = response.status;\n error.statusText = response.statusText;\n error.message = message;\n error.body = text;\n return error;\n }\n}\n\nconst XML_ENTITIES: Readonly<Record<string, string>> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" };\n\n/**\n * An error body as the text a person reads: JSON as its decoded values, XML as\n * its decoded text. Anything that redacts by value (the CLI knows the secrets\n * sent) then sees a secret as it was sent, not escaped as `\\\"` or `&`.\n * Credential fields are replaced while their names are still known.\n */\nexport function readableBody(body: string): string {\n const trimmed = body.trim();\n // Any JSON value: a bare string can carry \\u escapes too.\n if (/^[[{\"]/.test(trimmed)) {\n try {\n return flattenJson(JSON.parse(trimmed) as unknown);\n } catch {\n // not JSON after all\n }\n }\n if (!trimmed.startsWith('<')) return trimmed;\n // Mirth's HTML error pages say only \"Request failed.\", so they add nothing.\n if (/^<(!doctype|html)/i.test(trimmed)) return '';\n // A marker that survives removing the tags.\n const REDACTED = '\\u0000redacted\\u0000';\n return trimmed\n .replace(/<([\\w.:-]+)>[^<]*<\\/\\1>/g, (whole, key: string) => (isSecretKey(key) ? ` ${key}: ${REDACTED} ` : whole))\n .replace(/<[^>]*>/g, ' ')\n .split(REDACTED)\n .join('<redacted>')\n .replace(/&(#x[0-9a-f]+|#[0-9]+|amp|lt|gt|quot|apos);/gi, (whole, e: string) =>\n e[0] === '#'\n ? String.fromCodePoint(e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10))\n : (XML_ENTITIES[e.toLowerCase()] ?? whole),\n );\n}\n\nfunction flattenJson(value: unknown, key = ''): string {\n if (typeof value === 'string') return key !== '' && isSecretKey(key) && value !== '' ? '<redacted>' : value;\n if (Array.isArray(value)) return value.map((v) => flattenJson(v, key)).join('; ');\n if (value !== null && typeof value === 'object') {\n return Object.entries(value).map(([k, v]) => `${k}: ${flattenJson(v, k)}`).join(', ');\n }\n return String(value);\n}\n\n/**\n * Factory for the live Mirth transport client.\n */\nexport function createMirthClient(config: ClientConfig): MirthClientExt {\n return new MirthClientImpl(config);\n}\n","/**\n * Find secrets that the key-name rules in `templatize` miss: credentials\n * embedded in URLs and connection strings, authorization headers, password\n * assignments in scripts, private keys and well-known token formats.\n *\n * Findings are reported by location and kind only; a secret value is never\n * printed. `extract` replaces just the secret part of each string with an\n * `{{env:NAME}}` placeholder, so the surrounding script or URL stays readable.\n */\nimport { createHash } from 'node:crypto';\n\nimport { CHANNEL_SCRIPT_KEYS, CODE_KEYS, type CanonicalConfig } from '../types.js';\nimport { derivedName, hasPlaceholder, isSecretKey, mapLeaves, placeholder, type Env, type Leaf } from './index.js';\n\nexport type SecretKind =\n | 'private-key'\n | 'url-credentials'\n | 'connection-string'\n | 'authorization-header'\n | 'db-connection-call'\n | 'assignment'\n | 'setter-call'\n | 'aws-access-key'\n | 'jwt'\n | 'github-token'\n | 'slack-token';\n\n/** A secret's position in a string. */\ninterface Span {\n start: number;\n end: number;\n}\n\ninterface Rule {\n kind: SecretKind;\n /** Suffix for the env variable name. */\n suffix: string;\n /** `script`: the value is JavaScript (a step, template or channel script). */\n spans(value: string, script: boolean): Span[];\n}\n\n/** Spans of capture group `group` (0 = whole match) of every match of `re`. */\nfunction regexSpans(re: RegExp, group: number): (value: string) => Span[] {\n return (value) => {\n const out: Span[] = [];\n for (const m of value.matchAll(re)) {\n const secret = m[group];\n if (secret === undefined) continue;\n // The secret is the last occurrence of its text within the match.\n const start = m.index + m[0].lastIndexOf(secret);\n out.push({ start, end: start + secret.length });\n }\n return out;\n };\n}\n\n/**\n * The fourth argument of `createDatabaseConnection(driver, url, user, password)`\n * when it is a string literal. Arguments are split at top-level commas, so\n * calls like `$('driver')` in earlier arguments don't throw it off.\n */\nfunction dbConnectionSpans(value: string): Span[] {\n const out: Span[] = [];\n for (const m of value.matchAll(/createDatabaseConnection\\s*\\(/g)) {\n let depth = 0;\n let quote: string | null = null;\n let argStart = m.index + m[0].length;\n const args: Span[] = [];\n for (let i = argStart; i < value.length; i += 1) {\n const c = value[i]!;\n if (quote) {\n if (c === '\\\\') i += 1;\n else if (c === quote) quote = null;\n continue;\n }\n if (c === '\"' || c === \"'\") quote = c;\n else if (c === '(' || c === '[' || c === '{') depth += 1;\n else if ((c === ')' || c === ']' || c === '}') && depth > 0) depth -= 1;\n else if ((c === ',' && depth === 0) || c === ')') {\n args.push({ start: argStart, end: i });\n argStart = i + 1;\n if (c === ')') break;\n }\n }\n const pw = args[3];\n if (!pw) continue;\n const literal = /^\\s*([\"'])(.+)\\1\\s*$/s.exec(value.slice(pw.start, pw.end));\n if (literal) {\n const start = value.indexOf(literal[2]!, pw.start);\n out.push({ start, end: start + literal[2]!.length });\n }\n }\n return out;\n}\n\n/**\n * The tail of `name = 'literal'` / `name: \"literal\"`: an optional default-value\n * prefix (`name || `, `name ?? `), then a quoted literal of 4+ characters on one\n * line. Braces are excluded so `${var}` templates and placeholders don't match. A\n * literal with spaces must also hold a digit or symbol, so prose such as\n * `secret = 'Not configured yet'` is not a secret.\n */\nconst ASSIGNED = String.raw`[\"']?\\s*[:=]\\s*(?:[\\w$.[\\]'\"]+\\s*(?:\\|\\||\\?\\?)\\s*)?([\"'])((?=\\S)(?:[^\"'{}\\s]{4,}|(?=[^\"'{}\\n]*[0-9@#$%^&*+=~|\\\\/<>_])[^\"'{}\\n]{4,}))\\1`;\n\n/** A connection-string value: up to the next delimiter, without surrounding spaces. */\nconst CONN_VALUE = String.raw`([^;&'\"\\s](?:[^;&'\"\\n]*[^;&'\"\\s])?)`;\n\n/**\n * String literals and comments of a script: where a connection string can\n * appear as text. Regex literals are not recognised, so a quote inside one\n * can shift what counts as a literal.\n */\nfunction textSpans(code: string): Span[] {\n const out: Span[] = [];\n let i = 0;\n while (i < code.length) {\n const c = code[i]!;\n const next = code[i + 1];\n if (c === '/' && (next === '/' || next === '*')) {\n const close = next === '/' ? code.indexOf('\\n', i) : code.indexOf('*/', i + 2);\n const end = close < 0 ? code.length : close;\n out.push({ start: i + 2, end });\n i = end + 2;\n } else if (c === '\"' || c === \"'\" || c === '`') {\n let j = i + 1;\n while (j < code.length && code[j] !== c && (c === '`' || code[j] !== '\\n')) j += code[j] === '\\\\' ? 2 : 1;\n out.push({ start: i + 1, end: Math.min(j, code.length) });\n i = j + 1;\n } else {\n i += 1;\n }\n }\n return out;\n}\n\n/** Apply `spans` to a whole data value, but only to the text parts of a script. */\nfunction outsideCode(spans: (value: string) => Span[]): (value: string, script: boolean) => Span[] {\n return (value, script) =>\n script\n ? textSpans(value).flatMap((t) => spans(value.slice(t.start, t.end)).map((s) => ({ start: s.start + t.start, end: s.end + t.start })))\n : spans(value);\n}\n\n// Earlier rules win where spans overlap: a private key block may contain text\n// other rules match, and `token = 'ghp_…'` is one secret, not two.\nconst RULES: Rule[] = [\n {\n kind: 'private-key',\n suffix: 'PRIVATE_KEY',\n spans: regexSpans(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, 0),\n },\n { kind: 'aws-access-key', suffix: 'AWS_ACCESS_KEY', spans: regexSpans(/\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b/g, 0) },\n { kind: 'jwt', suffix: 'TOKEN', spans: regexSpans(/\\beyJ[A-Za-z0-9_-]{8,}\\.eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}/g, 0) },\n { kind: 'github-token', suffix: 'TOKEN', spans: regexSpans(/\\b(?:ghp|gho|ghs|ghu|github_pat)_[A-Za-z0-9_]{20,}/g, 0) },\n { kind: 'slack-token', suffix: 'TOKEN', spans: regexSpans(/\\bxox[abprs]-[A-Za-z0-9-]{10,}/g, 0) },\n // user:password@host. The user part stops at ';', '?' and '&' so a JDBC\n // parameter like `user=svc@srv` is not mistaken for credentials.\n { kind: 'url-credentials', suffix: 'PASSWORD', spans: regexSpans(/\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s:/@'\";?&]+:([^\\s@'\"/;?&]+)@/gi, 1) },\n // Drivers trim around `=` and the value, so spaces are allowed there. In a\n // script only string literals and comments are searched: `pwd=$('x')` is code.\n {\n kind: 'connection-string',\n suffix: 'PASSWORD',\n spans: outsideCode(regexSpans(new RegExp(String.raw`[;?&]\\s*(?:password|pwd)\\s*=\\s*${CONN_VALUE}`, 'gi'), 1)),\n },\n // Leading the whole value (`Password=…;Server=…`), when another key=value follows.\n {\n kind: 'connection-string',\n suffix: 'PASSWORD',\n spans: outsideCode(regexSpans(new RegExp(String.raw`^\\s*(?:password|pwd)\\s*=\\s*${CONN_VALUE}(?=\\s*;\\s*[\\w ]+=)`, 'gi'), 1)),\n },\n // Case-sensitive, and the credential must contain a digit or a base64/token\n // symbol, so prose like \"Basic authentication\" does not match.\n {\n kind: 'authorization-header',\n suffix: 'TOKEN',\n spans: regexSpans(/\\b(?:Basic|Bearer)\\s+((?=[A-Za-z0-9+/=._~-]*[0-9+/=])[A-Za-z0-9+/=._~-]{12,})/g, 1),\n },\n { kind: 'db-connection-call', suffix: 'DB_PASSWORD', spans: dbConnectionSpans },\n // name = 'literal' where the name ends in a secret word: password, dbPassword,\n // db_password, DB_PASSWORD, apiKey, authToken… (not tokenizer, not ==).\n // Also the default-value idiom: apiKey = apiKey || 'literal' (or ??).\n {\n kind: 'assignment',\n suffix: 'PASSWORD',\n spans: regexSpans(new RegExp(`(?<![\\\\w$])[\\\\w$]*?(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?key|token)${ASSIGNED}`, 'gi'), 2),\n },\n // `pass` as a whole name or a word boundary within one (pass, dbPass,\n // DB_PASS, sftp_pass), case-sensitive so bypass and compass don't match,\n // and not after words that make it an ordinary noun (byPass, firstPass).\n {\n kind: 'assignment',\n suffix: 'PASSWORD',\n spans: regexSpans(new RegExp(`(?<![\\\\w$])(?:pass|PASS|[\\\\w$]*[a-z0-9](?<!(?:[bB]y|[fF]irst|[sS]econd|[tT]hird|[lL]ast|[nN]ext|[oO]ne|[sS]ingle|[mM]ulti|[eE]very|[cC]om|[sS]ur|[oO]ver|[uU]nder))(?:Pass|PASS)|[\\\\w$]*_(?:pass|PASS))${ASSIGNED}`, 'g'), 2),\n },\n // conn.setPassword('literal'), props.setApiKey(\"literal\")…\n {\n kind: 'setter-call',\n suffix: 'PASSWORD',\n spans: regexSpans(/\\bset[A-Za-z]*(?:Password|Passwd|Passphrase|Secret|Token|ApiKey)\\s*\\(\\s*([\"'])([^\"'\\n]{4,})\\1\\s*\\)/g, 2),\n },\n];\n\n/** A Mirth `${variable}` or one of our placeholders is a reference, not a secret. */\nfunction isReference(secret: string): boolean {\n return secret.includes('${') || hasPlaceholder(secret);\n}\n\nexport interface Finding {\n location: string;\n kind: SecretKind;\n /** Where it is, for people: enclosing channel/connector names and the field. */\n where: string;\n /** Identifies the surrounding text (secret removed), for allow entries. */\n context: string;\n}\n\n/**\n * A known false positive. `context` ties it to the surrounding text as well as\n * the location, so an entry for a transformer step at index 2 stops matching\n * if a different step moves into that index.\n */\nexport interface AllowEntry {\n location: string;\n kind: SecretKind;\n context: string;\n note?: string;\n}\n\nexport type ScanMode = 'find' | 'extract' | 'redact';\n\nexport interface ScanResult {\n config: CanonicalConfig;\n findings: Finding[];\n /** extract mode: values for the env file (only ones it doesn't already hold). Never print these. */\n envUpdates: Record<string, string>;\n}\n\ninterface Hit extends Span {\n rule: Rule;\n}\n\n/** Every secret span in `value`, earlier rules winning overlaps, in position order. */\nfunction hitsIn(value: string, script = false): Hit[] {\n const taken: Hit[] = [];\n for (const rule of RULES) {\n for (const span of rule.spans(value, script)) {\n if (span.end <= span.start || isReference(value.slice(span.start, span.end))) continue;\n if (taken.some((t) => span.start < t.end && t.start < span.end)) continue;\n taken.push({ ...span, rule });\n }\n }\n return taken.sort((a, b) => a.start - b.start);\n}\n\nconst SCRIPT_KEYS: ReadonlySet<string> = new Set<string>([...CODE_KEYS, ...CHANNEL_SCRIPT_KEYS]);\n\n/** Script leaves: step, template and channel code, and the global scripts. */\nfunction isScript(leaf: Leaf): boolean {\n return SCRIPT_KEYS.has(leaf.key) || leaf.section === 'globalScripts';\n}\n\n/** `value` with every secret a rule recognises replaced by a marker, for messages. */\nexport function redactSecretsInText(text: string): string {\n // Credential fields echoed as JSON (\"passcode\": \"…\") or XML (<keyPW>…</keyPW>),\n // by the field names `templatize` extracts, then the value rules.\n const value = text\n .replace(/(\"([\\w.-]+)\"\\s*:\\s*\")((?:[^\"\\\\]|\\\\.)+)\"/g, (whole, head: string, key: string) => (isSecretKey(key) ? `${head}<redacted>\"` : whole))\n .replace(/<([\\w.:-]+)>([^<]+)<\\/\\1>/g, (whole, key: string) => (isSecretKey(key) ? `<${key}><redacted></${key}>` : whole));\n let out = '';\n let at = 0;\n for (const h of hitsIn(value)) {\n out += `${value.slice(at, h.start)}<redacted ${h.rule.kind}>`;\n at = h.end;\n }\n return out + value.slice(at);\n}\n\n/** Hash of the string with every secret removed: stable while its text is, and holds no secret. */\nfunction contextOf(value: string, hits: Hit[]): string {\n let redacted = '';\n let at = 0;\n for (const h of hits) {\n redacted += `${value.slice(at, h.start)}\\u0000${h.rule.kind}\\u0000`;\n at = h.end;\n }\n redacted += value.slice(at);\n return createHash('sha256').update(redacted).digest('hex').slice(0, 16);\n}\n\n/**\n * Scan every string leaf. `find` reports only; `extract` swaps each secret\n * for a placeholder and returns the values; `redact` swaps it for a marker\n * (for display, e.g. in `diff`).\n */\nexport function scanSecrets(config: CanonicalConfig, opts: { mode: ScanMode; allow?: AllowEntry[]; env?: Env }): ScanResult {\n const allowed = new Set((opts.allow ?? []).map((a) => `${a.location}#${a.kind}#${a.context}`));\n const env = opts.env ?? {};\n const findings: Finding[] = [];\n const envUpdates: Record<string, string> = {};\n const assigned = new Map<string, string>(); // name -> value, this run\n\n // Names placeholders already use belong to their locations; each new\n // placeholder gets its own name, so rotating one secret never changes another.\n const inUse = new Set<string>();\n mapLeaves(config, (value) => {\n for (const m of value.matchAll(/\\{\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}\\}/g)) inUse.add(m[1]!);\n return value;\n });\n const nameFor = (leaf: Leaf, rule: Rule, value: string): string => {\n const base = `${derivedName(leaf)}__${rule.suffix}`;\n for (let n = 1; ; n += 1) {\n const name = n === 1 ? base : `${base}_${n}`;\n if (assigned.has(name) || inUse.has(name)) continue;\n if (env[name] === undefined || env[name] === value) {\n assigned.set(name, value);\n // A value the environment already holds (the file, or CI's process\n // environment) is not written to the file again.\n if (env[name] !== value) envUpdates[name] = value;\n return name;\n }\n }\n };\n\n const out = mapLeaves(config, (value, leaf) => {\n const hits = hitsIn(value, isScript(leaf));\n if (hits.length === 0) return value;\n const context = contextOf(value, hits);\n let result = '';\n let at = 0;\n for (const h of hits) {\n if (allowed.has(`${leaf.location}#${h.rule.kind}#${context}`)) continue;\n findings.push({ location: leaf.location, kind: h.rule.kind, where: [...leaf.labels, leaf.key].join(' › '), context });\n if (opts.mode === 'find') continue;\n const secret = value.slice(h.start, h.end);\n const replacement = opts.mode === 'extract' ? placeholder(nameFor(leaf, h.rule, secret)) : `<redacted ${h.rule.kind}>`;\n result += value.slice(at, h.start) + replacement;\n at = h.end;\n }\n return opts.mode === 'find' ? value : result + value.slice(at);\n });\n\n return { config: out, findings, envUpdates };\n}\n\n/**\n * Known secret values that still appear verbatim somewhere in `config`: a\n * repeat no rule recognised (a default argument, a URL fragment). Values\n * shorter than 8 characters are skipped; short ones such as a database name\n * reused as a password match too much ordinary text.\n */\nexport function findEchoes(config: CanonicalConfig, secrets: Env): Array<{ name: string; where: string }> {\n const values = Object.entries(secrets).filter((e): e is [string, string] => typeof e[1] === 'string' && e[1].length >= 8);\n const out: Array<{ name: string; where: string }> = [];\n if (values.length === 0) return out;\n mapLeaves(config, (value, leaf) => {\n for (const [name, secret] of values) {\n if (value.includes(secret)) out.push({ name, where: [...leaf.labels, leaf.key].join(' › ') });\n }\n return value;\n });\n return out;\n}\n\nexport function formatFindings(findings: Finding[]): string {\n return findings\n .map((f) => ` ${f.kind.padEnd(20)} ${f.where}\\n ${''.padEnd(20)} at ${f.location} context ${f.context}`)\n .join('\\n');\n}\n","/**\n * Keep secrets and per-environment values out of the working tree.\n *\n * A string in the tree may contain `{{env:NAME}}` placeholders. `render`\n * replaces them from an environment (a `.env` file plus `process.env`) before\n * anything is sent to Mirth or written as XML. `templatize` goes the other way\n * on `pull`/`explode`: it swaps credential values for placeholders, returning\n * the values so the caller can store them in `.env`.\n *\n * The syntax is not Mirth's `${...}`, which connector fields already use for\n * Velocity variables (`${message.encodedData}`).\n */\nimport type { CanonicalConfig, Json } from '../types.js';\n\nexport type Env = Readonly<Record<string, string | undefined>>;\n\nconst PLACEHOLDER = /\\{\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}\\}/g;\n\n/**\n * Credential-bearing keys: `password`, `smtpPassword`, `passPhrase`, `apiToken`,\n * and the DICOM connector's `passcode`, `keyPW`, `keyStorePW`, `trustStorePW`.\n */\nconst SECRET_KEY = /(password|passwd|passphrase|passcode|secret|token|pw|pwd|(?:api|access|secret|private)[_-]?key)$/i;\n\n/** Mirth's configuration-map entry value holder (XML and live shapes). */\nconst CONFIG_PROPERTY = 'com.mirth.connect.util.ConfigurationProperty';\n\nexport function placeholder(name: string): string {\n return `{{env:${name}}}`;\n}\n\nexport function hasPlaceholder(value: string): boolean {\n PLACEHOLDER.lastIndex = 0;\n return PLACEHOLDER.test(value);\n}\n\n/** Fill every placeholder in `value`; names with no value are collected in `missing`. */\nfunction fill(value: string, env: Env, missing: Set<string>): string {\n return value.replace(PLACEHOLDER, (whole, name: string) => {\n const v = env[name];\n if (v === undefined) {\n missing.add(name);\n return whole;\n }\n return v;\n });\n}\n\n/**\n * Replace every placeholder in the config. Throws, naming every missing\n * variable, rather than sending a literal `{{env:…}}` to a server.\n */\nexport function render(config: CanonicalConfig, env: Env): CanonicalConfig {\n const missing = new Set<string>();\n const walk = (node: Json): Json => {\n if (typeof node === 'string') return fill(node, env, missing);\n if (Array.isArray(node)) return node.map(walk);\n if (node && typeof node === 'object') {\n const out: Record<string, Json> = {};\n for (const [k, v] of Object.entries(node)) out[k] = walk(v);\n return out;\n }\n return node;\n };\n const out = walk(config) as CanonicalConfig;\n if (missing.size > 0) {\n throw new Error(\n `missing values for ${[...missing].sort().join(', ')} (set them in the env file or the environment)`,\n );\n }\n return out;\n}\n\n// --- locations -------------------------------------------------------------\n\ntype Segment = string;\n\n/**\n * A stable address for a value: array elements are identified by `id` or\n * `metaDataId` when they have one, and configuration-map entries by their key,\n * so removing, reordering or adding elements does not move an existing\n * placeholder to a different value.\n */\nfunction elementSegment(el: Json, index: number): Segment {\n if (el && typeof el === 'object' && !Array.isArray(el)) {\n const id = el['id'] ?? el['metaDataId'];\n if (typeof id === 'string' || typeof id === 'number') return `[${String(id)}]`;\n const mapKey = CONFIG_PROPERTY in el ? configMapKeyOf(el) : undefined;\n if (mapKey !== undefined) return `[${mapKey}]`;\n }\n return `[${index}]`;\n}\n\nfunction configMapKeyOf(entry: Record<string, Json>): string | undefined {\n const key = entry['string'];\n if (typeof key === 'string') return key;\n return Array.isArray(key) && typeof key[0] === 'string' ? key[0] : undefined;\n}\n\nexport interface Leaf {\n location: string;\n key: string;\n /** `name`s of enclosing objects (channel, connector), outermost first. */\n labels: string[];\n /** Top-level section the leaf lives in (`serverSettings`, `channels`, …). */\n section: string;\n /** The configuration-map key when this leaf is a map entry's value. */\n configMapKey?: string;\n}\n\n/** Visit every string leaf, allowing the visitor to replace it. */\nexport function mapLeaves(config: CanonicalConfig, visit: (value: string, leaf: Leaf) => string): CanonicalConfig {\n const walk = (node: Json, key: string, path: Segment[], labels: string[], section: string, cmKey?: string): Json => {\n if (typeof node === 'string') {\n return visit(node, { location: path.join('/'), key, labels, section, configMapKey: cmKey });\n }\n if (Array.isArray(node)) {\n return node.map((el, i) => walk(el, key, [...path.slice(0, -1), `${path[path.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));\n }\n if (node && typeof node === 'object') {\n const name = node['name'];\n const inner = typeof name === 'string' && name.trim() !== '' ? [...labels, name] : labels;\n // A configuration-map entry: { string: key | [key], ConfigurationProperty: { value, comment } }.\n const mapKey = section === 'configurationMap' && CONFIG_PROPERTY in node ? configMapKeyOf(node) : cmKey;\n const out: Record<string, Json> = {};\n for (const [k, v] of Object.entries(node)) {\n out[k] = walk(v, k, [...path, k], inner, section || k, mapKey);\n }\n return out;\n }\n return node;\n };\n return walk(config, '', [], [], '') as CanonicalConfig;\n}\n\n/** A field name that holds a credential (see {@link SECRET_KEY}). */\nexport function isSecretKey(key: string): boolean {\n return SECRET_KEY.test(key);\n}\n\nfunction isSecret(leaf: Leaf): boolean {\n if (leaf.section === 'configurationMap') return leaf.configMapKey !== undefined && leaf.key === 'value';\n return SECRET_KEY.test(leaf.key);\n}\n\nexport function envName(parts: string[]): string {\n return parts\n .map((p) => p.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, ''))\n .filter(Boolean)\n .join('__')\n .replace(/^(?=[0-9])/, '_');\n}\n\nexport function derivedName(leaf: Leaf): string {\n if (leaf.configMapKey !== undefined) return envName(['CONFIG_MAP', leaf.configMapKey]);\n const context = leaf.labels.length > 0 ? leaf.labels : [leaf.section];\n return envName([...context, leaf.key]);\n}\n\n/**\n * Replace every literal credential (by field name, as `templatize` finds them)\n * with a marker, for display. `diff` uses it so a password typed into the\n * tree by hand is never printed.\n */\nexport function redactKnownSecrets(config: CanonicalConfig): CanonicalConfig {\n return mapLeaves(config, (value, leaf) => (isSecret(leaf) && value !== '' && !hasPlaceholder(value) ? '<redacted>' : value));\n}\n\n// --- templatize ------------------------------------------------------------\n\nexport interface TemplatizeResult {\n config: CanonicalConfig;\n /** Values to write to the env file (new or changed on the server). Never print these. */\n envUpdates: Record<string, string>;\n /** Human-readable notes: placeholders dropped, secrets updated from the server. */\n notes: string[];\n}\n\n/** Placeholder-bearing strings in a previously pulled (un-rendered) tree, by location. */\nfunction templatesOf(config: CanonicalConfig | null): Map<string, string> {\n const out = new Map<string, string>();\n if (config) {\n mapLeaves(config, (value, leaf) => {\n if (hasPlaceholder(value)) out.set(leaf.location, value);\n return value;\n });\n }\n return out;\n}\n\n/**\n * Read `value` as `template` with its placeholders filled in: returns each\n * placeholder's value, or null if the text around them differs. A name used\n * twice must match the same text both times.\n */\nfunction matchTemplate(template: string, value: string): Map<string, string> | null {\n const names: string[] = [];\n let pattern = '^';\n let at = 0;\n for (const m of template.matchAll(PLACEHOLDER)) {\n pattern += template.slice(at, m.index).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const seen = names.indexOf(m[1]!);\n if (seen >= 0) {\n pattern += `\\\\${seen + 1}`;\n } else {\n names.push(m[1]!);\n pattern += '([\\\\s\\\\S]*?)';\n }\n at = m.index + m[0].length;\n }\n pattern += `${template.slice(at).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}$`;\n const match = new RegExp(pattern).exec(value);\n return match ? new Map(names.map((n, i) => [n, match[i + 1]!])) : null;\n}\n\n/**\n * Replace credentials in a freshly fetched config with placeholders.\n *\n * `previous` is the existing tree (un-rendered), so placeholders the user\n * added by hand survive a re-pull as long as they still render to what the\n * server holds. `env` is what they render with.\n */\nexport function templatize(remote: CanonicalConfig, previous: CanonicalConfig | null, env: Env): TemplatizeResult {\n const templates = templatesOf(previous);\n const envUpdates: Record<string, string> = {};\n const notes: string[] = [];\n const assigned = new Map<string, string>(); // name -> value, this run\n const reserved = new Set<string>();\n for (const t of templates.values()) {\n for (const m of t.matchAll(PLACEHOLDER)) reserved.add(m[1]!);\n }\n\n /** A name no location uses yet, bound to `value`. Placeholders are never shared between locations. */\n const fresh = (base: string, value: string): string => {\n let name = base;\n for (let n = 2; assigned.has(name) || reserved.has(name); n += 1) name = `${base}_${n}`;\n assigned.set(name, value);\n if (env[name] !== value) envUpdates[name] = value;\n return name;\n };\n\n /**\n * Bind this location's placeholder values. A name another location already\n * holds with a different value (a shared placeholder whose credentials have\n * diverged) is split off under a new name, so rotating one credential never\n * changes another.\n */\n const bind = (template: string, values: Map<string, string>, rotated: boolean): string => {\n let out = template;\n for (const [name, value] of values) {\n const bound = assigned.get(name);\n if (bound !== undefined && bound !== value) {\n reserved.delete(name);\n const renamed = fresh(name, value);\n out = out.split(placeholder(name)).join(placeholder(renamed));\n notes.push(`${renamed}: split from ${name}, which another location holds with a different value`);\n continue;\n }\n assigned.set(name, value);\n if (env[name] !== value) {\n envUpdates[name] = value;\n if (rotated) notes.push(`${name}: server value differs from the env file; env file updated`);\n }\n }\n return out;\n };\n const envValues = (template: string): Map<string, string> =>\n new Map([...template.matchAll(PLACEHOLDER)].map((m) => [m[1]!, env[m[1]!]!] as const));\n\n const config = mapLeaves(remote, (value, leaf) => {\n const template = templates.get(leaf.location);\n if (template !== undefined) {\n const missing = new Set<string>();\n if (fill(template, env, missing) === value && missing.size === 0) return bind(template, envValues(template), false);\n // Same text around the placeholders, new values (a rotated secret):\n // keep the template and take the new values.\n const captured = matchTemplate(template, value);\n if (captured) return bind(template, captured, true);\n // Text edited elsewhere, secrets unchanged: put the placeholders back\n // where their values still appear. Lossless, since rendering restores\n // exactly this text.\n let restored = value;\n for (const m of template.matchAll(PLACEHOLDER)) {\n const v = env[m[1]!];\n if (v !== undefined && v.length >= 4) restored = restored.split(v).join(placeholder(m[1]!));\n }\n if (restored !== value) return bind(restored, envValues(restored), false);\n notes.push(`${leaf.location}: placeholder no longer matches the server; replaced with the server value`);\n return value;\n }\n if (isSecret(leaf) && value !== '' && !hasPlaceholder(value)) {\n return placeholder(fresh(derivedName(leaf), value));\n }\n return value;\n });\n\n return { config, envUpdates, notes };\n}\n","import type { CanonicalConfig } from '../types.js';\n\nconst object = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** Validate the live API envelope and core collections without dropping plugin fields. */\nexport function liveConfiguration(payload: unknown): CanonicalConfig {\n const bad = (detail: string): never => { throw new Error(`invalid server configuration response: ${detail}; nothing should be written from this snapshot`); };\n if (!object(payload) || Object.keys(payload).length !== 1 || !('serverConfiguration' in payload)) bad('expected the serverConfiguration wrapper');\n const config = (payload as Record<string, unknown>)['serverConfiguration'];\n if (!object(config)) bad('expected a configuration object');\n const c = config as Record<string, unknown>;\n if (typeof c['@version'] !== 'string' || !/^\\d+\\.\\d+(?:\\.\\d+)*(?:[-+][A-Za-z0-9.-]+)?$/.test(c['@version'])) bad('missing or invalid engine version');\n if (!('channels' in c)) bad('missing channels collection');\n const collection = (container: unknown, key: string, where: string): Record<string, unknown>[] => {\n if (container == null || container === '') return [];\n if (!object(container)) bad(`invalid ${where} collection`);\n if (!(key in (container as Record<string, unknown>)) && Object.keys(container as object).some(k => !k.startsWith('@'))) bad(`missing resource list in ${where}`);\n const raw = (container as Record<string, unknown>)[key];\n if (raw == null || raw === '') return [];\n const items = Array.isArray(raw) ? raw : [raw];\n for (const item of items) {\n if (!object(item) || typeof item.id !== 'string' || !item.id.trim() || typeof item.name !== 'string' || !item.name.trim()) bad(`invalid resource in ${where}`);\n if ('revision' in item && (!Number.isSafeInteger(item.revision) || Number(item.revision) < 0)) bad(`invalid revision in ${where}`);\n }\n return items as Record<string, unknown>[];\n };\n collection(c.channels, 'channel', 'channels');\n if ('codeTemplateLibraries' in c) {\n for (const library of collection(c.codeTemplateLibraries, 'codeTemplateLibrary', 'code template libraries')) {\n if ('codeTemplates' in library) collection(library.codeTemplates, 'codeTemplate', 'code templates');\n }\n }\n if ('channelGroups' in c) collection(c.channelGroups, 'channelGroup', 'channel groups');\n return c as CanonicalConfig;\n}\n"],"mappings":";AAkCO,SAAS,UAAU,GAA0B;AAClD,SACE,OAAO,MAAM,YACb,MAAM,QACN,CAAC,MAAM,QAAQ,CAAC,KAChB,OAAO,KAAK,CAAC,EAAE,WAAW,KAC1B,OAAQ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