imsg-mcp 1.25.2 → 1.25.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 +15 -0
- package/dist/{app-config-CK1zm-h1.js → app-config-DAwcDA3h.js} +2 -2
- package/dist/{app-config-CK1zm-h1.js.map → app-config-DAwcDA3h.js.map} +1 -1
- package/dist/{attachment-sync-CmPm-h69.js → attachment-sync-CD-v_qpd.js} +2 -2
- package/dist/{attachment-sync-CmPm-h69.js.map → attachment-sync-CD-v_qpd.js.map} +1 -1
- package/dist/{change-watcher-DRnLiHpP.js → change-watcher-DJ24OAN9.js} +2 -2
- package/dist/{change-watcher-DRnLiHpP.js.map → change-watcher-DJ24OAN9.js.map} +1 -1
- package/dist/cli.js +17 -17
- package/dist/{export-formats-B9v-Qh_H.js → export-formats-caHQJDm0.js} +1 -16
- package/dist/{export-formats-B9v-Qh_H.js.map → export-formats-caHQJDm0.js.map} +1 -1
- package/dist/{exportStream-CFfWlvVb.js → exportStream-DxyUSZw8.js} +3 -3
- package/dist/{exportStream-CFfWlvVb.js.map → exportStream-DxyUSZw8.js.map} +1 -1
- package/dist/{imessage-db-Bv2RrH5q.js → imessage-db-kP5t2aZb.js} +23 -13
- package/dist/imessage-db-kP5t2aZb.js.map +1 -0
- package/dist/index.js +12 -25
- package/dist/index.js.map +1 -1
- package/dist/{media-intel-cache-Dj1fn3P0.js → media-intel-cache-sRx_ix5A.js} +2 -2
- package/dist/{media-intel-cache-Dj1fn3P0.js.map → media-intel-cache-sRx_ix5A.js.map} +1 -1
- package/dist/{media-intel-runtime-BVJNaDBE.js → media-intel-runtime-DTHMFjik.js} +3 -3
- package/dist/{media-intel-runtime-BVJNaDBE.js.map → media-intel-runtime-DTHMFjik.js.map} +1 -1
- package/dist/{setup-floTXYNF.js → setup-DJ3g_smJ.js} +2 -2
- package/dist/{setup-floTXYNF.js.map → setup-DJ3g_smJ.js.map} +1 -1
- package/dist/{setup-wizard-TYwuk1Kh.js → setup-wizard-D8QvveiW.js} +3 -3
- package/dist/{setup-wizard-TYwuk1Kh.js.map → setup-wizard-D8QvveiW.js.map} +1 -1
- package/dist/{shutdown-BJyTvhvf.js → shutdown-C261a5Cx.js} +2 -2
- package/dist/{shutdown-BJyTvhvf.js.map → shutdown-C261a5Cx.js.map} +1 -1
- package/dist/{tui-config-CCczaq2h.js → tui-config-DRdkPMP8.js} +3 -3
- package/dist/tui-config-DRdkPMP8.js.map +1 -0
- package/dist/tui.js +90 -36
- package/dist/tui.js.map +1 -1
- package/dist/{watchdog-BibUvEUt.js → watchdog-CGzj6pvE.js} +3 -3
- package/dist/{watchdog-BibUvEUt.js.map → watchdog-CGzj6pvE.js.map} +1 -1
- package/package.json +3 -3
- package/dist/imessage-db-Bv2RrH5q.js.map +0 -1
- package/dist/tui-config-CCczaq2h.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,21 @@
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and follows [Semantic Versioning](https://semver.org/).
|
|
5
5
|
|
|
6
|
+
## imsg-mcp [1.25.4](https://github.com/george43g/EQStack/compare/imsg-mcp-v1.25.3...imsg-mcp-v1.25.4) (2026-08-23)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
### Bug Fixes
|
|
10
|
+
|
|
11
|
+
* **imsg-mcp:** TUI export no longer drops evicted messages ([dadcc8d](https://github.com/george43g/EQStack/commit/dadcc8dff290086992118522ac1119e9b6c7ebb0))
|
|
12
|
+
|
|
13
|
+
## imsg-mcp [1.25.3](https://github.com/george43g/EQStack/compare/imsg-mcp-v1.25.2...imsg-mcp-v1.25.3) (2026-08-23)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
### Bug Fixes
|
|
17
|
+
|
|
18
|
+
* **imsg-mcp:** keep eviction gap markers anchored to their message ([8fc9ab2](https://github.com/george43g/EQStack/commit/8fc9ab2797e944402a0c6c39dcc8acacc850141a)), closes [#94](https://github.com/george43g/EQStack/issues/94) [#87](https://github.com/george43g/EQStack/issues/87)
|
|
19
|
+
* **imsg-mcp:** stop chunked vim counts from losing a digit ([ebcbaa0](https://github.com/george43g/EQStack/commit/ebcbaa05c7c2e38ba6a654d5fcbc2609c6ffa092))
|
|
20
|
+
|
|
6
21
|
## imsg-mcp [1.25.2](https://github.com/george43g/EQStack/compare/imsg-mcp-v1.25.1...imsg-mcp-v1.25.2) (2026-08-22)
|
|
7
22
|
|
|
8
23
|
|
|
@@ -2,7 +2,7 @@ import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync } from "n
|
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
-
import { c as getTranscribeCloudConfig } from "./shutdown-
|
|
5
|
+
import { c as getTranscribeCloudConfig } from "./shutdown-C261a5Cx.js";
|
|
6
6
|
const HEX6 = /^#[0-9a-fA-F]{6}$/;
|
|
7
7
|
const PROVIDER_PRESET_NAMES = [
|
|
8
8
|
"openai",
|
|
@@ -248,4 +248,4 @@ export {
|
|
|
248
248
|
writeCredentials,
|
|
249
249
|
writeTuiConfig
|
|
250
250
|
};
|
|
251
|
-
//# sourceMappingURL=app-config-
|
|
251
|
+
//# sourceMappingURL=app-config-DAwcDA3h.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-config-CK1zm-h1.js","sources":["../src/app-config.ts"],"sourcesContent":["/**\n * Canonical persistent configuration for imsg-mcp — one JSON file that carries\n * both the flat TUI keys (theme / accentColor) AND the `interpret` block that\n * configures media interpretation (Stage 2 core: chains, providers, toggles).\n *\n * Resolution order (first one found wins) — unchanged from the original\n * tui-config module so existing files keep loading:\n * 1. $XDG_CONFIG_HOME/imsg-mcp/config.json\n * 2. $HOME/.config/imsg-mcp/config.json\n * 3. $HOME/.imsg-mcp/config.json (matches the slugs.db location)\n *\n * `src/tui-config.ts` re-exports this module verbatim for back-compat.\n *\n * API keys are NEVER stored in config.json. They live in\n * `~/.imsg-mcp/credentials.json` (chmod 600, `{ \"<providerName>\": \"sk-…\" }`)\n * or the legacy `IMSG_TRANSCRIBE_*` env vars, and are merged into providers only\n * at resolution time (`resolveInterpretConfig`).\n */\n\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { z } from \"zod\";\nimport { getTranscribeCloudConfig } from \"./config.js\";\nimport type { AutoMode, InterpretChains, InterpretConfig } from \"./media-intel.js\";\nimport type { ProviderConfig, ProviderPreset } from \"./media-providers.js\";\n\n// ── Schema ────────────────────────────────────────────────────────────────\n\nconst HEX6 = /^#[0-9a-fA-F]{6}$/;\n\n/** Preset names accepted in the `interpret.providers[].preset` field. Kept as a\n * literal tuple so Zod can build an enum without a runtime import of the\n * providers module (and asserted to stay in sync with `ProviderPreset`). */\nconst PROVIDER_PRESET_NAMES = [\n \"openai\",\n \"groq\",\n \"openrouter\",\n \"cloudflare\",\n \"huggingface\",\n \"ollama\",\n] as const satisfies readonly ProviderPreset[];\n\nconst ProviderModelsSchema = z\n .object({ transcribe: z.string().optional(), vision: z.string().optional() })\n .optional();\n\n/** A provider profile as stored in config.json — NO apiKey (that lives in\n * credentials.json / env and is merged in at resolution time). */\nconst ProviderConfigSchema = z\n .object({\n name: z.string().min(1),\n preset: z.enum(PROVIDER_PRESET_NAMES).optional(),\n baseUrl: z.string().url().optional(),\n accountId: z.string().optional(),\n models: ProviderModelsSchema,\n })\n .refine((p) => Boolean(p.preset) || Boolean(p.baseUrl), {\n message: \"provider needs either a preset or a baseUrl\",\n });\n\nconst ChainsSchema = z\n .object({\n audio: z.array(z.string()).default([\"apple\", \"local\"]),\n image: z.array(z.string()).default([]),\n video: z.array(z.string()).default([]),\n })\n .default({});\n\nconst NudgeSchema = z\n .object({\n enabled: z.boolean().default(true),\n tier2SyncNow: z.boolean().default(false),\n timeoutSeconds: z.number().int().positive().default(30),\n })\n .default({});\n\nexport const InterpretConfigSchema = z.object({\n /** Auto-interpretation gate. \"free\" (default) never makes a paid call without\n * an explicit force; \"all\" runs the full chain incl. cloud; \"off\" disables. */\n auto: z.enum([\"all\", \"free\", \"off\"]).default(\"free\"),\n /** Inline cached transcripts/captions in read surfaces (get_messages, TUI). */\n inlineTranscripts: z.boolean().default(true),\n /** Confirm before an export triggers more than this many uncached cloud calls. */\n exportConfirmThreshold: z.number().int().nonnegative().default(25),\n chains: ChainsSchema,\n providers: z.array(ProviderConfigSchema).default([]),\n nudge: NudgeSchema,\n});\n\nexport const AppConfigSchema = z.object({\n /** Glyph preset. \"safe\" is the universally-renderable default. */\n theme: z.enum([\"safe\", \"powerline\"]).default(\"safe\"),\n /** 6-digit hex color used to derive the whole UI palette. */\n accentColor: z.string().regex(HEX6, \"must be a 6-digit hex like #RRGGBB\").default(\"#1982FC\"),\n /** Media-interpretation config (optional — absent on TUI-only configs). */\n interpret: InterpretConfigSchema.optional(),\n});\n\nexport type AppConfig = z.infer<typeof AppConfigSchema>;\nexport type InterpretConfigInput = z.infer<typeof InterpretConfigSchema>;\n\n/** Back-compat alias — the TUI only ever reads theme/accentColor. */\nexport const TuiConfigSchema = AppConfigSchema;\nexport type TuiConfig = AppConfig;\n\nexport const DEFAULT_TUI_CONFIG: TuiConfig = {\n theme: \"safe\",\n accentColor: \"#1982FC\",\n};\n\n/** Free-first interpret defaults used when the block is absent from config. */\nexport const DEFAULT_INTERPRET_CONFIG: InterpretConfigInput = InterpretConfigSchema.parse({});\n\n// ── Path resolution ───────────────────────────────────────────────────────\n\n/** Candidate paths we try to read from, in order. Per the XDG spec, `~/.config`\n * is the DEFAULT VALUE of `$XDG_CONFIG_HOME` — not an additional search path —\n * so when the env var is set we must not fall through to the real `~/.config`\n * (that fall-through also let a dev machine's real config leak into tests that\n * point XDG at a temp dir). */\nfunction candidatePaths(): string[] {\n const home = homedir();\n const xdgBase = process.env.XDG_CONFIG_HOME || join(home, \".config\");\n return [join(xdgBase, \"imsg-mcp\", \"config.json\"), join(home, \".imsg-mcp\", \"config.json\")];\n}\n\n/** Where the file actually lives (first existing candidate), or null. */\nexport function findTuiConfigPath(): string | null {\n for (const p of candidatePaths()) {\n if (existsSync(p)) return p;\n }\n return null;\n}\n\n/** Where to write a fresh config file. Returns the *first* candidate so\n * XDG-style wins on a clean machine. */\nexport function defaultTuiConfigPath(): string {\n return candidatePaths()[0] ?? candidatePaths()[1];\n}\n\n// ── Loader ────────────────────────────────────────────────────────────────\n\nexport interface LoadedTuiConfig {\n config: AppConfig;\n /** Path of the file we read from, or `null` if defaults were used. */\n source: string | null;\n /** Human-readable warnings (parse errors, schema errors). Empty when clean. */\n warnings: string[];\n}\n\nexport function loadTuiConfig(): LoadedTuiConfig {\n const warnings: string[] = [];\n const path = findTuiConfigPath();\n if (!path) return { config: { ...DEFAULT_TUI_CONFIG }, source: null, warnings };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(path, \"utf8\"));\n } catch (err) {\n warnings.push(\n `config: failed to read ${path} (${err instanceof Error ? err.message : String(err)}); using defaults`,\n );\n return { config: { ...DEFAULT_TUI_CONFIG }, source: path, warnings };\n }\n\n const result = AppConfigSchema.safeParse(parsed);\n if (result.success) return { config: result.data, source: path, warnings };\n\n // Full parse failed. Degrade gracefully: if the flat TUI keys alone are valid,\n // keep them (a malformed `interpret` block should not blow away the theme).\n const tuiOnly = AppConfigSchema.pick({ theme: true, accentColor: true }).safeParse(parsed);\n const issues = result.error.issues\n .map((i) => `${i.path.join(\".\") || \"<root>\"}: ${i.message}`)\n .join(\"; \");\n if (tuiOnly.success) {\n warnings.push(`config: ${path} has invalid fields (${issues}); ignoring them`);\n return { config: { ...tuiOnly.data }, source: path, warnings };\n }\n warnings.push(`config: ${path} has invalid fields (${issues}); using defaults`);\n return { config: { ...DEFAULT_TUI_CONFIG }, source: path, warnings };\n}\n\n// ── Writer (used by `imsg config edit` + `imsg setup`) ────────────────────\n\nexport function writeTuiConfig(config: AppConfig, path = defaultTuiConfigPath()): string {\n // Validate before writing so we never persist garbage.\n const validated = AppConfigSchema.parse(config);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(validated, null, 2)}\\n`);\n return path;\n}\n\n// ── Credentials (chmod 600) ───────────────────────────────────────────────\n\n/** `~/.imsg-mcp/credentials.json` — `{ \"<providerName>\": \"<apiKey>\" }`. */\nexport function credentialsPath(): string {\n return join(homedir(), \".imsg-mcp\", \"credentials.json\");\n}\n\nexport function readCredentials(): Record<string, string> {\n const path = credentialsPath();\n if (!existsSync(path)) return {};\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\"));\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(parsed)) {\n if (typeof v === \"string\") out[k] = v;\n }\n return out;\n }\n } catch {\n // Corrupt credentials file — treat as empty (never throw on read).\n }\n return {};\n}\n\n/** Write the whole credentials map, enforcing 0600 on the file (and 0700 dir). */\nexport function writeCredentials(creds: Record<string, string>): string {\n const path = credentialsPath();\n const dir = dirname(path);\n mkdirSync(dir, { recursive: true });\n try {\n chmodSync(dir, 0o700);\n } catch {\n // Best-effort — a shared dir may already exist with other perms.\n }\n writeFileSync(path, `${JSON.stringify(creds, null, 2)}\\n`, { mode: 0o600 });\n // writeFileSync's `mode` is masked by umask on CREATE and ignored when the\n // file already exists — chmod unconditionally so 0600 is guaranteed.\n chmodSync(path, 0o600);\n return path;\n}\n\n/** Set (or clear, when key is empty) one provider's credential. */\nexport function setCredential(name: string, key: string): void {\n const creds = readCredentials();\n if (key) creds[name] = key;\n else delete creds[name];\n writeCredentials(creds);\n}\n\n// ── Interpret-config resolution (config + credentials + env → service) ─────\n\n/** The env-mapped implicit provider name (legacy IMSG_TRANSCRIBE_* path). */\nexport const ENV_PROVIDER_NAME = \"env\";\n\n/** Interpret config ready for `MediaIntelService`, plus the surfacing toggles\n * that frontends (Stage 4/6/7) read. Providers carry their merged apiKey. */\nexport interface ResolvedInterpretConfig extends InterpretConfig {\n inlineTranscripts: boolean;\n exportConfirmThreshold: number;\n nudge: { enabled: boolean; tier2SyncNow: boolean; timeoutSeconds: number };\n /** Where the config was read from (null = defaults). */\n configPath: string | null;\n warnings: string[];\n}\n\n/**\n * Resolve the full interpret configuration:\n * - start from the config file's `interpret` block (or free-first defaults),\n * - merge API keys from credentials.json into each named provider,\n * - map the legacy `IMSG_TRANSCRIBE_*` env vars to an implicit `env` provider\n * (and append `provider:env` to the audio chain if it has no provider yet),\n * preserving the shipped v1.7.0 cloud-transcription fallback.\n */\nexport function resolveInterpretConfig(): ResolvedInterpretConfig {\n const loaded = loadTuiConfig();\n const warnings = [...loaded.warnings];\n const block = InterpretConfigSchema.parse(loaded.config.interpret ?? {});\n const creds = readCredentials();\n\n const providers: ProviderConfig[] = block.providers.map((p) => ({\n ...p,\n apiKey: creds[p.name],\n }));\n const chains: InterpretChains = {\n audio: [...block.chains.audio],\n image: [...block.chains.image],\n video: [...block.chains.video],\n };\n\n // Legacy env fallback → implicit provider, if not already configured by name.\n const envCloud = getTranscribeCloudConfig();\n if (envCloud && !providers.some((p) => p.name === ENV_PROVIDER_NAME)) {\n providers.push({\n name: ENV_PROVIDER_NAME,\n baseUrl: envCloud.baseUrl,\n apiKey: envCloud.apiKey,\n models: { transcribe: envCloud.model },\n });\n if (!chains.audio.some((l) => l.startsWith(\"provider:\"))) {\n chains.audio.push(`provider:${ENV_PROVIDER_NAME}`);\n }\n }\n\n const auto: AutoMode = block.auto;\n return {\n auto,\n chains,\n providers,\n inlineTranscripts: block.inlineTranscripts,\n exportConfirmThreshold: block.exportConfirmThreshold,\n nudge: block.nudge,\n configPath: loaded.source,\n warnings,\n };\n}\n\n// ── Layered resolution (CLI > env > config > defaults) — TUI theme/accent ──\n\nexport interface TuiConfigOverrides {\n /** From `imsg --theme=...` */\n cliTheme?: string;\n /** From `imsg --accent=...` */\n cliAccent?: string;\n}\n\nexport interface ResolvedTuiConfig {\n theme: TuiConfig[\"theme\"];\n accentColor: string;\n /** Where each value came from, useful for `imsg config show`. */\n origin: {\n theme: \"cli\" | \"env\" | \"config\" | \"default\";\n accentColor: \"cli\" | \"env\" | \"config\" | \"default\";\n };\n /** The on-disk file path that contributed (or `null` if no file). */\n configPath: string | null;\n /** Any warnings raised during loading (malformed file, invalid env, etc). */\n warnings: string[];\n}\n\nexport function resolveTuiConfig(overrides: TuiConfigOverrides = {}): ResolvedTuiConfig {\n const loaded = loadTuiConfig();\n const warnings = [...loaded.warnings];\n\n // Theme precedence: CLI > env > config > default\n let theme: TuiConfig[\"theme\"] = loaded.config.theme;\n let themeOrigin: ResolvedTuiConfig[\"origin\"][\"theme\"] = loaded.source ? \"config\" : \"default\";\n\n if (process.env.IMSG_TUI_THEME) {\n const t = process.env.IMSG_TUI_THEME;\n if (t === \"safe\" || t === \"powerline\") {\n theme = t;\n themeOrigin = \"env\";\n } else {\n warnings.push(`IMSG_TUI_THEME=\"${t}\" is not \"safe\" or \"powerline\"; ignoring`);\n }\n }\n if (overrides.cliTheme !== undefined) {\n if (overrides.cliTheme === \"safe\" || overrides.cliTheme === \"powerline\") {\n theme = overrides.cliTheme;\n themeOrigin = \"cli\";\n } else {\n warnings.push(`--theme=\"${overrides.cliTheme}\" is not \"safe\" or \"powerline\"; ignoring`);\n }\n }\n\n // Accent precedence: CLI > env > config > default\n let accentColor = loaded.config.accentColor;\n let accentOrigin: ResolvedTuiConfig[\"origin\"][\"accentColor\"] = loaded.source\n ? \"config\"\n : \"default\";\n\n if (process.env.IMSG_TUI_ACCENT) {\n if (HEX6.test(process.env.IMSG_TUI_ACCENT)) {\n accentColor = process.env.IMSG_TUI_ACCENT;\n accentOrigin = \"env\";\n } else {\n warnings.push(\n `IMSG_TUI_ACCENT=\"${process.env.IMSG_TUI_ACCENT}\" is not a 6-digit hex; ignoring`,\n );\n }\n }\n if (overrides.cliAccent !== undefined) {\n if (HEX6.test(overrides.cliAccent)) {\n accentColor = overrides.cliAccent;\n accentOrigin = \"cli\";\n } else {\n warnings.push(`--accent=\"${overrides.cliAccent}\" is not a 6-digit hex; ignoring`);\n }\n }\n\n return {\n theme,\n accentColor,\n origin: { theme: themeOrigin, accentColor: accentOrigin },\n configPath: loaded.source,\n warnings,\n };\n}\n"],"names":[],"mappings":";;;;;AA6BA,MAAM,OAAO;AAKb,MAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,uBAAuB,EAC1B,OAAO,EAAE,YAAY,EAAE,SAAS,SAAA,GAAY,QAAQ,EAAE,OAAA,EAAS,WAAS,CAAG,EAC3E,SAAA;AAIH,MAAM,uBAAuB,EAC1B,OAAO;AAAA,EACN,MAAM,EAAE,SAAS,IAAI,CAAC;AAAA,EACtB,QAAQ,EAAE,KAAK,qBAAqB,EAAE,SAAA;AAAA,EACtC,SAAS,EAAE,OAAA,EAAS,IAAA,EAAM,SAAA;AAAA,EAC1B,WAAW,EAAE,OAAA,EAAS,SAAA;AAAA,EACtB,QAAQ;AACV,CAAC,EACA,OAAO,CAAC,MAAM,QAAQ,EAAE,MAAM,KAAK,QAAQ,EAAE,OAAO,GAAG;AAAA,EACtD,SAAS;AACX,CAAC;AAEH,MAAM,eAAe,EAClB,OAAO;AAAA,EACN,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,OAAO,CAAC;AAAA,EACrD,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE;AAAA,EACrC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAA,CAAE;AACvC,CAAC,EACA,QAAQ,EAAE;AAEb,MAAM,cAAc,EACjB,OAAO;AAAA,EACN,SAAS,EAAE,UAAU,QAAQ,IAAI;AAAA,EACjC,cAAc,EAAE,UAAU,QAAQ,KAAK;AAAA,EACv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AAAA,EACF;AACA,MAAI,UAAU,aAAa,QAAW;AACpC,QAAI,UAAU,aAAa,UAAU,UAAU,aAAa,aAAa;AACvE,cAAQ,UAAU;AAClB,oBAAc;AAAA,IAChB,OAAO;AACL,eAAS,KAAK,YAAY,UAAU,QAAQ,0CAA0C;AAAA,IACxF;AAAA,EACF;AAGA,MAAI,cAAc,OAAO,OAAO;AAChC,MAAI,eAA2D,OAAO,SAClE,WACA;AAEJ,MAAI,QAAQ,IAAI,iBAAiB;AAC/B,QAAI,KAAK,KAAK,QAAQ,IAAI,eAAe,GAAG;AAC1C,oBAAc,QAAQ,IAAI;AAC1B,qBAAe;AAAA,IACjB,OAAO;AACL,eAAS;AAAA,QACP,oBAAoB,QAAQ,IAAI,eAAe;AAAA,MAAA;AAAA,IAEnD;AAAA,EACF;AACA,MAAI,UAAU,cAAc,QAAW;AACrC,QAAI,KAAK,KAAK,UAAU,SAAS,GAAG;AAClC,oBAAc,UAAU;AACxB,qBAAe;AAAA,IACjB,OAAO;AACL,eAAS,KAAK,aAAa,UAAU,SAAS,kCAAkC;AAAA,IAClF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,QAAQ,EAAE,OAAO,aAAa,aAAa,aAAA;AAAA,IAC3C,YAAY,OAAO;AAAA,IACnB;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"app-config-DAwcDA3h.js","sources":["../src/app-config.ts"],"sourcesContent":["/**\n * Canonical persistent configuration for imsg-mcp — one JSON file that carries\n * both the flat TUI keys (theme / accentColor) AND the `interpret` block that\n * configures media interpretation (Stage 2 core: chains, providers, toggles).\n *\n * Resolution order (first one found wins) — unchanged from the original\n * tui-config module so existing files keep loading:\n * 1. $XDG_CONFIG_HOME/imsg-mcp/config.json\n * 2. $HOME/.config/imsg-mcp/config.json\n * 3. $HOME/.imsg-mcp/config.json (matches the slugs.db location)\n *\n * `src/tui-config.ts` re-exports this module verbatim for back-compat.\n *\n * API keys are NEVER stored in config.json. They live in\n * `~/.imsg-mcp/credentials.json` (chmod 600, `{ \"<providerName>\": \"sk-…\" }`)\n * or the legacy `IMSG_TRANSCRIBE_*` env vars, and are merged into providers only\n * at resolution time (`resolveInterpretConfig`).\n */\n\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { z } from \"zod\";\nimport { getTranscribeCloudConfig } from \"./config.js\";\nimport type { AutoMode, InterpretChains, InterpretConfig } from \"./media-intel.js\";\nimport type { ProviderConfig, ProviderPreset } from \"./media-providers.js\";\n\n// ── Schema ────────────────────────────────────────────────────────────────\n\nconst HEX6 = /^#[0-9a-fA-F]{6}$/;\n\n/** Preset names accepted in the `interpret.providers[].preset` field. Kept as a\n * literal tuple so Zod can build an enum without a runtime import of the\n * providers module (and asserted to stay in sync with `ProviderPreset`). */\nconst PROVIDER_PRESET_NAMES = [\n \"openai\",\n \"groq\",\n \"openrouter\",\n \"cloudflare\",\n \"huggingface\",\n \"ollama\",\n] as const satisfies readonly ProviderPreset[];\n\nconst ProviderModelsSchema = z\n .object({ transcribe: z.string().optional(), vision: z.string().optional() })\n .optional();\n\n/** A provider profile as stored in config.json — NO apiKey (that lives in\n * credentials.json / env and is merged in at resolution time). */\nconst ProviderConfigSchema = z\n .object({\n name: z.string().min(1),\n preset: z.enum(PROVIDER_PRESET_NAMES).optional(),\n baseUrl: z.string().url().optional(),\n accountId: z.string().optional(),\n models: ProviderModelsSchema,\n })\n .refine((p) => Boolean(p.preset) || Boolean(p.baseUrl), {\n message: \"provider needs either a preset or a baseUrl\",\n });\n\nconst ChainsSchema = z\n .object({\n audio: z.array(z.string()).default([\"apple\", \"local\"]),\n image: z.array(z.string()).default([]),\n video: z.array(z.string()).default([]),\n })\n .default({});\n\nconst NudgeSchema = z\n .object({\n enabled: z.boolean().default(true),\n tier2SyncNow: z.boolean().default(false),\n timeoutSeconds: z.number().int().positive().default(30),\n })\n .default({});\n\nexport const InterpretConfigSchema = z.object({\n /** Auto-interpretation gate. \"free\" (default) never makes a paid call without\n * an explicit force; \"all\" runs the full chain incl. cloud; \"off\" disables. */\n auto: z.enum([\"all\", \"free\", \"off\"]).default(\"free\"),\n /** Inline cached transcripts/captions in read surfaces (get_messages, TUI). */\n inlineTranscripts: z.boolean().default(true),\n /** Confirm before an export triggers more than this many uncached cloud calls. */\n exportConfirmThreshold: z.number().int().nonnegative().default(25),\n chains: ChainsSchema,\n providers: z.array(ProviderConfigSchema).default([]),\n nudge: NudgeSchema,\n});\n\nexport const AppConfigSchema = z.object({\n /** Glyph preset. \"safe\" is the universally-renderable default. */\n theme: z.enum([\"safe\", \"powerline\"]).default(\"safe\"),\n /** 6-digit hex color used to derive the whole UI palette. */\n accentColor: z.string().regex(HEX6, \"must be a 6-digit hex like #RRGGBB\").default(\"#1982FC\"),\n /** Media-interpretation config (optional — absent on TUI-only configs). */\n interpret: InterpretConfigSchema.optional(),\n});\n\nexport type AppConfig = z.infer<typeof AppConfigSchema>;\nexport type InterpretConfigInput = z.infer<typeof InterpretConfigSchema>;\n\n/** Back-compat alias — the TUI only ever reads theme/accentColor. */\nexport const TuiConfigSchema = AppConfigSchema;\nexport type TuiConfig = AppConfig;\n\nexport const DEFAULT_TUI_CONFIG: TuiConfig = {\n theme: \"safe\",\n accentColor: \"#1982FC\",\n};\n\n/** Free-first interpret defaults used when the block is absent from config. */\nexport const DEFAULT_INTERPRET_CONFIG: InterpretConfigInput = InterpretConfigSchema.parse({});\n\n// ── Path resolution ───────────────────────────────────────────────────────\n\n/** Candidate paths we try to read from, in order. Per the XDG spec, `~/.config`\n * is the DEFAULT VALUE of `$XDG_CONFIG_HOME` — not an additional search path —\n * so when the env var is set we must not fall through to the real `~/.config`\n * (that fall-through also let a dev machine's real config leak into tests that\n * point XDG at a temp dir). */\nfunction candidatePaths(): string[] {\n const home = homedir();\n const xdgBase = process.env.XDG_CONFIG_HOME || join(home, \".config\");\n return [join(xdgBase, \"imsg-mcp\", \"config.json\"), join(home, \".imsg-mcp\", \"config.json\")];\n}\n\n/** Where the file actually lives (first existing candidate), or null. */\nexport function findTuiConfigPath(): string | null {\n for (const p of candidatePaths()) {\n if (existsSync(p)) return p;\n }\n return null;\n}\n\n/** Where to write a fresh config file. Returns the *first* candidate so\n * XDG-style wins on a clean machine. */\nexport function defaultTuiConfigPath(): string {\n return candidatePaths()[0] ?? candidatePaths()[1];\n}\n\n// ── Loader ────────────────────────────────────────────────────────────────\n\nexport interface LoadedTuiConfig {\n config: AppConfig;\n /** Path of the file we read from, or `null` if defaults were used. */\n source: string | null;\n /** Human-readable warnings (parse errors, schema errors). Empty when clean. */\n warnings: string[];\n}\n\nexport function loadTuiConfig(): LoadedTuiConfig {\n const warnings: string[] = [];\n const path = findTuiConfigPath();\n if (!path) return { config: { ...DEFAULT_TUI_CONFIG }, source: null, warnings };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(path, \"utf8\"));\n } catch (err) {\n warnings.push(\n `config: failed to read ${path} (${err instanceof Error ? err.message : String(err)}); using defaults`,\n );\n return { config: { ...DEFAULT_TUI_CONFIG }, source: path, warnings };\n }\n\n const result = AppConfigSchema.safeParse(parsed);\n if (result.success) return { config: result.data, source: path, warnings };\n\n // Full parse failed. Degrade gracefully: if the flat TUI keys alone are valid,\n // keep them (a malformed `interpret` block should not blow away the theme).\n const tuiOnly = AppConfigSchema.pick({ theme: true, accentColor: true }).safeParse(parsed);\n const issues = result.error.issues\n .map((i) => `${i.path.join(\".\") || \"<root>\"}: ${i.message}`)\n .join(\"; \");\n if (tuiOnly.success) {\n warnings.push(`config: ${path} has invalid fields (${issues}); ignoring them`);\n return { config: { ...tuiOnly.data }, source: path, warnings };\n }\n warnings.push(`config: ${path} has invalid fields (${issues}); using defaults`);\n return { config: { ...DEFAULT_TUI_CONFIG }, source: path, warnings };\n}\n\n// ── Writer (used by `imsg config edit` + `imsg setup`) ────────────────────\n\nexport function writeTuiConfig(config: AppConfig, path = defaultTuiConfigPath()): string {\n // Validate before writing so we never persist garbage.\n const validated = AppConfigSchema.parse(config);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(validated, null, 2)}\\n`);\n return path;\n}\n\n// ── Credentials (chmod 600) ───────────────────────────────────────────────\n\n/** `~/.imsg-mcp/credentials.json` — `{ \"<providerName>\": \"<apiKey>\" }`. */\nexport function credentialsPath(): string {\n return join(homedir(), \".imsg-mcp\", \"credentials.json\");\n}\n\nexport function readCredentials(): Record<string, string> {\n const path = credentialsPath();\n if (!existsSync(path)) return {};\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\"));\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(parsed)) {\n if (typeof v === \"string\") out[k] = v;\n }\n return out;\n }\n } catch {\n // Corrupt credentials file — treat as empty (never throw on read).\n }\n return {};\n}\n\n/** Write the whole credentials map, enforcing 0600 on the file (and 0700 dir). */\nexport function writeCredentials(creds: Record<string, string>): string {\n const path = credentialsPath();\n const dir = dirname(path);\n mkdirSync(dir, { recursive: true });\n try {\n chmodSync(dir, 0o700);\n } catch {\n // Best-effort — a shared dir may already exist with other perms.\n }\n writeFileSync(path, `${JSON.stringify(creds, null, 2)}\\n`, { mode: 0o600 });\n // writeFileSync's `mode` is masked by umask on CREATE and ignored when the\n // file already exists — chmod unconditionally so 0600 is guaranteed.\n chmodSync(path, 0o600);\n return path;\n}\n\n/** Set (or clear, when key is empty) one provider's credential. */\nexport function setCredential(name: string, key: string): void {\n const creds = readCredentials();\n if (key) creds[name] = key;\n else delete creds[name];\n writeCredentials(creds);\n}\n\n// ── Interpret-config resolution (config + credentials + env → service) ─────\n\n/** The env-mapped implicit provider name (legacy IMSG_TRANSCRIBE_* path). */\nexport const ENV_PROVIDER_NAME = \"env\";\n\n/** Interpret config ready for `MediaIntelService`, plus the surfacing toggles\n * that frontends (Stage 4/6/7) read. Providers carry their merged apiKey. */\nexport interface ResolvedInterpretConfig extends InterpretConfig {\n inlineTranscripts: boolean;\n exportConfirmThreshold: number;\n nudge: { enabled: boolean; tier2SyncNow: boolean; timeoutSeconds: number };\n /** Where the config was read from (null = defaults). */\n configPath: string | null;\n warnings: string[];\n}\n\n/**\n * Resolve the full interpret configuration:\n * - start from the config file's `interpret` block (or free-first defaults),\n * - merge API keys from credentials.json into each named provider,\n * - map the legacy `IMSG_TRANSCRIBE_*` env vars to an implicit `env` provider\n * (and append `provider:env` to the audio chain if it has no provider yet),\n * preserving the shipped v1.7.0 cloud-transcription fallback.\n */\nexport function resolveInterpretConfig(): ResolvedInterpretConfig {\n const loaded = loadTuiConfig();\n const warnings = [...loaded.warnings];\n const block = InterpretConfigSchema.parse(loaded.config.interpret ?? {});\n const creds = readCredentials();\n\n const providers: ProviderConfig[] = block.providers.map((p) => ({\n ...p,\n apiKey: creds[p.name],\n }));\n const chains: InterpretChains = {\n audio: [...block.chains.audio],\n image: [...block.chains.image],\n video: [...block.chains.video],\n };\n\n // Legacy env fallback → implicit provider, if not already configured by name.\n const envCloud = getTranscribeCloudConfig();\n if (envCloud && !providers.some((p) => p.name === ENV_PROVIDER_NAME)) {\n providers.push({\n name: ENV_PROVIDER_NAME,\n baseUrl: envCloud.baseUrl,\n apiKey: envCloud.apiKey,\n models: { transcribe: envCloud.model },\n });\n if (!chains.audio.some((l) => l.startsWith(\"provider:\"))) {\n chains.audio.push(`provider:${ENV_PROVIDER_NAME}`);\n }\n }\n\n const auto: AutoMode = block.auto;\n return {\n auto,\n chains,\n providers,\n inlineTranscripts: block.inlineTranscripts,\n exportConfirmThreshold: block.exportConfirmThreshold,\n nudge: block.nudge,\n configPath: loaded.source,\n warnings,\n };\n}\n\n// ── Layered resolution (CLI > env > config > defaults) — TUI theme/accent ──\n\nexport interface TuiConfigOverrides {\n /** From `imsg --theme=...` */\n cliTheme?: string;\n /** From `imsg --accent=...` */\n cliAccent?: string;\n}\n\nexport interface ResolvedTuiConfig {\n theme: TuiConfig[\"theme\"];\n accentColor: string;\n /** Where each value came from, useful for `imsg config show`. */\n origin: {\n theme: \"cli\" | \"env\" | \"config\" | \"default\";\n accentColor: \"cli\" | \"env\" | \"config\" | \"default\";\n };\n /** The on-disk file path that contributed (or `null` if no file). */\n configPath: string | null;\n /** Any warnings raised during loading (malformed file, invalid env, etc). */\n warnings: string[];\n}\n\nexport function resolveTuiConfig(overrides: TuiConfigOverrides = {}): ResolvedTuiConfig {\n const loaded = loadTuiConfig();\n const warnings = [...loaded.warnings];\n\n // Theme precedence: CLI > env > config > default\n let theme: TuiConfig[\"theme\"] = loaded.config.theme;\n let themeOrigin: ResolvedTuiConfig[\"origin\"][\"theme\"] = loaded.source ? \"config\" : \"default\";\n\n if (process.env.IMSG_TUI_THEME) {\n const t = process.env.IMSG_TUI_THEME;\n if (t === \"safe\" || t === \"powerline\") {\n theme = t;\n themeOrigin = \"env\";\n } else {\n warnings.push(`IMSG_TUI_THEME=\"${t}\" is not \"safe\" or \"powerline\"; ignoring`);\n }\n }\n if (overrides.cliTheme !== undefined) {\n if (overrides.cliTheme === \"safe\" || overrides.cliTheme === \"powerline\") {\n theme = overrides.cliTheme;\n themeOrigin = \"cli\";\n } else {\n warnings.push(`--theme=\"${overrides.cliTheme}\" is not \"safe\" or \"powerline\"; ignoring`);\n }\n }\n\n // Accent precedence: CLI > env > config > default\n let accentColor = loaded.config.accentColor;\n let accentOrigin: ResolvedTuiConfig[\"origin\"][\"accentColor\"] = loaded.source\n ? \"config\"\n : \"default\";\n\n if (process.env.IMSG_TUI_ACCENT) {\n if (HEX6.test(process.env.IMSG_TUI_ACCENT)) {\n accentColor = process.env.IMSG_TUI_ACCENT;\n accentOrigin = \"env\";\n } else {\n warnings.push(\n `IMSG_TUI_ACCENT=\"${process.env.IMSG_TUI_ACCENT}\" is not a 6-digit hex; ignoring`,\n );\n }\n }\n if (overrides.cliAccent !== undefined) {\n if (HEX6.test(overrides.cliAccent)) {\n accentColor = overrides.cliAccent;\n accentOrigin = \"cli\";\n } else {\n warnings.push(`--accent=\"${overrides.cliAccent}\" is not a 6-digit hex; ignoring`);\n }\n }\n\n return {\n theme,\n accentColor,\n origin: { theme: themeOrigin, accentColor: accentOrigin },\n configPath: loaded.source,\n warnings,\n };\n}\n"],"names":[],"mappings":";;;;;AA6BA,MAAM,OAAO;AAKb,MAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,uBAAuB,EAC1B,OAAO,EAAE,YAAY,EAAE,SAAS,SAAA,GAAY,QAAQ,EAAE,OAAA,EAAS,WAAS,CAAG,EAC3E,SAAA;AAIH,MAAM,uBAAuB,EAC1B,OAAO;AAAA,EACN,MAAM,EAAE,SAAS,IAAI,CAAC;AAAA,EACtB,QAAQ,EAAE,KAAK,qBAAqB,EAAE,SAAA;AAAA,EACtC,SAAS,EAAE,OAAA,EAAS,IAAA,EAAM,SAAA;AAAA,EAC1B,WAAW,EAAE,OAAA,EAAS,SAAA;AAAA,EACtB,QAAQ;AACV,CAAC,EACA,OAAO,CAAC,MAAM,QAAQ,EAAE,MAAM,KAAK,QAAQ,EAAE,OAAO,GAAG;AAAA,EACtD,SAAS;AACX,CAAC;AAEH,MAAM,eAAe,EAClB,OAAO;AAAA,EACN,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,OAAO,CAAC;AAAA,EACrD,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE;AAAA,EACrC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAA,CAAE;AACvC,CAAC,EACA,QAAQ,EAAE;AAEb,MAAM,cAAc,EACjB,OAAO;AAAA,EACN,SAAS,EAAE,UAAU,QAAQ,IAAI;AAAA,EACjC,cAAc,EAAE,UAAU,QAAQ,KAAK;AAAA,EACvC,gBAAgB,EAAE,OAAA,EAAS,MAAM,SAAA,EAAW,QA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I,UAAU,aAAa,UAAU,UAAU,aAAa,aAAa;AACvE,cAAQ,UAAU;AAClB,oBAAc;AAAA,IAChB,OAAO;AACL,eAAS,KAAK,YAAY,UAAU,QAAQ,0CAA0C;AAAA,IACxF;AAAA,EACF;AAGA,MAAI,cAAc,OAAO,OAAO;AAChC,MAAI,eAA2D,OAAO,SAClE,WACA;AAEJ,MAAI,QAAQ,IAAI,iBAAiB;AAC/B,QAAI,KAAK,KAAK,QAAQ,IAAI,eAAe,GAAG;AAC1C,oBAAc,QAAQ,IAAI;AAC1B,qBAAe;AAAA,IACjB,OAAO;AACL,eAAS;AAAA,QACP,oBAAoB,QAAQ,IAAI,eAAe;AAAA,MAAA;AAAA,IAEnD;AAAA,EACF;AACA,MAAI,UAAU,cAAc,QAAW;AACrC,QAAI,KAAK,KAAK,UAAU,SAAS,GAAG;AAClC,oBAAc,UAAU;AACxB,qBAAe;AAAA,IACjB,OAAO;AACL,eAAS,KAAK,aAAa,UAAU,SAAS,kCAAkC;AAAA,IAClF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,QAAQ,EAAE,OAAO,aAAa,aAAa,aAAA;AAAA,IAC3C,YAAY,OAAO;AAAA,IACnB;AAAA,EAAA;AAEJ;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
|
-
import { s as syncNowViaSystemEvents, o as openConversationInMessages } from "./shutdown-
|
|
2
|
+
import { s as syncNowViaSystemEvents, o as openConversationInMessages } from "./shutdown-C261a5Cx.js";
|
|
3
3
|
function defaultAttachmentSyncDeps() {
|
|
4
4
|
return {
|
|
5
5
|
fileExists: (p) => existsSync(p),
|
|
@@ -76,4 +76,4 @@ export {
|
|
|
76
76
|
defaultAttachmentSyncDeps,
|
|
77
77
|
ensureAttachmentDownloaded
|
|
78
78
|
};
|
|
79
|
-
//# sourceMappingURL=attachment-sync-
|
|
79
|
+
//# sourceMappingURL=attachment-sync-CD-v_qpd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachment-sync-
|
|
1
|
+
{"version":3,"file":"attachment-sync-CD-v_qpd.js","sources":["../src/attachment-sync.ts"],"sourcesContent":["/**\n * Attachment sync nudge (Stage 7) — best-effort, tiered coaxing of Messages.app\n * into downloading an attachment whose bytes aren't on disk yet\n * (`transfer_state === -1`, purged/never-downloaded). iCloud syncs Messages\n * media only while a conversation is OPEN, and there is no public download API\n * (IMTransferAgent is a private SIP'd daemon). So we:\n *\n * Tier 1 (default): open the conversation in Messages via an `imessage:` URL\n * — community-verified to make the app pull that thread's media — then poll\n * `existsSync` until the file appears or a timeout elapses.\n * Tier 2 (opt-in, `nudge.tier2SyncNow`): UI-script Messages ▸ Settings ▸\n * iMessage ▸ \"Sync Now\". Needs Accessibility permission; we detect the\n * missing-permission error and return an actionable hint.\n * Tier 3: per-conversation \"download all\" UI script — documented only\n * (too fragile across macOS versions), no code here.\n *\n * This module is PURE ORCHESTRATION: every side effect (AppleScript, fs, timers)\n * is injected via {@link AttachmentSyncDeps}, so the tier/poll/timeout logic is\n * unit-tested deterministically with no real app launch and no real clock. The\n * default deps wire the real AppleScript primitives (themselves mocked under\n * Vitest) + node fs/timers.\n */\nimport { existsSync } from \"node:fs\";\nimport {\n openConversationInMessages,\n type SyncNowOutcome,\n syncNowViaSystemEvents,\n} from \"./applescript.js\";\n\nexport type { SyncNowOutcome };\n\n/** The subset of the resolved `nudge` config this module needs. */\nexport interface AttachmentSyncConfig {\n /** Master switch — when false, no tier runs and we never touch Messages. */\n enabled: boolean;\n /** Enable Tier 2 (System Events \"Sync Now\"). Default off. */\n tier2SyncNow: boolean;\n /** How long to wait for the file to appear after a nudge, in seconds. */\n timeoutSeconds: number;\n /** Poll cadence while waiting. Default 1000ms; floored at 100ms. */\n pollIntervalMs?: number;\n}\n\n/** Highest tier that actually ran (0 = none). */\nexport type SyncTier = 0 | 1 | 2;\n\nexport interface EnsureDownloadedInput {\n /** Absolute path (already `~`-expanded) we expect the file to appear at. */\n filePath: string;\n /** Chat identifier (handle or GUID) to open in Messages for Tier 1. */\n chatId?: string | null;\n /** `attachment.transfer_state` from chat.db (-1 = undownloaded); advisory. */\n transferState?: number | null;\n}\n\nexport interface EnsureDownloadedResult {\n /** True iff the file is on disk when we return. */\n downloaded: boolean;\n /** True iff we actually ran at least one tier (vs short-circuited). */\n attempted: boolean;\n /** Highest tier attempted. */\n tier: SyncTier;\n /** Machine-readable reason when not downloaded / skipped. */\n reason?: string;\n /** Human-actionable remediation (e.g. grant Accessibility). */\n hint?: string;\n}\n\n/** All side effects the orchestrator needs, injectable for tests. */\nexport interface AttachmentSyncDeps {\n fileExists(path: string): boolean;\n openConversation(chatId: string): Promise<void>;\n syncNow(): Promise<SyncNowOutcome>;\n sleep(ms: number): Promise<void>;\n now(): number;\n}\n\n/** Production deps: real fs + timers + AppleScript (AppleScript self-mocks under Vitest). */\nexport function defaultAttachmentSyncDeps(): AttachmentSyncDeps {\n return {\n fileExists: (p) => existsSync(p),\n openConversation: (chatId) => openConversationInMessages(chatId),\n syncNow: () => syncNowViaSystemEvents(),\n sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n now: () => Date.now(),\n };\n}\n\nfunction errMsg(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * Poll `fileExists` until it's true or `timeoutMs` elapses (measured against\n * `deps.now()`). Checks immediately first — opening the chat may have already\n * pulled the file — then sleeps `pollIntervalMs` between checks.\n */\nasync function pollForFile(\n deps: AttachmentSyncDeps,\n path: string,\n timeoutMs: number,\n pollIntervalMs: number,\n): Promise<boolean> {\n const start = deps.now();\n if (deps.fileExists(path)) return true;\n while (deps.now() - start < timeoutMs) {\n await deps.sleep(pollIntervalMs);\n if (deps.fileExists(path)) return true;\n }\n return false;\n}\n\n/**\n * Ensure `input.filePath` is on disk, nudging Messages to download it if not.\n * Best-effort: returns a structured result rather than throwing. Idempotent and\n * cheap when the file already exists (no side effects) or when disabled.\n */\nexport async function ensureAttachmentDownloaded(\n input: EnsureDownloadedInput,\n config: AttachmentSyncConfig,\n deps: AttachmentSyncDeps = defaultAttachmentSyncDeps(),\n): Promise<EnsureDownloadedResult> {\n const { filePath } = input;\n\n // Already on disk → nothing to do (no app launch).\n if (deps.fileExists(filePath)) {\n return { downloaded: true, attempted: false, tier: 0 };\n }\n if (!config.enabled) {\n return { downloaded: false, attempted: false, tier: 0, reason: \"sync nudge disabled\" };\n }\n\n const pollIntervalMs = Math.max(100, config.pollIntervalMs ?? 1000);\n const timeoutMs = Math.max(1000, config.timeoutSeconds * 1000);\n let tier: SyncTier = 0;\n let hint: string | undefined;\n\n // ── Tier 1: open the conversation so Messages pulls its media ──\n if (input.chatId) {\n tier = 1;\n try {\n await deps.openConversation(input.chatId);\n } catch (e) {\n hint = `Could not open the conversation in Messages: ${errMsg(e)}`;\n }\n if (await pollForFile(deps, filePath, timeoutMs, pollIntervalMs)) {\n return { downloaded: true, attempted: true, tier };\n }\n } else {\n hint = \"No chat identifier available to open the conversation in Messages.\";\n }\n\n // ── Tier 2 (opt-in): System Events \"Sync Now\" ──\n if (config.tier2SyncNow) {\n tier = 2;\n const outcome = await deps.syncNow();\n if (!outcome.ok) {\n if (outcome.needsAccessibility) {\n return {\n downloaded: deps.fileExists(filePath),\n attempted: true,\n tier,\n reason: \"accessibility-permission-required\",\n hint: \"Sync Now needs Accessibility permission. Grant it in System Settings ▸ Privacy & Security ▸ Accessibility for your terminal/IDE, then retry.\",\n };\n }\n hint = outcome.error ?? hint ?? \"Sync Now failed.\";\n } else if (await pollForFile(deps, filePath, timeoutMs, pollIntervalMs)) {\n return { downloaded: true, attempted: true, tier };\n }\n }\n\n return {\n downloaded: deps.fileExists(filePath),\n attempted: tier > 0,\n tier,\n reason: tier === 0 ? \"no sync tier could run\" : \"attachment did not download in time\",\n hint,\n };\n}\n"],"names":[],"mappings":";;AA8EO,SAAS,4BAAgD;AAC9D,SAAO;AAAA,IACL,YAAY,CAAC,MAA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AM,WAAW,MAAM,KAAA;AAAA,IAC9C;AAAA,EACF,OAAO;AACL,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,cAAc;AACvB,WAAO;AACP,UAAM,UAAU,MAAM,KAAK,QAAA;AAC3B,QAAI,CAAC,QAAQ,IAAI;AACf,UAAI,QAAQ,oBAAoB;AAC9B,eAAO;AAAA,UACL,YAAY,KAAK,WAAW,QAAQ;AAAA,UACpC,WAAW;AAAA,UACX;AAAA,UACA,QAAQ;AAAA,UACR,MAAM;AAAA,QAAA;AAAA,MAEV;AACA,aAAO,QAAQ,SAAS,QAAQ;AAAA,IAClC,WAAW,MAAM,YAAY,MAAM,UAAU,WAAW,cAAc,GAAG;AACvE,aAAO,EAAE,YAAY,MAAM,WAAW,MAAM,KAAA;AAAA,IAC9C;AAAA,EACF;AAEA,SAAO;AAAA,IACL,YAAY,KAAK,WAAW,QAAQ;AAAA,IACpC,WAAW,OAAO;AAAA,IAClB;AAAA,IACA,QAAQ,SAAS,IAAI,2BAA2B;AAAA,IAChD;AAAA,EAAA;AAEJ;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { watch } from "node:fs";
|
|
2
2
|
import { dirname, basename } from "node:path";
|
|
3
|
-
import { w as warn, i as info } from "./shutdown-
|
|
3
|
+
import { w as warn, i as info } from "./shutdown-C261a5Cx.js";
|
|
4
4
|
class ChangeWatcher {
|
|
5
5
|
dbPath;
|
|
6
6
|
db;
|
|
@@ -200,4 +200,4 @@ function classify(message) {
|
|
|
200
200
|
export {
|
|
201
201
|
ChangeWatcher
|
|
202
202
|
};
|
|
203
|
-
//# sourceMappingURL=change-watcher-
|
|
203
|
+
//# sourceMappingURL=change-watcher-DJ24OAN9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"change-watcher-DRnLiHpP.js","sources":["../src/change-watcher.ts"],"sourcesContent":["/**\n * ChangeWatcher — turns chat.db writes into typed EventBus batches.\n *\n * Detection uses THREE layered primitives (the original design's single\n * directory watch was blind in production — see below):\n *\n * 1. A file watch on `chat.db-wal` ITSELF — kqueue on an opened fd, which\n * delivers write/extend events regardless of which process writes.\n * 2. A directory watch on dirname(dbPath) — re-arms the file watch when a\n * checkpoint truncates/recreates the wal (stale inode), and is the\n * drain signal on platforms where it does report file events.\n * 3. A slow safety poll (default 10s; one MAX(ROWID) query per tick) that\n * always runs alongside the watches.\n *\n * Why not the original directory watch alone: on the REAL\n * `~/Library/Messages` it armed cleanly and then delivered NOTHING while\n * rows landed in chat.db (observed live, 2026-08-10; suspected TCC/FSEvents\n * filtering on the protected directory — plain temp dirs DO report appends,\n * which is why the integration tests couldn't catch it). The file watch and\n * the safety poll are the primitives that don't depend on that delivery.\n *\n * If fs.watch throws outright (exotic filesystems), degrade to the\n * documented fast-poll fallback of the same drain path (default 2s).\n * The authoritative cursor is always a high-water ROWID, never file state.\n *\n * On a signal: debounce ~150ms (one logical message = several WAL writes),\n * then delta-read rows past the high-water mark via\n * `IMessageDB.getMessagesAfterRowid` — the same parse/convert pipeline as\n * every other reader (\"one parser, N callers\"; no forked streamer parser) —\n * classify, and emit ONE coalesced batch per drain. Bulk syncs loop the\n * delta read in `maxBatch` pages so thousands of rows become a few batches,\n * not a subscriber storm.\n *\n * The watcher never throws into the host process: drain errors are logged\n * and retried on the next event. Timers are unref'd; `stop()` is idempotent\n * and safe to register as a shutdown cleanup (the ENTRY POINT registers it —\n * this module stays side-effect-free at import, like the rest of core).\n */\n\nimport { watch } from \"node:fs\";\nimport { basename, dirname } from \"node:path\";\nimport type { ChangeEvent, EventBus } from \"./event-bus.js\";\nimport { info, warn } from \"./logger.js\";\nimport type { Message } from \"./types.js\";\n\n/** The DB surface the watcher needs — injectable for tests. */\nexport interface ChangeWatcherDb {\n getMaxMessageRowId(): number;\n getMessagesAfterRowid(afterRowid: number, limit?: number): Promise<Message[]>;\n}\n\nexport interface ChangeWatcherOptions {\n /** Path to chat.db — the watcher watches its parent directory. */\n dbPath: string;\n db: ChangeWatcherDb;\n bus: EventBus;\n /** Trailing-edge debounce between an fs event and the delta read. */\n debounceMs?: number;\n /** Poll cadence for the degenerate no-fs.watch fallback. */\n pollFallbackMs?: number;\n /** Slow backstop poll cadence while fs.watch is armed (0 disables). */\n safetyPollMs?: number;\n /** Rows per delta page; drains loop while a page comes back full. */\n maxBatch?: number;\n}\n\nexport class ChangeWatcher {\n private readonly dbPath: string;\n private readonly db: ChangeWatcherDb;\n private readonly bus: EventBus;\n private readonly debounceMs: number;\n private readonly pollFallbackMs: number;\n private readonly maxBatch: number;\n\n private readonly safetyPollMs: number;\n\n private watcher: ReturnType<typeof watch> | null = null;\n private walWatcher: ReturnType<typeof watch> | null = null;\n private pollTimer: ReturnType<typeof setInterval> | null = null;\n private safetyTimer: ReturnType<typeof setInterval> | null = null;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private highWaterRowid = 0;\n private draining = false;\n private rearm = false;\n private started = false;\n private usingPollFallback = false;\n\n constructor(opts: ChangeWatcherOptions) {\n this.dbPath = opts.dbPath;\n this.db = opts.db;\n this.bus = opts.bus;\n this.debounceMs = opts.debounceMs ?? 150;\n this.pollFallbackMs = opts.pollFallbackMs ?? 2_000;\n this.safetyPollMs = opts.safetyPollMs ?? 10_000;\n this.maxBatch = opts.maxBatch ?? 500;\n }\n\n /**\n * Seed the high-water mark from the CURRENT max ROWID (history is the\n * initial-load path's job; the stream carries only what happens next) and\n * arm the directory watch — or the poll fallback if fs.watch throws.\n */\n start(): void {\n if (this.started) return;\n this.started = true;\n this.highWaterRowid = this.db.getMaxMessageRowId();\n\n const dir = dirname(this.dbPath);\n const dbFile = basename(this.dbPath);\n try {\n this.watcher = watch(dir, (eventType, filename) => {\n // Directory watches only report ENTRY changes (create/rename/delete)\n // on macOS — a checkpoint truncating/recreating the wal lands here.\n // Any wal entry event means the file watch's inode may be stale:\n // re-arm it, then drain. filename can be null on some platforms —\n // treat that as a hit.\n if (filename === null || filename === `${dbFile}-wal` || filename === dbFile) {\n if (eventType === \"rename\" || this.walWatcher === null) this.armWalWatch();\n this.scheduleDrain();\n }\n });\n // Like the timers, the fs.watch handle must never keep the process\n // alive on its own — entry points arm the watcher lazily inside\n // request handlers, and shutdown() already stops it explicitly.\n this.watcher.unref();\n this.watcher.on(\"error\", (err) => {\n warn(\"change_watcher_fs_error_falling_back_to_poll\", { message: String(err) });\n this.teardownWatch();\n this.armPollFallback();\n });\n this.armWalWatch();\n this.armSafetyPoll();\n info(\"change_watcher_started\", {\n dir,\n high_water_rowid: this.highWaterRowid,\n debounce_ms: this.debounceMs,\n wal_file_watch: this.walWatcher !== null,\n safety_poll_ms: this.safetyPollMs,\n });\n } catch (err) {\n warn(\"change_watcher_fs_watch_unavailable\", { message: String(err) });\n this.armPollFallback();\n }\n }\n\n /**\n * Watch the WAL file itself — the only fs.watch mode that fires on APPENDS\n * on macOS (kqueue on the file). Best-effort: the wal may not exist yet\n * (fresh db, post-checkpoint gap); the directory watch re-arms us when its\n * entry appears, and the safety poll covers the meantime.\n */\n private armWalWatch(): void {\n if (!this.started) return;\n if (this.walWatcher) {\n this.walWatcher.close();\n this.walWatcher = null;\n }\n try {\n this.walWatcher = watch(`${this.dbPath}-wal`, () => {\n this.scheduleDrain();\n });\n this.walWatcher.unref();\n this.walWatcher.on(\"error\", () => {\n // Stale inode (checkpoint) or vanished file — the dir watch will\n // re-arm on the next wal entry event; don't fall back to full poll.\n if (this.walWatcher) {\n this.walWatcher.close();\n this.walWatcher = null;\n }\n });\n } catch {\n // ENOENT etc. — covered by dir watch + safety poll.\n this.walWatcher = null;\n }\n }\n\n /** Slow backstop drain while fs.watch is armed — catches silent watches. */\n private armSafetyPoll(): void {\n if (this.safetyTimer || this.safetyPollMs <= 0) return;\n this.safetyTimer = setInterval(() => {\n void this.drain();\n }, this.safetyPollMs);\n this.safetyTimer.unref();\n }\n\n /** Idempotent teardown — clears the watches, timers, and pending drains. */\n stop(): void {\n this.started = false;\n this.teardownWatch();\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n if (this.safetyTimer) {\n clearInterval(this.safetyTimer);\n this.safetyTimer = null;\n }\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n }\n\n /** Current cursor — exposed for the dev-stats panel and tests. */\n getHighWaterRowid(): number {\n return this.highWaterRowid;\n }\n\n /** True when running in the degenerate poll mode (fs.watch unavailable). */\n isPolling(): boolean {\n return this.usingPollFallback;\n }\n\n /**\n * Trigger a delta read now, bypassing the debounce. The poll fallback and\n * tests use this; the fs.watch path goes through `scheduleDrain`.\n */\n async pump(): Promise<void> {\n await this.drain();\n }\n\n private teardownWatch(): void {\n if (this.watcher) {\n this.watcher.close();\n this.watcher = null;\n }\n if (this.walWatcher) {\n this.walWatcher.close();\n this.walWatcher = null;\n }\n }\n\n private armPollFallback(): void {\n if (this.pollTimer || !this.started) return;\n this.usingPollFallback = true;\n this.pollTimer = setInterval(() => {\n void this.drain();\n }, this.pollFallbackMs);\n this.pollTimer.unref();\n info(\"change_watcher_poll_fallback_armed\", { interval_ms: this.pollFallbackMs });\n }\n\n private scheduleDrain(): void {\n if (!this.started) return;\n if (this.debounceTimer) clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null;\n void this.drain();\n }, this.debounceMs);\n this.debounceTimer.unref();\n }\n\n /**\n * Read rows past the high-water mark and emit them as one batch per page.\n * Re-entrancy guard: fs events landing mid-drain set `rearm` so the drain\n * runs once more instead of overlapping (overlapping reads would emit\n * duplicate rows — both would read from the same stale cursor).\n */\n private async drain(): Promise<void> {\n if (this.draining) {\n this.rearm = true;\n return;\n }\n this.draining = true;\n try {\n // Loop while pages come back full — a bulk sync writes thousands of\n // rows in one burst and each page becomes one coalesced batch.\n for (;;) {\n const messages = await this.db.getMessagesAfterRowid(this.highWaterRowid, this.maxBatch);\n if (messages.length === 0) break;\n for (const m of messages) {\n if (m.id > this.highWaterRowid) this.highWaterRowid = m.id;\n }\n this.bus.emit(messages.map(classify));\n if (messages.length < this.maxBatch) break;\n }\n } catch (err) {\n // Never throw into the host — the next WAL event retries naturally.\n warn(\"change_watcher_drain_failed\", { message: String(err) });\n } finally {\n this.draining = false;\n if (this.rearm) {\n this.rearm = false;\n void this.drain();\n }\n }\n }\n}\n\n/**\n * New-ROWID classification. Edited/unsent rows mutate EXISTING ROWIDs and are\n * invisible to the high-water delta — they belong to the mutation-detection\n * backlog item (date_edited / is_read deltas), not this path.\n */\nfunction classify(message: Message): ChangeEvent {\n return message.isReaction ? { type: \"reaction\", message } : { type: \"message.new\", message };\n}\n"],"names":[],"mappings":";;;AAkEO,MAAM,cAAc;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EAET,UAA2C;AAAA,EAC3C,aAA8C;AAAA,EAC9C,YAAmD;AAAA,EACnD,cAAqD;AAAA,EACrD,gBAAsD;AAAA,EACtD,iBAAiB;AAAA,EACjB,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,oBAAoB;AAAA,EAE5B,YAAY,MAA4B;AACtC,SAAK,SAAS,KAAK;AACnB,SAAK,KAAK,KAAK;AACf,SAAK,MAAM,KAAK;AAChB,SAAK,aAAa,KAAK,cAAc;AACrC,SAAK,iBAAiB,KAAK,kBAAkB;AAC7C,SAAK,eAAe,KAAK,gBAAgB;AACzC,SAAK,WAAW,KAAK,YAAY;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,QAAc;AACZ,QAAI,KAAK,QAAS;AAClB,SAAK,UAAU;AACf,SAAK,iBAAiB,KAAK,GAAG,mBAAA;AAE9B,UAAM,MAAM,QAAQ,KAAK,MAAM;AAC/B,UAAM,SAAS,SAAS,KAAK,MAAM;AACnC,QAAI;AACF,WAAK,UAAU,MAAM,KAAK,CAAC,WAAW,aAAa;AAMjD,YAAI,aAAa,QAAQ,aAAa,GAAG,MAAM,UAAU,aAAa,QAA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A;AAAA;AAAA,EAQA,MAAc,QAAuB;AACnC,QAAI,KAAK,UAAU;AACjB,WAAK,QAAQ;AACb;AAAA,IACF;AACA,SAAK,WAAW;AAChB,QAAI;AAGF,iBAAS;AACP,cAAM,WAAW,MAAM,KAAK,GAAG,sBAAsB,KAAK,gBAAgB,KAAK,QAAQ;AACvF,YAAI,SAAS,WAAW,EAAG;AAC3B,mBAAW,KAAK,UAAU;AACxB,cAAI,EAAE,KAAK,KAAK,eAAgB,MAAK,iBAAiB,EAAE;AAAA,QAC1D;AACA,aAAK,IAAI,KAAK,SAAS,IAAI,QAAQ,CAAC;AACpC,YAAI,SAAS,SAAS,KAAK,SAAU;AAAA,MACvC;AAAA,IACF,SAAS,KAAK;AAEZ,WAAK,+BAA+B,EAAE,SAAS,OAAO,GAAG,GAAG;AAAA,IAC9D,UAAA;AACE,WAAK,WAAW;AAChB,UAAI,KAAK,OAAO;AACd,aAAK,QAAQ;AACb,aAAK,KAAK,MAAA;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF;AAOA,SAAS,SAAS,SAA+B;AAC/C,SAAO,QAAQ,aAAa,EAAE,MAAM,YAAY,YAAY,EAAE,MAAM,eAAe,QAAA;AACrF;"}
|
|
1
|
+
{"version":3,"file":"change-watcher-DJ24OAN9.js","sources":["../src/change-watcher.ts"],"sourcesContent":["/**\n * ChangeWatcher — turns chat.db writes into typed EventBus batches.\n *\n * Detection uses THREE layered primitives (the original design's single\n * directory watch was blind in production — see below):\n *\n * 1. A file watch on `chat.db-wal` ITSELF — kqueue on an opened fd, which\n * delivers write/extend events regardless of which process writes.\n * 2. A directory watch on dirname(dbPath) — re-arms the file watch when a\n * checkpoint truncates/recreates the wal (stale inode), and is the\n * drain signal on platforms where it does report file events.\n * 3. A slow safety poll (default 10s; one MAX(ROWID) query per tick) that\n * always runs alongside the watches.\n *\n * Why not the original directory watch alone: on the REAL\n * `~/Library/Messages` it armed cleanly and then delivered NOTHING while\n * rows landed in chat.db (observed live, 2026-08-10; suspected TCC/FSEvents\n * filtering on the protected directory — plain temp dirs DO report appends,\n * which is why the integration tests couldn't catch it). The file watch and\n * the safety poll are the primitives that don't depend on that delivery.\n *\n * If fs.watch throws outright (exotic filesystems), degrade to the\n * documented fast-poll fallback of the same drain path (default 2s).\n * The authoritative cursor is always a high-water ROWID, never file state.\n *\n * On a signal: debounce ~150ms (one logical message = several WAL writes),\n * then delta-read rows past the high-water mark via\n * `IMessageDB.getMessagesAfterRowid` — the same parse/convert pipeline as\n * every other reader (\"one parser, N callers\"; no forked streamer parser) —\n * classify, and emit ONE coalesced batch per drain. Bulk syncs loop the\n * delta read in `maxBatch` pages so thousands of rows become a few batches,\n * not a subscriber storm.\n *\n * The watcher never throws into the host process: drain errors are logged\n * and retried on the next event. Timers are unref'd; `stop()` is idempotent\n * and safe to register as a shutdown cleanup (the ENTRY POINT registers it —\n * this module stays side-effect-free at import, like the rest of core).\n */\n\nimport { watch } from \"node:fs\";\nimport { basename, dirname } from \"node:path\";\nimport type { ChangeEvent, EventBus } from \"./event-bus.js\";\nimport { info, warn } from \"./logger.js\";\nimport type { Message } from \"./types.js\";\n\n/** The DB surface the watcher needs — injectable for tests. */\nexport interface ChangeWatcherDb {\n getMaxMessageRowId(): number;\n getMessagesAfterRowid(afterRowid: number, limit?: number): Promise<Message[]>;\n}\n\nexport interface ChangeWatcherOptions {\n /** Path to chat.db — the watcher watches its parent directory. */\n dbPath: string;\n db: ChangeWatcherDb;\n bus: EventBus;\n /** Trailing-edge debounce between an fs event and the delta read. */\n debounceMs?: number;\n /** Poll cadence for the degenerate no-fs.watch fallback. */\n pollFallbackMs?: number;\n /** Slow backstop poll cadence while fs.watch is armed (0 disables). */\n safetyPollMs?: number;\n /** Rows per delta page; drains loop while a page comes back full. */\n maxBatch?: number;\n}\n\nexport class ChangeWatcher {\n private readonly dbPath: string;\n private readonly db: ChangeWatcherDb;\n private readonly bus: EventBus;\n private readonly debounceMs: number;\n private readonly pollFallbackMs: number;\n private readonly maxBatch: number;\n\n private readonly safetyPollMs: number;\n\n private watcher: ReturnType<typeof watch> | null = null;\n private walWatcher: ReturnType<typeof watch> | null = null;\n private pollTimer: ReturnType<typeof setInterval> | null = null;\n private safetyTimer: ReturnType<typeof setInterval> | null = null;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private highWaterRowid = 0;\n private draining = false;\n private rearm = false;\n private started = false;\n private usingPollFallback = false;\n\n constructor(opts: ChangeWatcherOptions) {\n this.dbPath = opts.dbPath;\n this.db = opts.db;\n this.bus = opts.bus;\n this.debounceMs = opts.debounceMs ?? 150;\n this.pollFallbackMs = opts.pollFallbackMs ?? 2_000;\n this.safetyPollMs = opts.safetyPollMs ?? 10_000;\n this.maxBatch = opts.maxBatch ?? 500;\n }\n\n /**\n * Seed the high-water mark from the CURRENT max ROWID (history is the\n * initial-load path's job; the stream carries only what happens next) and\n * arm the directory watch — or the poll fallback if fs.watch throws.\n */\n start(): void {\n if (this.started) return;\n this.started = true;\n this.highWaterRowid = this.db.getMaxMessageRowId();\n\n const dir = dirname(this.dbPath);\n const dbFile = basename(this.dbPath);\n try {\n this.watcher = watch(dir, (eventType, filename) => {\n // Directory watches only report ENTRY changes (create/rename/delete)\n // on macOS — a checkpoint truncating/recreating the wal lands here.\n // Any wal entry event means the file watch's inode may be stale:\n // re-arm it, then drain. filename can be null on some platforms —\n // treat that as a hit.\n if (filename === null || filename === `${dbFile}-wal` || filename === dbFile) {\n if (eventType === \"rename\" || this.walWatcher === null) this.armWalWatch();\n this.scheduleDrain();\n }\n });\n // Like the timers, the fs.watch handle must never keep the process\n // alive on its own — entry points arm the watcher lazily inside\n // request handlers, and shutdown() already stops it explicitly.\n this.watcher.unref();\n this.watcher.on(\"error\", (err) => {\n warn(\"change_watcher_fs_error_falling_back_to_poll\", { message: String(err) });\n this.teardownWatch();\n this.armPollFallback();\n });\n this.armWalWatch();\n this.armSafetyPoll();\n info(\"change_watcher_started\", {\n dir,\n high_water_rowid: this.highWaterRowid,\n debounce_ms: this.debounceMs,\n wal_file_watch: this.walWatcher !== null,\n safety_poll_ms: this.safetyPollMs,\n });\n } catch (err) {\n warn(\"change_watcher_fs_watch_unavailable\", { message: String(err) });\n this.armPollFallback();\n }\n }\n\n /**\n * Watch the WAL file itself — the only fs.watch mode that fires on APPENDS\n * on macOS (kqueue on the file). Best-effort: the wal may not exist yet\n * (fresh db, post-checkpoint gap); the directory watch re-arms us when its\n * entry appears, and the safety poll covers the meantime.\n */\n private armWalWatch(): void {\n if (!this.started) return;\n if (this.walWatcher) {\n this.walWatcher.close();\n this.walWatcher = null;\n }\n try {\n this.walWatcher = watch(`${this.dbPath}-wal`, () => {\n this.scheduleDrain();\n });\n this.walWatcher.unref();\n this.walWatcher.on(\"error\", () => {\n // Stale inode (checkpoint) or vanished file — the dir watch will\n // re-arm on the next wal entry event; don't fall back to full poll.\n if (this.walWatcher) {\n this.walWatcher.close();\n this.walWatcher = null;\n }\n });\n } catch {\n // ENOENT etc. — covered by dir watch + safety poll.\n this.walWatcher = null;\n }\n }\n\n /** Slow backstop drain while fs.watch is armed — catches silent watches. */\n private armSafetyPoll(): void {\n if (this.safetyTimer || this.safetyPollMs <= 0) return;\n this.safetyTimer = setInterval(() => {\n void this.drain();\n }, this.safetyPollMs);\n this.safetyTimer.unref();\n }\n\n /** Idempotent teardown — clears the watches, timers, and pending drains. */\n stop(): void {\n this.started = false;\n this.teardownWatch();\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n if (this.safetyTimer) {\n clearInterval(this.safetyTimer);\n this.safetyTimer = null;\n }\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n }\n\n /** Current cursor — exposed for the dev-stats panel and tests. */\n getHighWaterRowid(): number {\n return this.highWaterRowid;\n }\n\n /** True when running in the degenerate poll mode (fs.watch unavailable). */\n isPolling(): boolean {\n return this.usingPollFallback;\n }\n\n /**\n * Trigger a delta read now, bypassing the debounce. The poll fallback and\n * tests use this; the fs.watch path goes through `scheduleDrain`.\n */\n async pump(): Promise<void> {\n await this.drain();\n }\n\n private teardownWatch(): void {\n if (this.watcher) {\n this.watcher.close();\n this.watcher = null;\n }\n if (this.walWatcher) {\n this.walWatcher.close();\n this.walWatcher = null;\n }\n }\n\n private armPollFallback(): void {\n if (this.pollTimer || !this.started) return;\n this.usingPollFallback = true;\n this.pollTimer = setInterval(() => {\n void this.drain();\n }, this.pollFallbackMs);\n this.pollTimer.unref();\n info(\"change_watcher_poll_fallback_armed\", { interval_ms: this.pollFallbackMs });\n }\n\n private scheduleDrain(): void {\n if (!this.started) return;\n if (this.debounceTimer) clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null;\n void this.drain();\n }, this.debounceMs);\n this.debounceTimer.unref();\n }\n\n /**\n * Read rows past the high-water mark and emit them as one batch per page.\n * Re-entrancy guard: fs events landing mid-drain set `rearm` so the drain\n * runs once more instead of overlapping (overlapping reads would emit\n * duplicate rows — both would read from the same stale cursor).\n */\n private async drain(): Promise<void> {\n if (this.draining) {\n this.rearm = true;\n return;\n }\n this.draining = true;\n try {\n // Loop while pages come back full — a bulk sync writes thousands of\n // rows in one burst and each page becomes one coalesced batch.\n for (;;) {\n const messages = await this.db.getMessagesAfterRowid(this.highWaterRowid, this.maxBatch);\n if (messages.length === 0) break;\n for (const m of messages) {\n if (m.id > this.highWaterRowid) this.highWaterRowid = m.id;\n }\n this.bus.emit(messages.map(classify));\n if (messages.length < this.maxBatch) break;\n }\n } catch (err) {\n // Never throw into the host — the next WAL event retries naturally.\n warn(\"change_watcher_drain_failed\", { message: String(err) });\n } finally {\n this.draining = false;\n if (this.rearm) {\n this.rearm = false;\n void this.drain();\n }\n }\n }\n}\n\n/**\n * New-ROWID classification. Edited/unsent rows mutate EXISTING ROWIDs and are\n * invisible to the high-water delta — they belong to the mutation-detection\n * backlog item (date_edited / is_read deltas), not this path.\n */\nfunction classify(message: Message): ChangeEvent {\n return message.isReaction ? { type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D;AACA,aAAK,IAAI,KAAK,SAAS,IAAI,QAAQ,CAAC;AACpC,YAAI,SAAS,SAAS,KAAK,SAAU;AAAA,MACvC;AAAA,IACF,SAAS,KAAK;AAEZ,WAAK,+BAA+B,EAAE,SAAS,OAAO,GAAG,GAAG;AAAA,IAC9D,UAAA;AACE,WAAK,WAAW;AAChB,UAAI,KAAK,OAAO;AACd,aAAK,QAAQ;AACb,aAAK,KAAK,MAAA;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF;AAOA,SAAS,SAAS,SAA+B;AAC/C,SAAO,QAAQ,aAAa,EAAE,MAAM,YAAY,YAAY,EAAE,MAAM,eAAe,QAAA;AACrF;"}
|
package/dist/cli.js
CHANGED
|
@@ -3,7 +3,7 @@ import { existsSync, realpathSync } from "node:fs";
|
|
|
3
3
|
import { createInterface } from "node:readline";
|
|
4
4
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
5
5
|
import { Command } from "commander";
|
|
6
|
-
import { A as APP_VERSION, d as checkLocalAccess, f as formatAccessReport, l as looksLikeThreadSlug, I as IMPLEMENTED_TYPES, e as ANALYTIC_INFO, h as installShutdownHandlers, r as registerCleanup, t as toYaml } from "./shutdown-
|
|
6
|
+
import { A as APP_VERSION, d as checkLocalAccess, f as formatAccessReport, l as looksLikeThreadSlug, I as IMPLEMENTED_TYPES, e as ANALYTIC_INFO, h as installShutdownHandlers, r as registerCleanup, t as toYaml } from "./shutdown-C261a5Cx.js";
|
|
7
7
|
import { spawn } from "node:child_process";
|
|
8
8
|
import { join, dirname } from "node:path";
|
|
9
9
|
function distRoot() {
|
|
@@ -337,9 +337,9 @@ async function runConsoleCommand(cmd, args, client) {
|
|
|
337
337
|
const seconds = Number(args[0] ?? 60);
|
|
338
338
|
if (!Number.isFinite(seconds) || seconds <= 0) throw new Error("Usage: watch [seconds]");
|
|
339
339
|
const { EventBus } = await import("./event-bus-DqXvbtEM.js");
|
|
340
|
-
const { ChangeWatcher } = await import("./change-watcher-
|
|
341
|
-
const { IMessageDB } = await import("./imessage-db-
|
|
342
|
-
const { getContactsDbPaths, getImsgDbPath, getSlugsDbPath } = await import("./shutdown-
|
|
340
|
+
const { ChangeWatcher } = await import("./change-watcher-DJ24OAN9.js");
|
|
341
|
+
const { IMessageDB } = await import("./imessage-db-kP5t2aZb.js").then((n) => n.i);
|
|
342
|
+
const { getContactsDbPaths, getImsgDbPath, getSlugsDbPath } = await import("./shutdown-C261a5Cx.js").then((n) => n.ak);
|
|
343
343
|
const db = new IMessageDB(getImsgDbPath(), getContactsDbPaths(), getSlugsDbPath());
|
|
344
344
|
const bus = new EventBus();
|
|
345
345
|
const watcher = new ChangeWatcher({ dbPath: getImsgDbPath(), db, bus });
|
|
@@ -486,9 +486,9 @@ async function runExportCommand(target, opts) {
|
|
|
486
486
|
const { existsSync: existsSync2, mkdirSync, copyFileSync, statSync } = await import("node:fs");
|
|
487
487
|
const { homedir } = await import("node:os");
|
|
488
488
|
const { dirname: dirname2, join: join2, isAbsolute, resolve } = await import("node:path");
|
|
489
|
-
const { getContactsDbPaths, getImsgDbPath, getSlugsDbPath } = await import("./shutdown-
|
|
490
|
-
const { IMessageDB } = await import("./imessage-db-
|
|
491
|
-
const { streamExport } = await import("./exportStream-
|
|
489
|
+
const { getContactsDbPaths, getImsgDbPath, getSlugsDbPath } = await import("./shutdown-C261a5Cx.js").then((n) => n.ak);
|
|
490
|
+
const { IMessageDB } = await import("./imessage-db-kP5t2aZb.js").then((n) => n.i);
|
|
491
|
+
const { streamExport } = await import("./exportStream-DxyUSZw8.js");
|
|
492
492
|
const { parseUserDate } = await import("./date-parse-DJXMfq3a.js");
|
|
493
493
|
const format = normalizeFormat(opts.format ?? "md");
|
|
494
494
|
const ext = extForFormat(format);
|
|
@@ -543,13 +543,13 @@ async function runExportCommand(target, opts) {
|
|
|
543
543
|
if (since) filters.sinceMs = since.getTime();
|
|
544
544
|
if (until) filters.untilMs = until.getTime();
|
|
545
545
|
const attachments = db.searchAttachments(filters);
|
|
546
|
-
const { resolveInterpretConfig } = await import("./app-config-
|
|
546
|
+
const { resolveInterpretConfig } = await import("./app-config-DAwcDA3h.js");
|
|
547
547
|
const nudge = resolveInterpretConfig().nudge;
|
|
548
548
|
const firstMissing = attachments.find(
|
|
549
549
|
(a) => a.filename && !existsSync2(a.filename.replace(/^~/, homedir()))
|
|
550
550
|
);
|
|
551
551
|
if (nudge.enabled && firstMissing && chatIdentifier) {
|
|
552
|
-
const { ensureAttachmentDownloaded } = await import("./attachment-sync-
|
|
552
|
+
const { ensureAttachmentDownloaded } = await import("./attachment-sync-CD-v_qpd.js");
|
|
553
553
|
log(` Nudging Messages to sync missing attachments…`, "dim");
|
|
554
554
|
await ensureAttachmentDownloaded(
|
|
555
555
|
{ filePath: firstMissing.filename.replace(/^~/, homedir()), chatId: chatIdentifier },
|
|
@@ -759,10 +759,10 @@ program.command("interpret <rowId>").description("Interpret one attachment (tran
|
|
|
759
759
|
process.exitCode = 1;
|
|
760
760
|
return;
|
|
761
761
|
}
|
|
762
|
-
const { getContactsDbPaths, getImsgDbPath, getSlugsDbPath } = await import("./shutdown-
|
|
763
|
-
const { IMessageDB } = await import("./imessage-db-
|
|
764
|
-
const { getInterpretRuntime, refForAttachment } = await import("./media-intel-runtime-
|
|
765
|
-
const { deleteMediaIntel } = await import("./media-intel-cache-
|
|
762
|
+
const { getContactsDbPaths, getImsgDbPath, getSlugsDbPath } = await import("./shutdown-C261a5Cx.js").then((n) => n.ak);
|
|
763
|
+
const { IMessageDB } = await import("./imessage-db-kP5t2aZb.js").then((n) => n.i);
|
|
764
|
+
const { getInterpretRuntime, refForAttachment } = await import("./media-intel-runtime-DTHMFjik.js").then((n) => n.c);
|
|
765
|
+
const { deleteMediaIntel } = await import("./media-intel-cache-sRx_ix5A.js");
|
|
766
766
|
const db = new IMessageDB(getImsgDbPath(), getContactsDbPaths(), getSlugsDbPath());
|
|
767
767
|
try {
|
|
768
768
|
const rec = db.getAttachmentByRowId(rowId);
|
|
@@ -797,7 +797,7 @@ program.command("interpret <rowId>").description("Interpret one attachment (tran
|
|
|
797
797
|
program.command("setup").description("Autodetect DB paths and emit an MCP host config snippet").option("-w, --write <host>", 'Write into a host config: "claude" or "cursor"').option("-r, --runtime <runtime>", 'Runtime command: "npx" (default), "bunx", or "global"').option("--print-only", "Just print the snippet (default behaviour)").option("-i, --interactive", "Configure media interpretation (providers, chains, keys)").action(
|
|
798
798
|
async (opts) => {
|
|
799
799
|
if (opts.interactive) {
|
|
800
|
-
const { runSetupWizard } = await import("./setup-wizard-
|
|
800
|
+
const { runSetupWizard } = await import("./setup-wizard-D8QvveiW.js");
|
|
801
801
|
try {
|
|
802
802
|
await runSetupWizard();
|
|
803
803
|
} catch (err) {
|
|
@@ -809,7 +809,7 @@ program.command("setup").description("Autodetect DB paths and emit an MCP host c
|
|
|
809
809
|
}
|
|
810
810
|
return;
|
|
811
811
|
}
|
|
812
|
-
const { probeMachine, buildMcpSnippet, writeHostConfig } = await import("./setup-
|
|
812
|
+
const { probeMachine, buildMcpSnippet, writeHostConfig } = await import("./setup-DJ3g_smJ.js");
|
|
813
813
|
const report = probeMachine();
|
|
814
814
|
if (!report.imsgDb.readable) {
|
|
815
815
|
log(`✗ Messages DB is not readable: ${report.imsgDb.path}`, "err");
|
|
@@ -852,7 +852,7 @@ program.command("setup").description("Autodetect DB paths and emit an MCP host c
|
|
|
852
852
|
);
|
|
853
853
|
const configCmd = program.command("config").description("Manage TUI settings (theme, accent color)");
|
|
854
854
|
configCmd.command("show").description("Print resolved TUI settings and where each value came from").action(async () => {
|
|
855
|
-
const { resolveTuiConfig, defaultTuiConfigPath } = await import("./tui-config-
|
|
855
|
+
const { resolveTuiConfig, defaultTuiConfigPath } = await import("./tui-config-DRdkPMP8.js");
|
|
856
856
|
const cfg = resolveTuiConfig();
|
|
857
857
|
log(
|
|
858
858
|
`config file : ${cfg.configPath ?? `(none — defaults; would write to ${defaultTuiConfigPath()})`}`
|
|
@@ -865,7 +865,7 @@ configCmd.command("show").description("Print resolved TUI settings and where eac
|
|
|
865
865
|
for (const w of cfg.warnings) log(w, "warn");
|
|
866
866
|
});
|
|
867
867
|
configCmd.command("edit").description("Open the TUI config file in $EDITOR (creates it if missing)").action(async () => {
|
|
868
|
-
const { defaultTuiConfigPath, findTuiConfigPath, writeTuiConfig, DEFAULT_TUI_CONFIG } = await import("./tui-config-
|
|
868
|
+
const { defaultTuiConfigPath, findTuiConfigPath, writeTuiConfig, DEFAULT_TUI_CONFIG } = await import("./tui-config-DRdkPMP8.js");
|
|
869
869
|
const path = findTuiConfigPath() ?? defaultTuiConfigPath();
|
|
870
870
|
const { existsSync: existsSync2 } = await import("node:fs");
|
|
871
871
|
if (!existsSync2(path)) {
|
|
@@ -71,20 +71,6 @@ function toCSV(messages) {
|
|
|
71
71
|
}
|
|
72
72
|
return lines.join("\n");
|
|
73
73
|
}
|
|
74
|
-
function toJSON(messages, header) {
|
|
75
|
-
const data = {
|
|
76
|
-
...header ?? {},
|
|
77
|
-
exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
78
|
-
count: messages.length,
|
|
79
|
-
messages: messages.map((m) => ({
|
|
80
|
-
...m,
|
|
81
|
-
date: m.date.toISOString(),
|
|
82
|
-
dateRead: m.dateRead?.toISOString() ?? null,
|
|
83
|
-
dateDelivered: m.dateDelivered?.toISOString() ?? null
|
|
84
|
-
}))
|
|
85
|
-
};
|
|
86
|
-
return JSON.stringify(data, null, 2);
|
|
87
|
-
}
|
|
88
74
|
function toNDJSONLine(m) {
|
|
89
75
|
const entry = {
|
|
90
76
|
...m,
|
|
@@ -111,8 +97,7 @@ function extensionFor(format) {
|
|
|
111
97
|
export {
|
|
112
98
|
toCSV as a,
|
|
113
99
|
toNDJSONLine as b,
|
|
114
|
-
toJSON as c,
|
|
115
100
|
extensionFor as e,
|
|
116
101
|
toMarkdown as t
|
|
117
102
|
};
|
|
118
|
-
//# sourceMappingURL=export-formats-
|
|
103
|
+
//# sourceMappingURL=export-formats-caHQJDm0.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"export-formats-
|
|
1
|
+
{"version":3,"file":"export-formats-caHQJDm0.js","sources":["../src/export-formats.ts"],"sourcesContent":["/**\n * Format converters for exporting messages from the TUI.\n *\n * All three formats accept the same Message[] + optional header info.\n * Keep these pure (no fs / no React) — the modal + MCP export tool both\n * call into them.\n */\nimport type { Message } from \"./types.js\";\n\nexport interface ExportHeader {\n thread: string;\n participants?: string[];\n serviceType?: string;\n}\n\nfunction fmtDate(d: Date): string {\n return d\n .toISOString()\n .replace(\"T\", \" \")\n .replace(/\\.\\d+Z$/, \"\");\n}\n\nfunction senderLabel(m: Message): string {\n if (m.isFromMe) return \"Me\";\n return m.displayName ?? m.handle;\n}\n\n/** Markdown — human-readable, suitable for sharing or further processing. */\nexport function toMarkdown(messages: Message[], header: ExportHeader): string {\n const lines: string[] = [];\n lines.push(`# ${header.thread}`);\n lines.push(\"\");\n if (header.participants && header.participants.length > 0) {\n lines.push(`**Participants**: ${header.participants.join(\", \")}`);\n }\n if (header.serviceType) {\n lines.push(`**Service**: ${header.serviceType}`);\n }\n lines.push(`**Exported**: ${fmtDate(new Date())} (${messages.length} messages)`);\n lines.push(\"\");\n lines.push(\"---\");\n lines.push(\"\");\n\n for (const m of messages) {\n if (m.isReply && m.replyTo?.replyToText) {\n lines.push(`> ${m.replyTo.replyToText.replace(/\\n/g, \"\\n> \")}`);\n }\n const ts = `[${fmtDate(m.date)}]`;\n const sender = senderLabel(m);\n let text = m.text ?? (m.hasAttachments ? \"*(attachment)*\" : \"*(no text)*\");\n // Embed a resolved voice-note transcript / image-video caption: replace the\n // placeholder when the message has no text of its own, else append a tag.\n const interp = m.interpretedMedia;\n if (interp) {\n const label = interp.kind === \"audio\" ? \"voice note\" : interp.kind;\n text = m.text ? `${m.text} _[${label}: ${interp.text}]_` : `_[${label}: ${interp.text}]_`;\n }\n const flags: string[] = [];\n if (m.isEdited) flags.push(\"edited\");\n if (m.hasAttachments) flags.push(\"📎\");\n const flagStr = flags.length > 0 ? ` _(${flags.join(\", \")})_` : \"\";\n lines.push(`**${ts}** ${sender}: ${text}${flagStr}`);\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n\n/** CSV — for spreadsheet import. RFC 4180-ish quoting. */\nexport function toCSV(messages: Message[]): string {\n const escapeCsv = (v: string | null | undefined): string => {\n if (v == null) return \"\";\n if (/[\",\\n\\r]/.test(v)) {\n return `\"${v.replace(/\"/g, '\"\"')}\"`;\n }\n return v;\n };\n\n const lines: string[] = [];\n lines.push(\n \"id,date,sender,handle,is_from_me,is_read,is_reply,reply_to_text,text,has_attachments\",\n );\n\n for (const m of messages) {\n const row = [\n String(m.id),\n m.date.toISOString(),\n escapeCsv(senderLabel(m)),\n escapeCsv(m.handle),\n m.isFromMe ? \"1\" : \"0\",\n m.isRead ? \"1\" : \"0\",\n m.isReply ? \"1\" : \"0\",\n escapeCsv(m.replyTo?.replyToText ?? \"\"),\n // For a media-only message (voice note, image), surface the resolved\n // transcript/caption in the text column so spreadsheets aren't blank.\n escapeCsv(m.text ?? m.interpretedMedia?.text ?? \"\"),\n m.hasAttachments ? \"1\" : \"0\",\n ];\n lines.push(row.join(\",\"));\n }\n\n return lines.join(\"\\n\");\n}\n\n/** JSON — full message objects, indented, dates as ISO strings. */\nexport function toJSON(messages: Message[], header?: ExportHeader): string {\n const data = {\n ...(header ?? {}),\n exportedAt: new Date().toISOString(),\n count: messages.length,\n messages: messages.map((m) => ({\n ...m,\n date: m.date.toISOString(),\n dateRead: m.dateRead?.toISOString() ?? null,\n dateDelivered: m.dateDelivered?.toISOString() ?? null,\n })),\n };\n return JSON.stringify(data, null, 2);\n}\n\n/** NDJSON — newline-delimited JSON, ideal for streaming exports. */\nexport function toNDJSONLine(m: Message): string {\n const entry: Record<string, unknown> = {\n ...m,\n date: m.date.toISOString(),\n dateRead: m.dateRead?.toISOString() ?? null,\n dateDelivered: m.dateDelivered?.toISOString() ?? null,\n };\n // Sort top-level keys so the same data always serializes to the same bytes.\n // Message objects come from different construction paths (TS parser, native\n // parser, cache hydration) whose property insertion order can differ, which\n // made re-exports of identical data diff at the byte level.\n return JSON.stringify(\n Object.fromEntries(Object.entries(entry).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),\n );\n}\n\n/** Choose extension for a given format. */\nexport function extensionFor(format: \"markdown\" | \"csv\" | \"json\" | \"ndjson\"): string {\n switch (format) {\n case \"markdown\":\n return \"md\";\n case \"csv\":\n return \"csv\";\n case \"json\":\n return \"json\";\n case \"ndjson\":\n return \"ndjson\";\n }\n}\n"],"names":[],"mappings":"AAeA,SAAS,QAAQ,GAAiB;AAChC,SAAO,EACJ,cACA,QAAQ,KAAK,GAAG,EAChB,QAAQ,WAAW,EAAE;AAC1B;AAEA,SAAS,YAAY,GAAoB;AACvC,MAAI,EAAE,SAAU,QAAO;AACvB,SAAO,EAAE,eAAe,EAAE;AAC5B;AAGO,SAAS,WAAW,UAAqB,QAA8B;AAC5E,QAAM,QAAkB,CAAA;AACxB,QAAM,KAAK,KAAK,OAAO,MAAM,EAAE;AAC/B,QAAM,KAAK,EAAE;AACb,MAAI,OAAO,gBAAgB,OAAO,aAAa,SAAS,GAAG;AACzD,UAAM,KAAK,qBAAqB,OAAO,aAAa,KAAK,IAAI,CAAC,EAAE;AAAA,EAClE;AACA,MAAI,OAAO,aAAa;AACtB,UAAM,KAAK,gBAAgB,OAAO,WAAW,EAAE;AAAA,EACjD;AACA,QAAM,KAAK,iBAAiB,QAAQ,oBAAI,MAAM,CAAC,KAAK,SAAS,MAAM,YAAY;AAC/E,QAAM,KAAK,EAAE;AACb,QAAM,KAAK,KAAK;AAChB,QAAM,KAAK,EAAE;AAEb,aAAW,KAAK,UAAU;AACxB,QAAI,EAAE,WAAW,EAAE,SAAS,aAAa;AACvC,YAAM,KAAK,KAAK,EAAE,QAAQ,YAAY,QAAQ,OAAO,MAAM,CAAC,EAAE;AAAA,IAChE;AACA,UAAM,KAAK,IAAI,QAAQ,E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,UAAU,EAAE,QAAQ,EAAE,kBAAkB,QAAQ,EAAE;AAAA,MAClD,EAAE,iBAAiB,MAAM;AAAA,IAAA;AAE3B,UAAM,KAAK,IAAI,KAAK,GAAG,CAAC;AAAA,EAC1B;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;AAmBO,SAAS,aAAa,GAAoB;AAC/C,QAAM,QAAiC;AAAA,IACrC,GAAG;AAAA,IACH,MAAM,EAAE,KAAK,YAAA;AAAA,IACb,UAAU,EAAE,UAAU,YAAA,KAAiB;AAAA,IACvC,eAAe,EAAE,eAAe,iBAAiB;AAAA,EAAA;AAMnD,SAAO,KAAK;AAAA,IACV,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAAC;AAAA,EAAA;AAE7F;AAGO,SAAS,aAAa,QAAwD;AACnF,UAAQ,QAAA;AAAA,IACN,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,EAAA;AAEb;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createWriteStream, statSync } from "node:fs";
|
|
2
|
-
import { t as toMarkdown, a as toCSV, b as toNDJSONLine } from "./export-formats-
|
|
3
|
-
import { g as getInterpretRuntime, r as refsForMessages, e as embedInterpretations } from "./media-intel-runtime-
|
|
2
|
+
import { t as toMarkdown, a as toCSV, b as toNDJSONLine } from "./export-formats-caHQJDm0.js";
|
|
3
|
+
import { g as getInterpretRuntime, r as refsForMessages, e as embedInterpretations } from "./media-intel-runtime-DTHMFjik.js";
|
|
4
4
|
class ExportInterpretGuardError extends Error {
|
|
5
5
|
constructor(uncachedCloud, threshold) {
|
|
6
6
|
super(
|
|
@@ -168,4 +168,4 @@ export {
|
|
|
168
168
|
ExportInterpretGuardError,
|
|
169
169
|
streamExport
|
|
170
170
|
};
|
|
171
|
-
//# sourceMappingURL=exportStream-
|
|
171
|
+
//# sourceMappingURL=exportStream-DxyUSZw8.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exportStream-CFfWlvVb.js","sources":["../src/exportStream.ts"],"sourcesContent":["/**\n * Streaming exporter — writes a conversation to a file in pages so a 100k\n * message history doesn't blow up memory. Used by the `export_messages`\n * MCP tool.\n *\n * Strategy:\n * 1. Walk history chronologically with a stable `(date, ROWID)` cursor.\n * 2. Each page is formatted and written immediately to a writable stream.\n * 3. For JSON we emit a top-level `{ ..., messages: [...] }` shape, opening\n * the array, comma-separating page entries, then closing — that way we\n * never hold the full array in memory.\n * 4. NDJSON is the simplest streaming option (one JSON object per line) —\n * recommended for large exports.\n */\n\nimport { createWriteStream, statSync } from \"node:fs\";\nimport { toCSV, toMarkdown, toNDJSONLine } from \"./export-formats.js\";\nimport type { IMessageDB, MessageExportCursor, UnmergedSiblingChat } from \"./imessage-db.js\";\nimport {\n embedInterpretations,\n getInterpretRuntime,\n type InterpretRuntime,\n refsForMessages,\n} from \"./media-intel-runtime.js\";\n\nexport interface ExportOptions {\n db: IMessageDB;\n chatIdentifier: string;\n format: \"markdown\" | \"csv\" | \"json\" | \"ndjson\";\n outputPath: string;\n since: Date | null;\n until: Date | null;\n pageSize: number;\n signal?: AbortSignal;\n /**\n * Actively interpret media during export (transcribe voice notes, caption\n * images/videos) and embed the text. Cached + instant Apple transcripts are\n * embedded regardless; this only controls whether NEW (incl. paid) calls run.\n */\n interpret?: boolean;\n /** Skip the paid-call guard (see `exportConfirmThreshold`). */\n confirmCloudInterpret?: boolean;\n /** Injectable interpret runtime (defaults to the process singleton). */\n interpretRuntime?: InterpretRuntime;\n}\n\n/**\n * Thrown before any output is written when an `interpret` export would trigger\n * more uncached cloud calls than the configured threshold and the caller has\n * not confirmed. The handler turns this into an actionable message.\n */\nexport class ExportInterpretGuardError extends Error {\n constructor(\n public readonly uncachedCloud: number,\n public readonly threshold: number,\n ) {\n super(\n `This export would trigger ${uncachedCloud} uncached cloud interpretation call(s) (threshold ${threshold}). Re-run with confirmCloudInterpret:true to proceed, or narrow the range with since/until.`,\n );\n this.name = \"ExportInterpretGuardError\";\n }\n}\n\nexport interface ExportResult {\n savedTo: string;\n count: number;\n oldest: Date | null;\n newest: Date | null;\n sizeBytes: number;\n unmergedSiblings: UnmergedSiblingChat[];\n}\n\n/** Type guard — Node ESM filesystem stream */\ntype WritableStream = ReturnType<typeof createWriteStream>;\n\nfunction writeAndDrain(stream: WritableStream, chunk: string): Promise<void> {\n return new Promise((resolve, reject) => {\n if (stream.write(chunk)) {\n resolve();\n return;\n }\n // Back-pressure path: register both listeners and ensure either side\n // also removes the OTHER. Pre-fix only the firing side cleaned up\n // (via .once), so each back-pressure tick leaked a stale \"error\"\n // listener — exporting a 26k-msg thread triggered the MaxListeners\n // warning around the 11th tick.\n const onDrain = () => {\n stream.removeListener(\"error\", onError);\n resolve();\n };\n const onError = (err: Error) => {\n stream.removeListener(\"drain\", onDrain);\n reject(err);\n };\n stream.once(\"drain\", onDrain);\n stream.once(\"error\", onError);\n });\n}\n\nfunction endStream(stream: WritableStream): Promise<void> {\n return new Promise((resolve, reject) => {\n stream.end((err?: Error | null) => (err ? reject(err) : resolve()));\n });\n}\n\nexport async function streamExport(opts: ExportOptions): Promise<ExportResult> {\n const { db, chatIdentifier, format, outputPath, since, until, pageSize, signal } = opts;\n const interpret = opts.interpret ?? false;\n const runtime = opts.interpretRuntime ?? getInterpretRuntime();\n const embedActive = interpret;\n\n // Guard: an ACTIVE-interpret export can fan out into many paid calls. Count\n // the uncached-cloud work in a metadata-only pre-pass BEFORE truncating the\n // output file, and refuse (throwing) when it exceeds the threshold unless the\n // caller confirmed. Cached/instant embedding needs no guard.\n if (interpret && !opts.confirmCloudInterpret) {\n const threshold = runtime.config.exportConfirmThreshold;\n let uncached = 0;\n let guardCursor: MessageExportCursor | null = null;\n while (true) {\n if (signal?.aborted) throw new Error(\"Export cancelled by client.\");\n const page = await db.getMessagesForChatExportPage(chatIdentifier, pageSize, {\n afterCursor: guardCursor,\n since,\n until,\n });\n if (page.messages.length === 0) break;\n uncached += runtime.service.countUncachedCloud(refsForMessages(page.messages));\n guardCursor = page.nextCursor;\n if (!guardCursor || page.rawCount < pageSize) break;\n await new Promise((r) => setImmediate(r));\n }\n if (uncached > threshold) throw new ExportInterpretGuardError(uncached, threshold);\n }\n\n const stream = createWriteStream(outputPath, { encoding: \"utf8\" });\n\n let count = 0;\n let oldest: Date | null = null;\n let newest: Date | null = null;\n let cursor: MessageExportCursor | null = null;\n\n try {\n if (signal?.aborted) throw new Error(\"Export cancelled by client.\");\n\n // Header\n if (format === \"markdown\") {\n const conv = await db.findChatByHandle(chatIdentifier);\n const name = conv?.displayName ?? conv?.rawIdentifier ?? chatIdentifier;\n await writeAndDrain(stream, `# ${name}\\n\\n`);\n if (conv?.threadSlug) await writeAndDrain(stream, `**Slug**: \\`${conv.threadSlug}\\`\\n`);\n if (since) await writeAndDrain(stream, `**Since**: ${since.toISOString()}\\n`);\n if (until) await writeAndDrain(stream, `**Until**: ${until.toISOString()}\\n`);\n await writeAndDrain(stream, `**Exported**: ${new Date().toISOString()}\\n\\n---\\n\\n`);\n } else if (format === \"csv\") {\n await writeAndDrain(\n stream,\n \"id,date,sender,handle,is_from_me,is_read,is_reply,reply_to_text,text,has_attachments\\n\",\n );\n } else if (format === \"json\") {\n await writeAndDrain(\n stream,\n `{\\n \"chatIdentifier\": ${JSON.stringify(chatIdentifier)},\\n \"exportedAt\": ${JSON.stringify(new Date().toISOString())},\\n \"messages\": [\\n`,\n );\n }\n // ndjson: no header\n\n let firstJson = true;\n\n // Page through history in chronological order. The export-specific DB\n // method applies date bounds in SQL and dedupes merged chat rows before\n // LIMIT so every normal message gets one chance to be exported.\n while (true) {\n if (signal?.aborted) throw new Error(\"Export cancelled by client.\");\n const page = await db.getMessagesForChatExportPage(chatIdentifier, pageSize, {\n includeReactionDetails: true,\n afterCursor: cursor,\n since,\n until,\n });\n if (page.messages.length === 0) break;\n\n // Embed voice-note transcripts / captions: cached + instant always, plus\n // active (incl. paid) interpretation when requested. The guard above has\n // already cleared any cloud fan-out.\n await embedInterpretations(page.messages, runtime, embedActive);\n\n // Track running oldest/newest for the result\n for (const m of page.messages) {\n if (oldest == null || m.date < oldest) oldest = m.date;\n if (newest == null || m.date > newest) newest = m.date;\n }\n\n // Format and write\n if (page.messages.length > 0) {\n if (format === \"markdown\") {\n await writeAndDrain(\n stream,\n toMarkdown(page.messages, { thread: chatIdentifier }).split(\"\\n\").slice(6).join(\"\\n\"),\n );\n // ^ slice(6) skips the per-page header (6 lines without participants) — we wrote it once above\n } else if (format === \"csv\") {\n // toCSV emits its own header; skip the first line on each page\n const csvBody = toCSV(page.messages).split(\"\\n\").slice(1).join(\"\\n\");\n await writeAndDrain(stream, `${csvBody}\\n`);\n } else if (format === \"json\") {\n for (const m of page.messages) {\n if (!firstJson) await writeAndDrain(stream, \",\\n\");\n await writeAndDrain(stream, ` ${toNDJSONLine(m)}`);\n firstJson = false;\n }\n } else if (format === \"ndjson\") {\n for (const m of page.messages) {\n await writeAndDrain(stream, `${toNDJSONLine(m)}\\n`);\n }\n }\n }\n count += page.messages.length;\n\n cursor = page.nextCursor;\n if (!cursor || page.rawCount < pageSize) break; // last page\n\n // Yield so other tasks (e.g. health_check) can run\n await new Promise((r) => setImmediate(r));\n }\n\n // Footer\n if (format === \"json\") {\n await writeAndDrain(stream, `\\n ],\\n \"count\": ${count}\\n}\\n`);\n }\n\n await endStream(stream);\n const sizeBytes = (() => {\n try {\n return statSync(outputPath).size;\n } catch {\n return 0;\n }\n })();\n\n const unmergedSiblings = db.findUnmergedSiblingChats(chatIdentifier);\n\n return { savedTo: outputPath, count, oldest, newest, sizeBytes, unmergedSiblings };\n } catch (error) {\n stream.destroy();\n throw error;\n }\n}\n"],"names":[],"mappings":";;;AAmDO,MAAM,kCAAkC,MAAM;AAAA,EACnD,YACkB,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SAAU;AAGzC,YAAM,IAAI,QAAQ,CAAC,MAAM,aAAa,CAAC,CAAC;AAAA,IAC1C;AAGA,QAAI,WAAW,QAAQ;AACrB,YAAM,cAAc,QAAQ;AAAA;AAAA,aAAsB,KAAK;AAAA;AAAA,CAAO;AAAA,IAChE;AAEA,UAAM,UAAU,MAAM;AACtB,UAAM,aAAa,MAAM;AACvB,UAAI;AACF,eAAO,SAAS,UAAU,EAAE;AAAA,MAC9B,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF,GAAA;AAEA,UAAM,mBAAmB,GAAG,yBAAyB,cAAc;AAEnE,WAAO,EAAE,SAAS,YAAY,OAAO,QAAQ,QAAQ,WAAW,iBAAA;AAAA,EAClE,SAAS,OAAO;AACd,WAAO,QAAA;AACP,UAAM;AAAA,EACR;AACF;"}
|
|
1
|
+
{"version":3,"file":"exportStream-DxyUSZw8.js","sources":["../src/exportStream.ts"],"sourcesContent":["/**\n * Streaming exporter — writes a conversation to a file in pages so a 100k\n * message history doesn't blow up memory. Used by the `export_messages`\n * MCP tool.\n *\n * Strategy:\n * 1. Walk history chronologically with a stable `(date, ROWID)` cursor.\n * 2. Each page is formatted and written immediately to a writable stream.\n * 3. For JSON we emit a top-level `{ ..., messages: [...] }` shape, opening\n * the array, comma-separating page entries, then closing — that way we\n * never hold the full array in memory.\n * 4. NDJSON is the simplest streaming option (one JSON object per line) —\n * recommended for large exports.\n */\n\nimport { createWriteStream, statSync } from \"node:fs\";\nimport { toCSV, toMarkdown, toNDJSONLine } from \"./export-formats.js\";\nimport type { IMessageDB, MessageExportCursor, UnmergedSiblingChat } from \"./imessage-db.js\";\nimport {\n embedInterpretations,\n getInterpretRuntime,\n type InterpretRuntime,\n refsForMessages,\n} from \"./media-intel-runtime.js\";\n\nexport interface ExportOptions {\n db: IMessageDB;\n chatIdentifier: string;\n format: \"markdown\" | \"csv\" | \"json\" | \"ndjson\";\n outputPath: string;\n since: Date | null;\n until: Date | null;\n pageSize: number;\n signal?: AbortSignal;\n /**\n * Actively interpret media during export (transcribe voice notes, caption\n * images/videos) and embed the text. Cached + instant Apple transcripts are\n * embedded regardless; this only controls whether NEW (incl. paid) calls run.\n */\n interpret?: boolean;\n /** Skip the paid-call guard (see `exportConfirmThreshold`). */\n confirmCloudInterpret?: boolean;\n /** Injectable interpret runtime (defaults to the process singleton). */\n interpretRuntime?: InterpretRuntime;\n}\n\n/**\n * Thrown before any output is written when an `interpret` export would trigger\n * more uncached cloud calls than the configured threshold and the caller has\n * not confirmed. The handler turns this into an actionable message.\n */\nexport class ExportInterpretGuardError extends Error {\n constructor(\n public readonly uncachedCloud: number,\n public readonly threshold: number,\n ) {\n super(\n `This export would trigger ${uncachedCloud} uncached cloud interpretation call(s) (threshold ${threshold}). Re-run with confirmCloudInterpret:true to proceed, or narrow the range with since/until.`,\n );\n this.name = \"ExportInterpretGuardError\";\n }\n}\n\nexport interface ExportResult {\n savedTo: string;\n count: number;\n oldest: Date | null;\n newest: Date | null;\n sizeBytes: number;\n unmergedSiblings: UnmergedSiblingChat[];\n}\n\n/** Type guard — Node ESM filesystem stream */\ntype WritableStream = ReturnType<typeof createWriteStream>;\n\nfunction writeAndDrain(stream: WritableStream, chunk: string): Promise<void> {\n return new Promise((resolve, reject) => {\n if (stream.write(chunk)) {\n resolve();\n return;\n }\n // Back-pressure path: register both listeners and ensure either side\n // also removes the OTHER. Pre-fix only the firing side cleaned up\n // (via .once), so each back-pressure tick leaked a stale \"error\"\n // listener — exporting a 26k-msg thread triggered the MaxListeners\n // warning around the 11th tick.\n const onDrain = () => {\n stream.removeListener(\"error\", onError);\n resolve();\n };\n const onError = (err: Error) => {\n stream.removeListener(\"drain\", onDrain);\n reject(err);\n };\n stream.once(\"drain\", onDrain);\n stream.once(\"error\", onError);\n });\n}\n\nfunction endStream(stream: WritableStream): Promise<void> {\n return new Promise((resolve, reject) => {\n stream.end((err?: Error | null) => (err ? reject(err) : resolve()));\n });\n}\n\nexport async function streamExport(opts: ExportOptions): Promise<ExportResult> {\n const { db, chatIdentifier, format, outputPath, since, until, pageSize, signal } = opts;\n const interpret = opts.interpret ?? false;\n const runtime = opts.interpretRuntime ?? getInterpretRuntime();\n const embedActive = interpret;\n\n // Guard: an ACTIVE-interpret export can fan out into many paid calls. Count\n // the uncached-cloud work in a metadata-only pre-pass BEFORE truncating the\n // output file, and refuse (throwing) when it exceeds the threshold unless the\n // caller confirmed. Cached/instant embedding needs no guard.\n if (interpret && !opts.confirmCloudInterpret) {\n const threshold = runtime.config.exportConfirmThreshold;\n let uncached = 0;\n let guardCursor: MessageExportCursor | null = null;\n while (true) {\n if (signal?.aborted) throw new Error(\"Export cancelled by client.\");\n const page = await db.getMessagesForChatExportPage(chatIdentifier, pageSize, {\n afterCursor: guardCursor,\n since,\n until,\n });\n if (page.messages.length === 0) break;\n uncached += runtime.service.countUncachedCloud(refsForMessages(page.messages));\n guardCursor = page.nextCursor;\n if (!guardCursor || page.rawCount < pageSize) break;\n await new Promise((r) => setImmediate(r));\n }\n if (uncached > threshold) throw new ExportInterpretGuardError(uncached, threshold);\n }\n\n const stream = createWriteStream(outputPath, { encoding: \"utf8\" });\n\n let count = 0;\n let oldest: Date | null = null;\n let newest: Date | null = null;\n let cursor: MessageExportCursor | null = null;\n\n try {\n if (signal?.aborted) throw new Error(\"Export cancelled by client.\");\n\n // Header\n if (format === \"markdown\") {\n const conv = await db.findChatByHandle(chatIdentifier);\n const name = conv?.displayName ?? conv?.rawIdentifier ?? chatIdentifier;\n await writeAndDrain(stream, `# ${name}\\n\\n`);\n if (conv?.threadSlug) await writeAndDrain(stream, `**Slug**: \\`${conv.threadSlug}\\`\\n`);\n if (since) await writeAndDrain(stream, `**Since**: ${since.toISOString()}\\n`);\n if (until) await writeAndDrain(stream, `**Until**: ${until.toISOString()}\\n`);\n await writeAndDrain(stream, `**Exported**: ${new Date().toISOString()}\\n\\n---\\n\\n`);\n } else if (format === \"csv\") {\n await writeAndDrain(\n stream,\n \"id,date,sender,handle,is_from_me,is_read,is_reply,reply_to_text,text,has_attachments\\n\",\n );\n } else if (format === \"json\") {\n await writeAndDrain(\n stream,\n `{\\n \"chatIdentifier\": ${JSON.stringify(chatIdentifier)},\\n \"exportedAt\": ${JSON.stringify(new Date().toISOString())},\\n \"messages\": [\\n`,\n );\n }\n // ndjson: no header\n\n let firstJson = true;\n\n // Page through history in chronological order. The export-specific DB\n // method applies date bounds in SQL and dedupes merged chat rows before\n // LIMIT so every normal message gets one chance to be exported.\n while (true) {\n if (signal?.aborted) throw new Error(\"Export cancelled by client.\");\n const page = await db.getMessagesForChatExportPage(chatIdentifier, pageSize, {\n includeReactionDetails: true,\n afterCursor: cursor,\n since,\n until,\n });\n if (page.messages.length === 0) break;\n\n // Embed voice-note transcripts / captions: cached + instant always, plus\n // active (incl. paid) interpretation when requested. The guard above has\n // already cleared any cloud fan-out.\n await embedInterpretations(page.messages, runtime, embedActive);\n\n // Track running oldest/newest for the result\n for (const m of page.messages) {\n if (oldest == null || m.date < oldest) oldest = m.date;\n if (newest == null || m.date > newest) newest = m.date;\n }\n\n // Format and write\n if (page.messages.length > 0) {\n if (format === \"markdown\") {\n await writeAndDrain(\n stream,\n toMarkdown(page.messages, { thread: chatIdentifier }).split(\"\\n\").slice(6).join(\"\\n\"),\n );\n // ^ slice(6) skips the per-page header (6 lines without participants) — we wrote it once above\n } else if (format === \"csv\") {\n // toCSV emits its own header; skip the first line on each page\n const csvBody = toCSV(page.messages).split(\"\\n\").slice(1).join(\"\\n\");\n await writeAndDrain(stream, `${csvBody}\\n`);\n } else if (format === \"json\") {\n for (const m of page.messages) {\n if (!firstJson) await writeAndDrain(stream, \",\\n\");\n await writeAndDrain(stream, ` ${toNDJSONLine(m)}`);\n firstJson = false;\n }\n } else if (format === \"ndjson\") {\n for (const m of page.messages) {\n await writeAndDrain(stream, `${toNDJSONLine(m)}\\n`);\n }\n }\n }\n count += page.messages.length;\n\n cursor = page.nextCursor;\n if (!cursor || page.rawCount < pageSize) break; // last page\n\n // Yield so other tasks (e.g. health_check) can run\n await new Promise((r) => setImmediate(r));\n }\n\n // Footer\n if (format === \"json\") {\n await writeAndDrain(stream, `\\n ],\\n \"count\": ${count}\\n}\\n`);\n }\n\n await endStream(stream);\n const sizeBytes = (() => {\n try {\n return statSync(outputPath).size;\n } catch {\n return 0;\n }\n })();\n\n const unmergedSiblings = db.findUnmergedSiblingChats(chatIdentifier);\n\n return { savedTo: outputPath, count, oldest, newest, sizeBytes, unmergedSiblings };\n } catch (error) {\n stream.destroy();\n throw error;\n }\n}\n"],"names":[],"mappings":";;;AAmDO,MAAM,kCAAkC,MAAM;AAAA,EACnD,YACkB,eACA,WAChB;AACA;AAAA,MACE,6BAA6B,aAAa,qDAAqD,SAAS;AAAA,IAAA;AAJ1F,SAAA,gBAAA;AACA,SAAA,YAAA;AAKhB,SAAK,OAAO;AAAA,EACd;AAAA,EAPkB;AAAA,EACA;AAOpB;AAcA,SAAS,cAAc,QAAwB,OAA8B;AAC3E,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI,OAAO,MAAM,KAAK,GAAG;AACvB,cAAA;AACA;AAAA,IACF;AAMA,UAAM,UAAU,MAAM;AACpB,aAAO,eAAe,SAAS,OAAO;AACtC,cAAA;AAAA,IACF;AACA,UAAM,UAAU,CAAC,QAAe;AAC9B,aAAO,eAAe,SAAS,OAAO;AACtC,aAAO,GAAG;AAAA,IACZ;AACA,WAAO,KAAK,SAAS,OAAO;AAC5B,WAAO,KAAK,SAAS,OAAO;AAAA,EAC9B,CAAC;AACH;AAEA,SAAS,UAAU,QAAuC;AACxD,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,WAAO,IAAI,CAAC,QAAwB,MAAM,OAAO,GAAG,IAAI,SAAU;AAAA,EACpE,CAAC;AACH;AAEA,eAAsB,aAAa,MAA4C;AAC7E,QAAM,EAAE,IAAI,gBAAgB,QAAQ,YAAY,OAAO,OAAO,UAAU,OAAA,IAAW;AACnF,QAAM,YAAY,KAAK,aAA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