jsmind 0.9.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +78 -67
  3. package/README.zh.md +81 -0
  4. package/dist/cli.js +4482 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/jsmind.cjs +4101 -0
  7. package/dist/jsmind.cjs.map +1 -0
  8. package/dist/jsmind.d.ts +1269 -0
  9. package/dist/jsmind.js +4099 -0
  10. package/dist/jsmind.js.map +1 -0
  11. package/dist/jsmind.umd.js +4107 -0
  12. package/dist/jsmind.umd.js.map +1 -0
  13. package/package.json +65 -51
  14. package/es6/README-en.md +0 -37
  15. package/es6/README.md +0 -34
  16. package/es6/jsmind.draggable-node.js +0 -9
  17. package/es6/jsmind.draggable-node.js.map +0 -1
  18. package/es6/jsmind.js +0 -9
  19. package/es6/jsmind.js.map +0 -1
  20. package/es6/jsmind.screenshot.js +0 -9
  21. package/es6/jsmind.screenshot.js.map +0 -1
  22. package/style/jsmind.css +0 -408
  23. package/types/generated/index.d.ts +0 -8
  24. package/types/generated/jsmind.common.d.ts +0 -66
  25. package/types/generated/jsmind.d.ts +0 -366
  26. package/types/generated/jsmind.data_provider.d.ts +0 -56
  27. package/types/generated/jsmind.dom.d.ts +0 -59
  28. package/types/generated/jsmind.format.d.ts +0 -100
  29. package/types/generated/jsmind.graph.d.ts +0 -180
  30. package/types/generated/jsmind.layout_provider.d.ts +0 -182
  31. package/types/generated/jsmind.mind.d.ts +0 -121
  32. package/types/generated/jsmind.node.d.ts +0 -62
  33. package/types/generated/jsmind.option.d.ts +0 -64
  34. package/types/generated/jsmind.plugin.d.ts +0 -21
  35. package/types/generated/jsmind.shortcut_provider.d.ts +0 -52
  36. package/types/generated/jsmind.util.d.ts +0 -26
  37. package/types/generated/jsmind.view_provider.d.ts +0 -347
  38. package/types/generated/plugins/jsmind.draggable-node.d.ts +0 -229
  39. package/types/generated/plugins/jsmind.screenshot.d.ts +0 -83
  40. package/types/tsconfig.declaration.json +0 -19
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sources":["../src/cli/exit.ts","../src/cli/io.ts","../src/common/object.ts","../src/model/data/style.ts","../src/common/error.ts","../src/common/index.ts","../src/model/data/node.ts","../src/model/data/edge.ts","../src/model/data/node-content.ts","../src/serialization/validation.ts","../src/cli/browser.ts","../src/view/export.ts","../src/cli/commands/export.ts","../src/cli/commands/validate.ts","../src/observer/manager.ts","../src/common/option.ts","../src/generation/index.ts","../src/model/event/index.ts","../src/model/event/data.ts","../src/model/mind.ts","../src/serialization/json.ts","../src/cli/format.ts","../src/cli/mutate.ts","../src/cli/shared.ts","../src/cli/commands/mind.ts","../src/cli/field-path.ts","../src/cli/commands/node.ts","../src/cli/commands/context.ts","../src/cli/commands/create.ts","../src/cli/index.ts"],"sourcesContent":["/**\n * Exit codes and the error type the CLI commands throw.\n *\n * @remarks\n * The three failure classes are kept apart on purpose. An agent that gets `1`\n * will go and fix the data; one that gets `2` will fix its command line; one\n * that gets `3` will stop and ask a human. Collapsing them into a single code\n * leaves the caller guessing which of those to do.\n *\n * @packageDocumentation\n */\n\n/**\n * Process exit codes.\n *\n * @public\n */\nexport const CliExit = {\n /** Everything worked. */\n Ok: 0,\n /** The data is invalid: validation failed, or a referenced id is absent. */\n InvalidData: 1,\n /** The command line is wrong: missing argument, unknown command, conflicts. */\n Usage: 2,\n /** IO or runtime failure: file missing, no write permission, crash. */\n IoError: 3,\n} as const;\n\nexport type CliExit = typeof CliExit[keyof typeof CliExit];\n\n/**\n * An error that already knows which exit code it deserves.\n *\n * @public\n */\nexport class CliError extends Error {\n /** Exit code this failure maps to. */\n readonly exit: CliExit;\n\n /**\n * @param message - Human-readable description, written to stderr.\n * @param exit - Exit code to terminate with.\n */\n constructor(message: string, exit: CliExit) {\n super(message);\n this.exit = exit;\n this.name = 'CliError';\n }\n}\n\n/**\n * Convenience constructor for a usage error.\n *\n * @param message - What the caller got wrong.\n * @returns A CliError carrying `CliExit.Usage`.\n */\nexport function usageError(message: string): CliError {\n return new CliError(message, CliExit.Usage);\n}\n\n/**\n * Convenience constructor for an invalid-data error.\n *\n * @param message - What is wrong with the data.\n * @returns A CliError carrying `CliExit.InvalidData`.\n */\nexport function dataError(message: string): CliError {\n return new CliError(message, CliExit.InvalidData);\n}\n\n/**\n * Convenience constructor for an IO error.\n *\n * @param message - What failed.\n * @returns A CliError carrying `CliExit.IoError`.\n */\nexport function ioError(message: string): CliError {\n return new CliError(message, CliExit.IoError);\n}\n","/**\n * File and stream plumbing shared by every CLI command.\n *\n * @packageDocumentation\n */\n\nimport { readFileSync, writeFileSync, copyFileSync, existsSync } from 'node:fs';\nimport { dataError, ioError, usageError } from './exit.ts';\n\n/**\n * Reads and parses a JSON file.\n *\n * @param path - File to read.\n * @returns The parsed document.\n * @throws {@link CliError} With `IoError` when the file cannot be read, or with\n * `InvalidData` when it is not valid JSON.\n */\nexport function readJsonFile(path: string): unknown {\n let text: string;\n try {\n text = readFileSync(path, 'utf8');\n } catch (err) {\n const code = (err as { code?: string }).code;\n if (code === 'ENOENT') {\n throw ioError(`File not found: ${path}`);\n }\n if (code === 'EACCES') {\n throw ioError(`Permission denied: ${path}`);\n }\n throw ioError(`Cannot read ${path}: ${(err as Error).message}`);\n }\n\n try {\n return JSON.parse(text);\n } catch (err) {\n // Reachable file, unreadable content: that is a data problem, not a\n // filesystem one. Exit 1 tells the caller to fix the file; exit 3 would\n // send it to a human for something it can see for itself.\n throw dataError(`Not valid JSON: ${path} (${(err as Error).message})`);\n }\n}\n\n/**\n * Renders a document as the CLI writes it.\n *\n * @remarks\n * Two-space indent and a trailing newline, so a file the CLI touches stays\n * diff-friendly instead of collapsing onto one line.\n *\n * @param data - Document to render.\n * @returns JSON text ready to write.\n */\nexport function renderJson(data: unknown): string {\n return `${JSON.stringify(data, null, 2)}\\n`;\n}\n\n/**\n * Options controlling how a command writes its result.\n *\n * @public\n */\nexport interface WriteOptions {\n /** Print what would be written; touch nothing. */\n dryRun: boolean;\n /** Write here instead of the input file. */\n output?: string;\n /** Keep a `.bak` copy of the original before overwriting. */\n backup: boolean;\n}\n\n/**\n * Writes a document to disk.\n *\n * @remarks\n * Returns the text that was written so the caller can validate exactly what\n * landed, rather than re-deriving it and hoping the two agree.\n *\n * @param data - Document to write.\n * @param target - Path to write to.\n * @param options - Dry-run / backup behaviour.\n * @returns The serialized text, or null in dry-run mode.\n */\nexport function writeJsonFile(\n data: unknown,\n target: string,\n options: WriteOptions\n): string | null {\n const text = renderJson(data);\n\n if (options.dryRun) {\n return null;\n }\n\n if (options.backup && existsSync(target)) {\n try {\n copyFileSync(target, `${target}.bak`);\n } catch (err) {\n throw ioError(`Cannot create backup for ${target}: ${(err as Error).message}`);\n }\n }\n\n try {\n writeFileSync(target, text, 'utf8');\n } catch (err) {\n throw ioError(`Cannot write ${target}: ${(err as Error).message}`);\n }\n\n return text;\n}\n\n/**\n * Restores a file to a previously captured state.\n *\n * @remarks\n * Used when validation fails after a write. Best effort: if even the restore\n * fails the caller has already got a loud enough problem, so the original error\n * is not masked by this one.\n *\n * @param target - Path to restore.\n * @param previous - Exact contents to put back.\n */\nexport function restoreFile(target: string, previous: string): void {\n try {\n writeFileSync(target, previous, 'utf8');\n } catch {\n // Nothing useful to add; the caller reports the validation failure,\n // which is the real problem.\n }\n}\n\n/**\n * Reads an integer option that must be present.\n *\n * @param values - Parsed option values.\n * @param name - Option name without dashes.\n * @returns The integer.\n * @throws {@link CliError} With `Usage` when absent or not an integer.\n */\nexport function requireIntOption(values: Record<string, unknown>, name: string): number {\n const raw = values[name];\n if (raw === undefined) {\n throw usageError(`Missing required option --${name}`);\n }\n return parseIntOption(raw, name);\n}\n\n/**\n * Reads an integer option, falling back when it is absent.\n *\n * @param raw - Raw option value.\n * @param fallback - Used when the option is absent.\n * @param name - Option name for the error message.\n * @returns The integer.\n * @throws {@link CliError} With `Usage` when present but not a non-negative integer.\n */\nexport function intOption(raw: unknown, fallback: number, name: string): number {\n if (raw === undefined) {\n return fallback;\n }\n return parseIntOption(raw, name);\n}\n\n/**\n * Reads an optional integer option, or `undefined` when absent.\n *\n * @param values - Parsed option values.\n * @param name - Option name without dashes.\n * @returns The non-negative integer, or `undefined`.\n * @throws {@link CliError} With `Usage` when present but not a non-negative integer.\n * @remarks\n * The optional counterpart of {@link requireIntOption}. Together with\n * {@link numberOption} that covers the three readers this CLI needs - required,\n * optional, fractional - and none of them takes a flag deciding what it accepts:\n * the name says it. A parameter that switched \"allow negatives\" on would have to\n * be passed correctly at every call site, and forgetting it would not fail loudly.\n */\nexport function optionalIntOption(\n values: Record<string, unknown>,\n name: string\n): number | undefined {\n if (values[name] === undefined) {\n return undefined;\n }\n return parseIntOption(values[name], name);\n}\n\n/**\n * Reads a positive number option, falling back when it is absent.\n *\n * Unlike {@link intOption} this accepts fractions, which is what a rendering\n * scale needs: 1.5 is a legitimate value, 0 is not - it would produce an\n * image with no pixels in it.\n *\n * @param raw - Raw option value.\n * @param fallback - Used when the option is absent.\n * @param name - Option name for the error message.\n * @returns The number.\n * @throws {@link CliError} With `Usage` when present but not a positive number.\n */\nexport function numberOption(raw: unknown, fallback: number, name: string): number {\n if (raw === undefined) {\n return fallback;\n }\n const value = Number(raw);\n if (!Number.isFinite(value) || value <= 0) {\n throw usageError(`--${name} must be a positive number, got \"${String(raw)}\"`);\n }\n return value;\n}\n\n/**\n * Reads an option restricted to a fixed set of values.\n *\n * The allowed list goes in the message, because \"not one of image/gif\" alone\n * leaves the caller guessing what would have worked.\n *\n * @param raw - Raw option value.\n * @param fallback - Used when the option is absent.\n * @param allowed - Accepted values.\n * @param name - Option name for the error message.\n * @returns The chosen value.\n * @throws {@link CliError} With `Usage` when present but not in `allowed`.\n */\nexport function enumOption<T extends string>(\n raw: unknown,\n fallback: T,\n allowed: readonly T[],\n name: string\n): T {\n if (raw === undefined) {\n return fallback;\n }\n const value = String(raw) as T;\n if (!allowed.includes(value)) {\n throw usageError(`--${name} must be one of ${allowed.join(', ')}, got \"${value}\"`);\n }\n return value;\n}\n\n/**\n * Converts one raw option value to a non-negative integer.\n *\n * @param raw - Raw value.\n * @param name - Option name for the error message.\n * @returns The integer.\n * @throws {@link CliError} With `Usage` when the value is not a non-negative integer.\n */\nfunction parseIntOption(raw: unknown, name: string): number {\n const value = Number(raw);\n if (!Number.isInteger(value) || value < 0) {\n throw usageError(`--${name} must be a non-negative integer, got \"${String(raw)}\"`);\n }\n return value;\n}\n\n/**\n * Reads a required string option from parsed arguments.\n *\n * @param values - Parsed option values.\n * @param name - Option name without dashes.\n * @returns The value.\n * @throws {@link CliError} With `Usage` when absent.\n */\nexport function requireOption(\n values: Record<string, unknown>,\n name: string\n): string {\n const value = values[name];\n if (typeof value !== 'string' || value.length === 0) {\n throw usageError(`Missing required option --${name}`);\n }\n return value;\n}\n\n/**\n * Reads an optional string option.\n *\n * @param values - Parsed option values.\n * @param name - Option name without dashes.\n * @returns The value, or undefined.\n */\nexport function optionalOption(\n values: Record<string, unknown>,\n name: string\n): string | undefined {\n const value = values[name];\n return typeof value === 'string' ? value : undefined;\n}\n","/**\n * Plain-object helpers.\n *\n * @packageDocumentation\n */\n\n/**\n * Merges user values over default values, returning a new object.\n *\n * @remarks\n * A one-level merge: nested objects are replaced, not merged field by field.\n * Callers that need a deeper merge must merge each nested section themselves.\n *\n * The user values being absent returns a copy of the defaults rather than the\n * defaults themselves, so the result can be mutated without reaching back into\n * whatever constant was passed in.\n *\n * @param defaultValues - The base values.\n * @param userValues - Values to apply on top, if any.\n * @returns A new object; neither input is mutated.\n *\n * @public\n */\nexport function mergeObjects<T>(defaultValues: T, userValues?: Partial<T>): T {\n if (!userValues) {\n return { ...defaultValues };\n }\n\n return {\n ...defaultValues,\n ...userValues\n } as T;\n}\n","/**\n * Style and theme data structures for JsMind mind maps.\n *\n * @remarks\n * This module only defines data. Nothing here draws anything — the rendering\n * layer consumes these values but never appears in this file.\n *\n * @packageDocumentation\n */\n\nimport { mergeObjects } from '../../common/object.ts';\n\n/**\n * Semantic tone. Expresses color only, never geometry.\n *\n * @remarks\n * Semantic roles are about color; geometry is orthogonal (a node can be\n * warning-colored, thick-bordered and large-font at once). Keeping them apart\n * gives the agent fewer side effects per change, which makes generated output\n * more controllable.\n *\n * @public\n */\nexport const JmTone = {\n /** Default tone, resolved from the theme's neutral palette. */\n Default: 'default',\n /** Primary or emphasis tone. */\n Primary: 'primary',\n /** Success or positive tone. */\n Success: 'success',\n /** Warning or caution tone. */\n Warning: 'warning',\n /** Danger or negative tone. */\n Danger: 'danger',\n /** Informational or neutral-accent tone. */\n Info: 'info',\n /**\n * Accent tone for an element that stands out without carrying a judgement.\n *\n * @remarks\n * `primary` already means \"this is the important one\", which is a claim\n * about the content. `accent` is the option for \"make this one visually\n * distinct\" with no claim attached — the purple that v1 exposed as\n * `theme-wisteria` and that none of the semantic tones could absorb.\n */\n Accent: 'accent',\n} as const;\n\nexport type JmTone = typeof JmTone[keyof typeof JmTone];\n\n/**\n * Font weight.\n *\n * @remarks\n * An enum rather than an inline union so the CLI can enumerate the accepted\n * values instead of repeating them. `JmLinePattern` and `JmLineCurve` had this\n * shape already; `fontWeight` was the odd one out.\n *\n * @public\n */\nexport const JmFontWeight = {\n /** Regular weight. */\n Normal: 'normal',\n /** Emphasised weight. */\n Bold: 'bold',\n} as const;\n\nexport type JmFontWeight = typeof JmFontWeight[keyof typeof JmFontWeight];\n\n/**\n * Line dash style.\n *\n * @public\n */\nexport const JmLinePattern = {\n /** Continuous line. */\n Solid: 'solid',\n /** Dashed line. */\n Dashed: 'dashed',\n /** Dotted line. */\n Dotted: 'dotted',\n} as const;\n\nexport type JmLinePattern = typeof JmLinePattern[keyof typeof JmLinePattern];\n\n/**\n * How a line travels between its two endpoints.\n *\n * @remarks\n * A different axis from {@link JmLinePattern}: `pattern` says whether the\n * stroke is dashed, `curve` says what shape it traces. They are separable on\n * purpose - a straight dashed line and a curved dashed line both need to exist,\n * and a single `style` string (as in v1's `line_style`) could only ever express\n * one of the two.\n *\n * @public\n */\nexport const JmLineCurve = {\n /** Straight segment from one endpoint to the other. */\n Straight: 'straight',\n /**\n * Cubic bezier leaving each endpoint horizontally.\n *\n * @remarks\n * The default, and what v1 drew. Edges leaving a node always read better\n * when they depart along the horizontal axis: siblings sit in a column, so a\n * straight segment between two of them cuts diagonally across the layout.\n */\n Bezier: 'bezier',\n} as const;\n\nexport type JmLineCurve = typeof JmLineCurve[keyof typeof JmLineCurve];\n\n/**\n * Visual style of a single line.\n *\n * @remarks\n * Shared by two places: `JmNodeStyle.incoming` (the line connecting a node to\n * its parent) and `JmEdge.style` (lines for additional, non-hierarchical\n * relationships). One shape avoids two vocabularies for the same thing.\n *\n * @public\n */\nexport interface JmLineStyle {\n /** Line color, e.g. `#4a9eff`. */\n color?: string;\n /** Line width in pixels. */\n width?: number;\n /**\n * Line pattern.\n *\n * @remarks\n * Named `pattern` rather than `style` because this type is itself reached\n * through `node.style.incoming`, and `.style.style` reads badly. `pattern`\n * also covers `solid` honestly — `solid` is not a dash.\n */\n pattern?: JmLinePattern;\n /** How the line travels between its endpoints. Defaults to `bezier`. */\n curve?: JmLineCurve;\n}\n\n/**\n * Visual overrides for a single node.\n *\n * @remarks\n * Every field is optional and unset fields fall back to the theme. The node\n * carries only what differs from the theme, so a theme change still reaches\n * every node that did not explicitly override anything.\n *\n * `incoming` lives on the child node: a line connects exactly one child, which\n * makes the child the natural owner. The name mirrors the layout layer\n * (`calculateNodeIncomingPoint` / `calculateNodeOutgoingPoint`).\n *\n * @public\n */\nexport interface JmNodeStyle {\n /** Semantic tone for this node. Overrides background/border/color from the theme. */\n tone?: JmTone;\n /** Background color, e.g. `#ffffff`. */\n background?: string;\n /** Text color. */\n color?: string;\n /** Border color. */\n borderColor?: string;\n /** Border width in pixels. */\n borderWidth?: number;\n /** Border dash style. */\n borderStyle?: JmLinePattern;\n /** Font size in pixels. */\n fontSize?: number;\n /** Font weight. */\n fontWeight?: JmFontWeight;\n /** Style of the line connecting this node to its parent. */\n incoming?: JmLineStyle;\n}\n\n/**\n * Colors a tone resolves to.\n *\n * @remarks\n * `line` is the color of the connecting line, which usually differs from\n * `border` so that a subtree reads as one visual grouping.\n *\n * @public\n */\nexport interface JmTonePalette {\n /**\n * Node background color.\n *\n * @remarks\n * Every field here carries a `Color` suffix. The palette sits alongside\n * `JmNodeStyle`, which already uses `borderColor`, so `borderColor` means\n * the same thing in both places and an agent reading the JSON never has to\n * guess whether `fill` or `border` is a color or a length.\n */\n fillColor: string;\n /** Node text color. */\n textColor: string;\n /** Node border color. */\n borderColor: string;\n /** Connecting line color. */\n lineColor: string;\n}\n\n/**\n * One drop shadow, in CSS terms.\n *\n * @remarks\n * Spelled out as four numbers and a color rather than kept as a CSS string\n * like `\"1px 1px 1px #666\"` so it can be merged field by field — an override\n * that changes only the blur should not have to restate the offsets — and so\n * an agent writing the JSON never has to get CSS shorthand syntax right.\n *\n * @public\n */\nexport interface JmThemeShadowLayer {\n /** Horizontal offset in pixels. */\n offsetX: number;\n /** Vertical offset in pixels. */\n offsetY: number;\n /** Blur radius in pixels. */\n blur: number;\n /** Shadow color, e.g. `#666666`. */\n color: string;\n}\n\n/**\n * Drop shadows for the three visual states a node can be in.\n *\n * @remarks\n * States live in the theme rather than in CSS because they change the node's\n * appearance, and \"how does this node look\" belongs with the rest of the\n * appearance. `normal` is the resting state; `hover` and `selected` are what\n * the pointer and the selection do to it.\n *\n * @public\n */\nexport interface JmThemeShadow {\n /** Shadow when the node is idle. */\n normal: JmThemeShadowLayer;\n /** Shadow while the pointer is over the node. */\n hover: JmThemeShadowLayer;\n /** Shadow when the node is selected. */\n selected: JmThemeShadowLayer;\n}\n\n/**\n * A partial replacement for {@link JmThemeShadow}.\n *\n * @remarks\n * Every level is optional so a style can restyle one state, or one field of one\n * state (`hover.blur`), without restating the rest. The merged result is always\n * complete.\n *\n * @public\n */\nexport interface JmThemeShadowOverride {\n /** Override for the idle shadow. */\n normal?: Partial<JmThemeShadowLayer>;\n /** Override for the hover shadow. */\n hover?: Partial<JmThemeShadowLayer>;\n /** Override for the selected shadow. */\n selected?: Partial<JmThemeShadowLayer>;\n}\n\n/**\n * Partial overrides for {@link JmThemeNode}.\n *\n * @remarks\n * Identical to `Partial<JmThemeNode>` except for `shadow`, which allows\n * overriding a single state rather than all three.\n *\n * @public\n */\nexport type JmThemeNodeOverride = Omit<Partial<JmThemeNode>, 'shadow'> & {\n /** Override for the node shadows. */\n shadow?: JmThemeShadowOverride;\n};\n\n/**\n * Geometry and typography shared by every node.\n *\n * @public\n */\nexport interface JmThemeNode {\n /** Corner radius in pixels. */\n radius: number;\n /** Inner padding in pixels. */\n padding: number;\n /** Base font size in pixels. */\n fontSize: number;\n /**\n * Root node font size in pixels.\n *\n * @remarks\n * Separate from `fontSize` because the root is the one node that reads as a\n * title: v1 rendered it at 24px against a 16px body. Folding it into\n * `fontSize` would have forced every theme to pick one and lose the\n * hierarchy.\n */\n rootFontSize: number;\n /** Font family. */\n fontFamily: string;\n /**\n * Line height as a multiple of the font size.\n *\n * @remarks\n * Unitless multiplier, matching the CSS `line-height: 1.125` form, so it\n * scales with `fontSize` instead of needing a matching pixel value per size.\n */\n lineHeight: number;\n /** Default border width in pixels. */\n borderWidth: number;\n /**\n * Maximum node width in pixels before text wraps.\n *\n * @remarks\n * Wrapping is a layout input, not a detail: it decides how tall a node is,\n * which decides where its children go.\n */\n maxWidth: number;\n /** Drop shadows for the idle, hover and selected states. */\n shadow: JmThemeShadow;\n}\n\n/**\n * Geometry shared by every line of a mind map.\n *\n * @public\n */\nexport interface JmThemeLine {\n /** Default line width in pixels. */\n width: number;\n /** Default line pattern. Named `pattern` to match `JmLineStyle.pattern`. */\n pattern: JmLinePattern;\n /** Default curve shape. Named `curve` to match `JmLineStyle.curve`. */\n curve: JmLineCurve;\n}\n\n/**\n * Geometry of the collapse/expand control.\n *\n * @public\n */\nexport interface JmThemeExpander {\n /** Expander width and height in pixels. */\n size: number;\n /**\n * Corner radius in pixels.\n *\n * @remarks\n * `size / 2` gives a circle, which is what the stylesheet did with\n * `border-radius: 50%`. A number keeps it in the same units as every other\n * length here; percentage radii only make sense when the box can grow.\n */\n radius: number;\n /** Font size of the character or count drawn inside, in pixels. */\n fontSize: number;\n /** Line height of that content, in pixels. */\n lineHeight: number;\n /** Border width in pixels. */\n borderWidth: number;\n}\n\n/**\n * Complete visual theme.\n *\n * @remarks\n * Every section except `name` is optional and merged deeply over the built-in\n * preset it names, so a theme can override one tone color without restating\n * every other color.\n *\n * @public\n */\nexport interface JmTheme {\n /** Canvas background color. */\n background?: string;\n /** Per-tone color palettes. */\n tones?: Partial<Record<JmTone, Partial<JmTonePalette>>>;\n /** Node geometry. */\n node?: Partial<JmThemeNode>;\n /** Line geometry. */\n line?: Partial<JmThemeLine>;\n /** Expander geometry. */\n expander?: Partial<JmThemeExpander>;\n}\n\n/**\n * Style declaration for a whole mind map, as stored in the data file.\n *\n * @remarks\n * Named in the singular, like the per-node and per-edge style fields: one\n * `style` concept, with the scope decided by where it sits. `mind.style` covers\n * the whole map; `node.style` covers one node; `edge.style` covers one edge.\n * Carrying both `styles` and `style` in one document only differed by an `s`,\n * which is a trap for an agent generating the JSON.\n *\n * Read this as: \"this mind map looks like this — it inherits from `theme`, then\n * overrides the fields listed below.\"\n *\n * Splitting inheritance from overrides into one flat declaration avoids the\n * ambiguity of a nested `{ name, ...overrides }` form, where `name` could be\n * read either as \"what this theme is called\" or as \"which theme to inherit\".\n * Here `theme` can only mean the latter.\n *\n * - `theme` names a built-in preset to inherit from. Omitted means `\"default\"`,\n * so a file that only overrides a few colors does not have to name it.\n * - Every other field is an override applied on top of that preset, merged\n * deeply.\n *\n * @public\n */\nexport interface JmStyle {\n /** Name of the built-in theme to inherit from. Defaults to `\"default\"`. */\n theme?: string;\n /** Canvas background color. */\n background?: string;\n /** Per-tone color overrides. */\n tones?: Partial<Record<JmTone, Partial<JmTonePalette>>>;\n /** Node geometry overrides. */\n node?: JmThemeNodeOverride;\n /** Line geometry overrides. */\n line?: Partial<JmThemeLine>;\n /** Expander geometry overrides. */\n expander?: Partial<JmThemeExpander>;\n}\n\n/**\n * The only theme built into this version.\n *\n * @remarks\n * Dark mode is a separate theme, not a light/dark variant pair of the same\n * theme, because a dark palette is not a mechanical inversion of a light one.\n *\n * @public\n */\nexport const JSMIND_THEME_DEFAULT: JmTheme = {\n background: '#ffffff',\n // Filled solids with white text, taken from v1 — a node carrying a tone\n // that only tints its background barely reads as \"this one is different\"\n // from across the canvas. The v1 palette names that map onto these tones\n // (belizehole, nephrite, pumpkin, pomegranate) are the same hue a few\n // degrees away, so they fold in rather than getting their own entry.\n tones: {\n default: { fillColor: '#ffffff', textColor: '#333333', borderColor: '#cccccc', lineColor: '#b0b0b0' },\n primary: { fillColor: '#428bca', textColor: '#ffffff', borderColor: '#357ebd', lineColor: '#689ece' },\n success: { fillColor: '#5cb85c', textColor: '#ffffff', borderColor: '#4cae4c', lineColor: '#79c279' },\n warning: { fillColor: '#f0ad4e', textColor: '#ffffff', borderColor: '#eea236', lineColor: '#f2b968' },\n danger: { fillColor: '#d9534f', textColor: '#ffffff', borderColor: '#d43f3a', lineColor: '#df6f6b' },\n info: { fillColor: '#5dc0de', textColor: '#ffffff', borderColor: '#46b8da', lineColor: '#74cae3' },\n accent: { fillColor: '#9b59b6', textColor: '#ffffff', borderColor: '#8e44ad', lineColor: '#aa73c2' },\n },\n node: {\n radius: 5,\n padding: 10,\n fontSize: 16,\n rootFontSize: 24,\n fontFamily: 'Verdana, Arial, Helvetica, sans-serif',\n lineHeight: 1.125,\n // Zero, because the stylesheet drew no border: the depth came from the\n // shadow below. Tone palettes still carry a borderColor for themes that\n // do want one.\n borderWidth: 0,\n maxWidth: 400,\n shadow: {\n normal: { offsetX: 1, offsetY: 1, blur: 1, color: '#666666' },\n hover: { offsetX: 2, offsetY: 2, blur: 8, color: '#000000' },\n selected: { offsetX: 2, offsetY: 2, blur: 8, color: '#000000' },\n },\n },\n line: {\n width: 2,\n pattern: JmLinePattern.Solid,\n curve: JmLineCurve.Bezier,\n },\n expander: {\n size: 13,\n radius: 6.5,\n fontSize: 8,\n lineHeight: 11,\n borderWidth: 1,\n },\n};\n\n/**\n * Built-in theme presets, keyed by name.\n *\n * @public\n */\nexport const JSMIND_THEME_PRESETS: Record<string, JmTheme> = {\n default: JSMIND_THEME_DEFAULT,\n};\n\n/**\n * Checks whether a value is a plain object that can be merged.\n *\n * @param value - The value to check.\n * @returns True for plain objects, false for arrays, null and primitives.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Deeply merges theme overrides onto a base theme.\n *\n * @remarks\n * A shallow merge is not enough. `tones: { primary: { fill: \"#f00\" } }` merged\n * shallowly would replace the whole `primary` entry, dropping `text`, `border`\n * and `line`, and the node would render black-on-black. Deep merge keeps the\n * fields the override did not mention.\n *\n * @param base - The theme to merge onto.\n * @param override - The partial theme to apply.\n * @returns A new merged theme; neither input is mutated.\n *\n * @public\n */\nexport function mergeJmTheme(base: JmTheme, override: JmStyle): JmTheme {\n const result: JmTheme = { ...base };\n\n // `theme` names the preset to inherit from and is consumed by\n // resolveJmStyle before this runs, so there is nothing to carry over here.\n if (override.background !== undefined) {\n result.background = override.background;\n }\n\n // node/line/expander each hold scalars, so they merge one level deep with\n // the same flat merge the options layer uses. Spread the base first:\n // mergeObjects replaces a missing default wholesale, which would drop\n // every field the override did not mention.\n if (override.node) {\n // `shadow` is decomposed first: it nests further than the rest\n // (state -> layer), and `mergeObjects` cannot express that in one call.\n const { shadow: shadowOverride, ...nodeRest } = override.node;\n const merged = mergeObjects(\n { ...base.node } as Partial<JmThemeNode>,\n nodeRest as Partial<JmThemeNode>\n );\n // A shallow merge would let an override that only restyles `hover`\n // replace the whole shadow block, dropping `normal` and `selected` and\n // leaving the node with no resting shadow at all.\n const baseShadow = base.node?.shadow;\n if (baseShadow && shadowOverride) {\n merged.shadow = mergeShadow(baseShadow, shadowOverride);\n }\n result.node = merged;\n }\n if (override.line) {\n result.line = mergeObjects({ ...base.line }, override.line);\n }\n if (override.expander) {\n result.expander = mergeObjects({ ...base.expander }, override.expander);\n }\n\n // `tones` is the one section nested two levels deep: tone -> palette. Each\n // palette must be merged field by field, or an override that names only\n // `fillColor` would drop textColor/borderColor/lineColor and the node\n // would render black on black.\n if (override.tones) {\n result.tones = mergeTonePalettes(base.tones, override.tones);\n }\n\n return result;\n}\n\n/**\n * Merges shadow overrides into a complete shadow.\n *\n * @remarks\n * Two levels deep: state, then layer. Each state the override does not mention\n * is passed through, and each layer is merged field by field so `hover.blur`\n * alone is a legal override.\n *\n * @param base - The complete shadow to merge onto.\n * @param override - The partial shadow to apply.\n * @returns A new complete shadow; neither input is mutated.\n *\n * @private\n */\nfunction mergeShadow(base: JmThemeShadow, override: JmThemeShadowOverride): JmThemeShadow {\n const result: JmThemeShadow = { ...base };\n\n for (const state of ['normal', 'hover', 'selected'] as const) {\n const layer = override[state];\n if (layer) {\n result[state] = mergeObjects({ ...base[state] }, layer);\n }\n }\n\n return result;\n}\n\n/**\n * Merges tone palette overrides into a set of palettes.\n *\n * @remarks\n * Per tone, the palette is merged field by field. Tones the override does not\n * mention are passed through untouched.\n *\n * @param base - The palettes to merge onto, possibly absent.\n * @param override - The per-tone overrides to apply.\n * @returns New palettes; neither input is mutated.\n *\n * @private\n */\nfunction mergeTonePalettes(\n base: Partial<Record<JmTone, Partial<JmTonePalette>>> | undefined,\n override: Partial<Record<JmTone, Partial<JmTonePalette>>>\n): Partial<Record<JmTone, Partial<JmTonePalette>>> {\n const tones: Partial<Record<JmTone, Partial<JmTonePalette>>> = { ...base };\n\n for (const key of Object.keys(override) as JmTone[]) {\n const overridePalette = override[key];\n if (!overridePalette) {\n continue;\n }\n tones[key] = mergeObjects(tones[key], overridePalette);\n }\n\n return tones;\n}\n\n/**\n * Resolves a style declaration into a complete theme.\n *\n * @remarks\n * `style.theme` picks the preset to inherit from (default `\"default\"`), then\n * every other field in `style` is merged on top of it, deeply.\n *\n * @param style - The style declaration, if the data carried one.\n * @returns A fully populated theme; never partial.\n * @throws {@link Error} If the named preset does not exist.\n *\n * @public\n */\nexport function resolveJmStyle(style?: JmStyle): JmTheme {\n if (style === undefined || style === null) {\n return { ...JSMIND_THEME_DEFAULT };\n }\n\n if (!isPlainObject(style)) {\n throw new Error('invalid style declaration');\n }\n\n const themeName = style.theme ?? 'default';\n if (typeof themeName !== 'string') {\n throw new Error('invalid theme name');\n }\n\n const preset = JSMIND_THEME_PRESETS[themeName];\n if (!preset) {\n throw new Error(`unknown theme: ${themeName}`);\n }\n\n return mergeJmTheme(preset, style);\n}\n","/**\n * Custom error class for jsMind operations.\n *\n * @public\n */\nexport class JsMindError extends Error {\n /** The data associated with the error. */\n data: Record<string, unknown>;\n\n /**\n * Stable machine-readable code, when the failure has one.\n *\n * @remarks\n * Callers branch on this rather than on `message`, which is written for\n * humans and may be reworded at any time.\n */\n code?: string;\n\n /**\n * Creates a new JsMindError instance.\n *\n * @param message - The error message.\n * @param data - Extra data carried with the error.\n * @param code - Stable machine-readable code, if any.\n */\n constructor(message: string, data: Record<string, unknown> = {}, code?: string) {\n super(message);\n this.data = data;\n if (code !== undefined) {\n this.code = code;\n }\n }\n}\n\n","/**\n * Represents a size with width and height.\n *\n * @public\n */\nexport class JmSize {\n /** The width value. */\n width: number;\n\n /** The height value. */\n height: number;\n\n /**\n * Creates a new size instance.\n *\n * @param width - The width value.\n * @param height - The height value.\n */\n constructor(width: number, height: number) {\n this.width = width;\n this.height = height;\n }\n}\n\nexport class JmPoint {\n x: number;\n\n y: number;\n\n constructor(x: number, y: number) {\n this.x = x;\n this.y = y;\n }\n\n offset(offset: JmPoint): JmPoint {\n return new JmPoint(this.x + offset.x, this.y + offset.y);\n }\n\n static readonly Zero: JmPoint = new JmPoint(0, 0);\n}\n\nexport class JmBounds {\n center: JmPoint;\n\n size: JmSize;\n\n constructor(center: JmPoint, size: JmSize) {\n this.center = center;\n this.size = size;\n }\n}\n","import type { JmElement } from '../../common/dom.ts';\nimport { JsMindError } from '../../common/error.ts';\nimport { JmPoint } from '../../common/index.ts';\nimport { JmSize } from '../../common/index.ts';\nimport type { JmNodeContent } from './node-content.ts';\nimport type { JmNodeStyle } from './style.ts';\n\n/**\n * Options for creating a new node.\n *\n * @public\n */\nexport interface NodeCreationOptions {\n /** Optional custom node ID. */\n nodeId?: string;\n /** Whether the node is folded (default: false). */\n folded?: boolean;\n /** Direction of the node (default: null). */\n side?: JmNodeSide;\n /** Additional data for the node (default: {}). */\n data?: Record<string, unknown>;\n /** Visual overrides for the node (default: none). */\n style?: JmNodeStyle;\n}\n\n/**\n * Options for specifying node destination.\n *\n * @public\n */\nexport interface NodeDestinationOptions {\n /** The ID of the target parent node (required). */\n parentId: string;\n /** The position index among siblings (if not provided, adds to end). */\n position?: number\n /** The direction of the node (if not provided, keeps current direction). */\n side?: JmNodeSide;\n}\n\n\nexport class JmNodeViewData {\n element: JmElement | null = null;\n\n expander: JmElement | null = null;\n\n leadingLine: SVGPathElement | null = null;\n}\n\nexport class JmNodeLayoutData {\n side: JmNodeSide = JmNodeSide.Center;\n\n visible: boolean = true;\n\n size: JmSize = new JmSize(0, 0);\n\n withDescendantsSize: JmSize = new JmSize(0, 0);\n\n offsetToParent: JmPoint = new JmPoint(0, 0);\n}\n\nclass NodeInternalData {\n view: JmNodeViewData = new JmNodeViewData();\n\n layout: JmNodeLayoutData = new JmNodeLayoutData();\n}\n/**\n * Node of mind map.\n *\n * @public\n */\nexport class JmNode {\n /** The unique identifier of the node. */\n id: string;\n\n /** The content of the node. */\n content: JmNodeContent;\n\n /** The parent node, or null if this is the root node. */\n parent: JmNode | null;\n\n /** Array of child nodes. */\n children: JmNode[];\n\n /** Whether the node is folded (collapsed). */\n folded: boolean;\n\n /** The direction of the node. */\n side: JmNodeSide;\n\n /** Additional data associated with the node. */\n data: Record<string, unknown>;\n\n /**\n * Visual overrides for this node.\n *\n * @remarks\n * Unset fields fall back to the theme. Storing only the difference keeps\n * theme changes propagating to every node that did not override anything.\n */\n style?: JmNodeStyle;\n\n /** View data associated with the node. */\n _data: NodeInternalData;\n\n /**\n * Creates a new node.\n *\n * @param id - The unique identifier of the node.\n * @param content - The content of the node.\n * @throws {@link JsMindError} If the node ID or content is invalid.\n */\n constructor(id: string, content: JmNodeContent) {\n if (!id) {\n throw new JsMindError('Invalid node id');\n }\n if (!content) {\n throw new JsMindError('Content is required');\n }\n\n this.id = id;\n this.content = content;\n this.parent = null;\n this.children = [];\n this.folded = false;\n this.side = JmNodeSide.SideA;\n this.data = {};\n this._data = new NodeInternalData();\n }\n\n /**\n * Lists all subnode IDs recursively.\n *\n * @returns Array of all subnode IDs including this node's children and their descendants.\n */\n getAllSubnodeIds(): string[] {\n const nodeIds: string[] = [];\n if(this.children.length > 0) {\n this.children.forEach((node)=>{\n nodeIds.push(node.id);\n nodeIds.push(...node.getAllSubnodeIds());\n });\n }\n return nodeIds;\n }\n\n /**\n * Compares this node with another node.\n *\n * @param other - The other node to compare with.\n * @returns True if they are equal, false otherwise.\n */\n equals(other: JmNode): boolean {\n return this.id === other.id\n && this.content.type === other.content.type\n && this.content.value === other.content.value\n && this.folded === other.folded\n && this.side === other.side\n && ((this.parent === null && other.parent === null) || (this.parent!.id === other.parent!.id))\n && this.children.length === other.children.length\n && this.children.every((child, idx, _)=>{ return child.id === other.children[idx].id; });\n }\n\n /**\n * Checks if this node is a descendant of another node.\n *\n * @param potentialAncestor - The potential ancestor node.\n * @returns True if this node is a descendant of potentialAncestor.\n */\n isDescendant(potentialAncestor: JmNode): boolean {\n if (!potentialAncestor || !potentialAncestor.children) {\n return false;\n }\n\n for (const child of potentialAncestor.children) {\n if (child.id === this.id) {\n return true;\n }\n if (this.isDescendant(child)) {\n return true;\n }\n }\n return false;\n }\n\n isRoot(): boolean {\n return this.parent === null;\n }\n}\n\n/**\n * Enumeration for directions of node.\n *\n * @public\n */\nexport const JmNodeSide = {\n /** Left direction. */\n SideB: -1,\n /** Center direction. */\n Center: 0,\n /** Right direction. */\n SideA: 1,\n} as const;\n\nexport type JmNodeSide = typeof JmNodeSide[keyof typeof JmNodeSide];\n","import { JsMindError } from '../../common/error.ts';\nimport type { JmLineStyle } from './style.ts';\n\n/**\n * Options for creating a new edge.\n *\n * @public\n */\nexport interface EdgeCreationOptions {\n /** Optional edge ID, will be generated if not provided. */\n edgeId?: string;\n /** Optional label for the edge. */\n label?: string;\n /** Optional visual style for the edge line. */\n style?: JmLineStyle;\n}\n\n/**\n * Edge of mind map.\n *\n * @remarks\n * Edges represent additional relationships between nodes (not parent-child relationships).\n *\n * @public\n */\nexport class JmEdge {\n /** The unique identifier of the edge. */\n id: string;\n\n /** The ID of the source node. */\n sourceNodeId: string;\n\n /** The ID of the target node. */\n targetNodeId: string;\n\n /** The type of the edge. */\n type: JmEdgeType;\n\n /** The optional label of the edge. */\n label: string | null;\n\n /**\n * Visual style of the edge line.\n *\n * @remarks\n * Uses the same `JmLineStyle` as `JmNodeStyle.incoming` so that\n * hierarchical and additional relationships share one vocabulary.\n */\n style?: JmLineStyle;\n\n /**\n * Creates a new edge.\n *\n * @param id - The unique identifier of the edge.\n * @param sourceNodeId - The ID of the source node.\n * @param targetNodeId - The ID of the target node.\n * @param type - The type of the edge.\n * @param label - Optional label for the edge.\n * @throws {@link JsMindError} If any of the required parameters are invalid.\n */\n constructor(id: string, sourceNodeId: string, targetNodeId: string, type: JmEdgeType, label: string | null = null) {\n if (!id) {\n throw new JsMindError('invalid edge id');\n }\n if (!sourceNodeId) {\n throw new JsMindError('invalid source node id');\n }\n if (!targetNodeId) {\n throw new JsMindError('invalid target node');\n }\n if (!type) {\n throw new JsMindError('invalid edge type');\n }\n this.id = id;\n this.sourceNodeId = sourceNodeId;\n this.targetNodeId = targetNodeId;\n this.type = type;\n this.label = label;\n }\n}\n\n/**\n * Type of edge - only for additional relationships (not parent-child).\n *\n * @public\n */\nexport const JmEdgeType = {\n /** Link edge type. */\n Link: 'link',\n} as const;\n\nexport type JmEdgeType = typeof JmEdgeType[keyof typeof JmEdgeType];\n\n","/**\n * Content types and utilities for JsMind nodes.\n *\n * @packageDocumentation\n */\n\n/**\n * Enumeration for content types of node.\n *\n * @public\n */\nexport const JmNodeContentType = {\n /** Text content type. */\n Text: 'text',\n} as const;\n\nexport type JmNodeContentType = typeof JmNodeContentType[keyof typeof JmNodeContentType];\n\n/**\n * Content of mind map node.\n *\n * @public\n */\nexport class JmNodeContent {\n /** The type of the content. */\n type: JmNodeContentType;\n\n /** The actual content value. */\n value: unknown;\n\n /**\n * Creates a content object.\n *\n * @param type - The type of content.\n * @param value - The actual content value.\n * @throws {@link Error} If the content type is invalid.\n */\n constructor(type: JmNodeContentType, value: unknown) {\n if (!type || !Object.values(JmNodeContentType).includes(type)) {\n throw new Error(`Invalid content type: ${type}`);\n }\n this.type = type;\n this.value = value;\n }\n\n /**\n * Checks if content is of specific type.\n *\n * @param type - The type to check.\n * @returns True if content is of the specified type.\n */\n hasType(type: JmNodeContentType): boolean {\n return this.type === type;\n }\n\n /**\n * Checks if content is text type.\n *\n * @returns True if content is text type.\n */\n isText(): boolean {\n return this.hasType(JmNodeContentType.Text);\n }\n\n getText(): string {\n if (!this.isText()) {\n throw new Error('Content is not text type');\n }\n return this.value as string;\n }\n\n /**\n * Creates a text content object.\n *\n * @param text - The text content.\n * @returns The content object.\n */\n static createText(text: string): JmNodeContent {\n return new JmNodeContent(JmNodeContentType.Text, text);\n }\n\n /**\n * Creates a content object from an object with type and value.\n *\n * @param obj - The object to create content from.\n * @returns The content object.\n */\n static fromObject(obj: { type: JmNodeContentType, value: unknown }): JmNodeContent {\n return new JmNodeContent(obj.type, obj.value);\n }\n}\n\n","/**\n * Validation for v2 mind map data.\n *\n * @remarks\n * Every check returns a coded issue instead of throwing. A caller (the CLI, a\n * host application, an agent) branches on `code`; the `message` is for humans\n * to read and must never be parsed.\n *\n * @packageDocumentation\n */\n\nimport { JmTone } from '../model/data/style.ts';\nimport { JSMIND_THEME_PRESETS } from '../model/data/style.ts';\nimport { JmLinePattern } from '../model/data/style.ts';\nimport { JmNodeSide } from '../model/data/node.ts';\nimport { JmEdgeType } from '../model/data/edge.ts';\nimport { JmNodeContentType } from '../model/data/node-content.ts';\n\n/**\n * Error codes for v2 data validation.\n *\n * @remarks\n * Codes are stable identifiers. Messages may be reworded at any time; these\n * may not.\n *\n * @public\n */\nexport const JmValidationCode = {\n /** Top-level `format` missing or not \"jsmind_v2\". */\n Format: 'E_FORMAT',\n /** `meta` missing or its fields are not strings. */\n Meta: 'E_META',\n /** The top-level `nodes` object is absent or not an object. */\n NodesMissing: 'E_NODES_MISSING',\n /** The top-level `edges` object is absent or not an object. */\n EdgesMissing: 'E_EDGES_MISSING',\n /** `root` does not point at an existing node. */\n RootMissing: 'E_ROOT_MISSING',\n /** A `nodes` key differs from the `id` of its value. */\n NodeKeyMismatch: 'E_NODE_KEY_MISMATCH',\n /** An `edges` key differs from the `id` of its value. */\n EdgeKeyMismatch: 'E_EDGE_KEY_MISMATCH',\n /** A node's `parent` points at a node that is not present. */\n NodeParentMissing: 'E_NODE_PARENT_MISSING',\n /** A node's `children` lists an id that is not present. */\n NodeChildMissing: 'E_NODE_CHILD_MISSING',\n /** An edge endpoint points at a node that is not present. */\n EdgeNodeMissing: 'E_EDGE_NODE_MISSING',\n /** More than one node has `parent === null`. */\n MultipleRoots: 'E_MULTIPLE_ROOTS',\n /** The root node has a non-null `parent`. */\n RootParentSet: 'E_ROOT_PARENT_SET',\n /** A non-root node uses `side: 0`, which belongs to the root alone. */\n NonRootSideCenter: 'E_NON_ROOT_SIDE_CENTER',\n /** `parent.children` and `child.parent` disagree. */\n ParentChildMismatch: 'E_PARENT_CHILD_MISMATCH',\n /** Following `parent` links returns to where it started. */\n Cycle: 'E_CYCLE',\n /** `content.type` is not a known content type. */\n ContentType: 'E_CONTENT_TYPE',\n /** `edge.type` is not a known edge type. */\n EdgeType: 'E_EDGE_TYPE',\n /** `side` is not a known side value. */\n Side: 'E_SIDE',\n /** `style.tone` is not one of the known tones. */\n Tone: 'E_TONE',\n /** A line pattern is not solid/dashed/dotted. */\n LineStyle: 'E_LINE_STYLE',\n /** A numeric style value is out of range. */\n StyleRange: 'E_STYLE_RANGE',\n /** `style.theme` names a preset that does not exist. */\n ThemeUnknown: 'E_THEME_UNKNOWN',\n} as const;\n\nexport type JmValidationCode = typeof JmValidationCode[keyof typeof JmValidationCode];\n\n/**\n * One validation problem.\n *\n * @public\n */\nexport interface JmValidationIssue {\n /** Stable machine-readable code. Branch on this. */\n code: JmValidationCode;\n /** Location within the document, e.g. `nodes/jm-c1/style/tone`. */\n path: string;\n /** Human-readable description. Never parse this. */\n message: string;\n}\n\n/**\n * Outcome of a validation pass.\n *\n * @public\n */\nexport interface JmValidationResult {\n /** True when `errors` is empty. */\n valid: boolean;\n /** Every problem found, in document order. */\n errors: JmValidationIssue[];\n}\n\n/** Edge types accepted for `edge.type`. */\nconst EDGE_TYPES: ReadonlySet<string> = new Set(Object.values(JmEdgeType));\n\n/** Numeric side values accepted for a node. */\nconst SIDE_VALUES: ReadonlySet<number> = new Set(Object.values(JmNodeSide));\n\n/** Line patterns accepted for `borderStyle` and `incoming.pattern`. */\nconst LINE_PATTERNS: ReadonlySet<string> = new Set(Object.values(JmLinePattern));\n\n/** Tones accepted for `style.tone`. */\nconst TONES: ReadonlySet<string> = new Set(Object.values(JmTone));\n\n/** Content types accepted for `content.type`. */\nconst CONTENT_TYPES: ReadonlySet<string> = new Set(Object.values(JmNodeContentType));\n\n/**\n * Narrows to a plain object.\n *\n * @param value - Value to test.\n * @returns True for non-null, non-array objects.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reads a string field, or null when absent or not a string.\n *\n * @param holder - Object to read from.\n * @param key - Field name.\n * @returns The string, or null.\n */\nfunction str(holder: Record<string, unknown>, key: string): string | null {\n const value = holder[key];\n return typeof value === 'string' ? value : null;\n}\n\n/**\n * Validates v2 data against every rule in the format specification.\n *\n * @remarks\n * Never throws for malformed input: anything structurally wrong becomes an\n * issue with a code. The one thing it cannot represent is a non-object root,\n * which it reports as `E_FORMAT` since nothing can be read from it.\n *\n * @param data - Candidate data, typically parsed JSON.\n * @returns Every issue found; `valid` is true only when the list is empty.\n *\n * @public\n */\nexport function validateMindData(data: unknown): JmValidationResult {\n const errors: JmValidationIssue[] = [];\n\n if (!isRecord(data)) {\n errors.push({\n code: JmValidationCode.Format,\n path: '',\n message: 'Data is not an object.',\n });\n return { valid: false, errors };\n }\n\n // ---- format ----\n if (data.format !== 'jsmind_v2') {\n errors.push({\n code: JmValidationCode.Format,\n path: 'format',\n message: `Expected format \"jsmind_v2\", got ${JSON.stringify(data.format) ?? 'nothing'}.`,\n });\n }\n\n // ---- meta ----\n const meta = data.meta;\n if (!isRecord(meta)) {\n errors.push({\n code: JmValidationCode.Meta,\n path: 'meta',\n message: 'Missing \"meta\" object.',\n });\n } else {\n for (const key of ['name', 'author', 'version'] as const) {\n if (typeof meta[key] !== 'string') {\n errors.push({\n code: JmValidationCode.Meta,\n path: `meta/${key}`,\n message: `\"meta.${key}\" must be a string.`,\n });\n }\n }\n }\n\n // ---- nodes / edges containers ----\n const nodes = data.nodes;\n const edges = data.edges;\n\n // Both container checks run before the early return: a document missing both\n // should learn about both, not just whichever is checked first.\n if (!isRecord(nodes)) {\n errors.push({\n code: JmValidationCode.NodesMissing,\n path: 'nodes',\n message: 'Missing \"nodes\" object.',\n });\n }\n if (!isRecord(edges)) {\n errors.push({\n code: JmValidationCode.EdgesMissing,\n path: 'edges',\n message: 'Missing \"edges\" object.',\n });\n }\n if (!isRecord(nodes)) {\n // Without nodes there is not a single reference in the document that can\n // be resolved, so every later rule would only repeat itself.\n return { valid: false, errors };\n }\n\n const nodeIds = new Set(Object.keys(nodes));\n\n // ---- root ----\n const rootId = str(data, 'root');\n if (!rootId) {\n errors.push({\n code: JmValidationCode.RootMissing,\n path: 'root',\n message: '\"root\" must be a non-empty string.',\n });\n } else if (!nodeIds.has(rootId)) {\n errors.push({\n code: JmValidationCode.RootMissing,\n path: 'root',\n message: `\"root\" points at \"${rootId}\", which is not in \"nodes\".`,\n });\n }\n\n // ---- node keys ----\n for (const [key, node] of Object.entries(nodes)) {\n if (!isRecord(node)) {\n errors.push({\n code: JmValidationCode.NodeKeyMismatch,\n path: `nodes/${key}`,\n message: `Node under key \"${key}\" is not an object.`,\n });\n continue;\n }\n if (node.id !== key) {\n errors.push({\n code: JmValidationCode.NodeKeyMismatch,\n path: `nodes/${key}`,\n message: `Key \"${key}\" does not match the node's own id ${JSON.stringify(node.id)}.`,\n });\n }\n }\n\n // ---- edge keys ----\n if (isRecord(edges)) {\n for (const [key, edge] of Object.entries(edges)) {\n if (!isRecord(edge)) {\n errors.push({\n code: JmValidationCode.EdgeKeyMismatch,\n path: `edges/${key}`,\n message: `Edge under key \"${key}\" is not an object.`,\n });\n continue;\n }\n if (edge.id !== key) {\n errors.push({\n code: JmValidationCode.EdgeKeyMismatch,\n path: `edges/${key}`,\n message: `Key \"${key}\" does not match the edge's own id ${JSON.stringify(edge.id)}.`,\n });\n }\n }\n }\n\n // ---- per-node checks ----\n const parentOf = new Map<string, string | null>();\n\n for (const [key, node] of Object.entries(nodes)) {\n if (!isRecord(node)) {\n continue;\n }\n const at = `nodes/${key}`;\n\n // content\n const content = node.content;\n if (!isRecord(content)) {\n errors.push({\n code: JmValidationCode.ContentType,\n path: `${at}/content`,\n message: 'Missing \"content\" object.',\n });\n } else {\n const type = content.type;\n if (typeof type !== 'string' || !CONTENT_TYPES.has(type)) {\n errors.push({\n code: JmValidationCode.ContentType,\n path: `${at}/content/type`,\n message: `Unknown content type ${JSON.stringify(type)}. Expected one of ${[...CONTENT_TYPES].join(', ')}.`,\n });\n }\n }\n\n // parent reference\n const parent = node.parent;\n if (parent === null) {\n parentOf.set(key, null);\n } else if (typeof parent === 'string') {\n parentOf.set(key, parent);\n if (!nodeIds.has(parent)) {\n errors.push({\n code: JmValidationCode.NodeParentMissing,\n path: `${at}/parent`,\n message: `Parent \"${parent}\" is not in \"nodes\".`,\n });\n }\n } else {\n errors.push({\n code: JmValidationCode.NodeParentMissing,\n path: `${at}/parent`,\n message: '\"parent\" must be a node id or null.',\n });\n // Deliberately NOT recorded as null. A malformed parent is\n // undetermined, not root-like: recording it as null makes the root\n // count below report an extra E_MULTIPLE_ROOTS for the same broken\n // field, which is a false positive on a different code.\n }\n\n // children references\n const children = node.children;\n if (!Array.isArray(children)) {\n errors.push({\n code: JmValidationCode.NodeChildMissing,\n path: `${at}/children`,\n message: '\"children\" must be an array.',\n });\n } else {\n for (const childId of children) {\n if (typeof childId !== 'string' || !nodeIds.has(childId)) {\n errors.push({\n code: JmValidationCode.NodeChildMissing,\n path: `${at}/children`,\n message: `Child ${JSON.stringify(childId)} is not in \"nodes\".`,\n });\n }\n }\n }\n\n // side is a number in the JSON, per the format spec: -1 left, 0 centre,\n // 1 right. No name conversion happens at this layer.\n const side = node.side;\n if (typeof side !== 'number' || !SIDE_VALUES.has(side)) {\n errors.push({\n code: JmValidationCode.Side,\n path: `${at}/side`,\n message: `\"side\" must be -1, 0 or 1, got ${JSON.stringify(side)}.`,\n });\n } else if (side === JmNodeSide.Center && parent !== null) {\n // Centre is not a position, it is the absence of one: it tells the\n // layout to place the node relative to the root, which only the root\n // itself can do. A child carrying it is laid out nowhere and does\n // not paint at all - the data validates, the node silently vanishes\n // from the picture, and nothing downstream says why.\n errors.push({\n code: JmValidationCode.NonRootSideCenter,\n path: `${at}/side`,\n message: 'Only the root may use side 0 (centre); a child must be -1 (left) or 1 (right).',\n });\n }\n\n // per-node style\n validateNodeStyle(node.style, `${at}/style`, errors);\n }\n\n // ---- parent/children agreement ----\n for (const [key, node] of Object.entries(nodes)) {\n if (!isRecord(node) || !Array.isArray(node.children)) {\n continue;\n }\n for (const childId of node.children) {\n if (typeof childId !== 'string') {\n continue;\n }\n const child = nodes[childId];\n if (!isRecord(child)) {\n continue;\n }\n if (child.parent !== key) {\n errors.push({\n code: JmValidationCode.ParentChildMismatch,\n path: `nodes/${childId}/parent`,\n message: `Listed as a child of \"${key}\", but its parent is ${JSON.stringify(child.parent)}.`,\n });\n }\n }\n }\n\n // ---- exactly one root ----\n // Nodes with a malformed parent are absent from parentOf entirely, so a\n // broken field cannot masquerade as a second root.\n const roots = [...parentOf.entries()].filter(([, parent]) => parent === null).map(([id]) => id);\n if (roots.length > 1) {\n errors.push({\n code: JmValidationCode.MultipleRoots,\n path: 'nodes',\n message: `${roots.length} nodes have a null parent: ${roots.join(', ')}. Exactly one is allowed.`,\n });\n }\n if (rootId && parentOf.has(rootId) && parentOf.get(rootId) !== null) {\n errors.push({\n code: JmValidationCode.RootParentSet,\n path: `nodes/${rootId}/parent`,\n message: 'The root node must have a null parent.',\n });\n }\n\n // ---- cycles ----\n // A node whose parent chain runs INTO a cycle but does not belong to one\n // must not be blamed: walking up from D (D -> A -> B -> C -> A) does revisit\n // a node, but it is A, not D. Report the cycle's own members instead.\n const reportedCycles = new Set<string>();\n\n for (const startId of nodeIds) {\n const cycle = findParentCycle(startId, parentOf);\n if (cycle === null) {\n continue;\n }\n\n // Same cycle reached from different entry points yields the same member\n // set; sort it so one cycle is reported exactly once, and pick a stable\n // node to hang the issue on.\n const members = [...cycle].sort();\n const key = members.join(',');\n if (reportedCycles.has(key)) {\n continue;\n }\n reportedCycles.add(key);\n\n errors.push({\n code: JmValidationCode.Cycle,\n path: `nodes/${members[0]}`,\n message: `Following \"parent\" from this node returns to it (cycle: ${members.join(' -> ')} -> ${members[0]}).`,\n });\n }\n\n // ---- edges ----\n if (isRecord(edges)) {\n for (const [key, edge] of Object.entries(edges)) {\n if (!isRecord(edge)) {\n continue;\n }\n const at = `edges/${key}`;\n const edgeType = edge.type;\n if (typeof edgeType !== 'string' || !EDGE_TYPES.has(edgeType)) {\n errors.push({\n code: JmValidationCode.EdgeType,\n path: `${at}/type`,\n message: `Unknown edge type ${JSON.stringify(edgeType)}. Expected one of ${[...EDGE_TYPES].join(', ')}.`,\n });\n }\n\n for (const field of ['sourceNodeId', 'targetNodeId'] as const) {\n const endpoint = edge[field];\n if (typeof endpoint !== 'string' || !nodeIds.has(endpoint)) {\n errors.push({\n code: JmValidationCode.EdgeNodeMissing,\n path: `${at}/${field}`,\n message: `Edge endpoint ${JSON.stringify(endpoint)} is not in \"nodes\".`,\n });\n }\n }\n validateLineStyle(edge.style, `${at}/style`, errors);\n }\n }\n\n // ---- mind map style ----\n validateMindStyle(data.style, errors);\n\n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Walks parent links from a node and returns the members of the cycle it hits.\n *\n * @remarks\n * Returns the cycle itself, not the starting node. Walking up from a node that\n * merely points *into* a cycle passes through that cycle without belonging to\n * it — the caller needs the members to blame the right nodes and to recognise\n * the same cycle reached from different starting points.\n *\n * @param startId - Node to start from.\n * @param parentOf - Parent map built during the walk.\n * @returns Member ids of the cycle, in traversal order; null when the chain\n * ends without looping.\n */\nfunction findParentCycle(\n startId: string,\n parentOf: Map<string, string | null>\n): string[] | null {\n const path: string[] = [];\n const indexOf = new Map<string, number>();\n let cursor: string | null | undefined = startId;\n\n while (cursor !== null && cursor !== undefined) {\n const seenAt = indexOf.get(cursor);\n if (seenAt !== undefined) {\n // Everything from the first sighting onwards is the cycle; what came\n // before it is the tail that led in and is not part of it.\n return path.slice(seenAt);\n }\n indexOf.set(cursor, path.length);\n path.push(cursor);\n cursor = parentOf.get(cursor);\n }\n\n return null;\n}\n\n/**\n * Validates the per-node style block.\n *\n * @param style - Candidate style value.\n * @param at - Path prefix for messages.\n * @param errors - Collector.\n */\nfunction validateNodeStyle(style: unknown, at: string, errors: JmValidationIssue[]): void {\n if (style === undefined) {\n return;\n }\n if (!isRecord(style)) {\n errors.push({\n code: JmValidationCode.StyleRange,\n path: at,\n message: '\"style\" must be an object.',\n });\n return;\n }\n\n const tone = style.tone;\n if (tone !== undefined && (typeof tone !== 'string' || !TONES.has(tone))) {\n errors.push({\n code: JmValidationCode.Tone,\n path: `${at}/tone`,\n message: `Unknown tone ${JSON.stringify(tone)}. Expected one of ${[...TONES].join(', ')}.`,\n });\n }\n\n const borderPattern = style.borderStyle;\n if (borderPattern !== undefined) {\n if (typeof borderPattern !== 'string' || !LINE_PATTERNS.has(borderPattern)) {\n errors.push({\n code: JmValidationCode.LineStyle,\n path: `${at}/borderStyle`,\n message: `Unknown line pattern ${JSON.stringify(borderPattern)}. Expected one of ${[...LINE_PATTERNS].join(', ')}.`,\n });\n }\n }\n\n for (const field of ['borderWidth', 'fontSize'] as const) {\n const value = style[field];\n if (value !== undefined && (typeof value !== 'number' || !(value > 0))) {\n errors.push({\n code: JmValidationCode.StyleRange,\n path: `${at}/${field}`,\n message: `\"${field}\" must be a positive number, got ${JSON.stringify(value)}.`,\n });\n }\n }\n\n if (style.incoming !== undefined) {\n validateLineStyle(style.incoming, `${at}/incoming`, errors);\n }\n}\n\n/**\n * Validates a line style block, shared by node `incoming` and edge `style`.\n *\n * @param style - Candidate line style.\n * @param at - Path prefix for messages.\n * @param errors - Collector.\n */\nfunction validateLineStyle(style: unknown, at: string, errors: JmValidationIssue[]): void {\n if (style === undefined) {\n return;\n }\n if (!isRecord(style)) {\n errors.push({\n code: JmValidationCode.LineStyle,\n path: at,\n message: 'Line style must be an object.',\n });\n return;\n }\n\n if (style.pattern !== undefined) {\n const pattern = style.pattern;\n if (typeof pattern !== 'string' || !LINE_PATTERNS.has(pattern)) {\n errors.push({\n code: JmValidationCode.LineStyle,\n path: `${at}/pattern`,\n message: `Unknown line pattern ${JSON.stringify(pattern)}. Expected one of ${[...LINE_PATTERNS].join(', ')}.`,\n });\n }\n }\n\n const width = style.width;\n if (width !== undefined && (typeof width !== 'number' || !(width > 0))) {\n errors.push({\n code: JmValidationCode.StyleRange,\n path: `${at}/width`,\n message: `\"width\" must be a positive number, got ${JSON.stringify(width)}.`,\n });\n }\n}\n\n/**\n * Validates the mind map level style declaration.\n *\n * @param style - Candidate style declaration.\n * @param errors - Collector.\n */\nfunction validateMindStyle(style: unknown, errors: JmValidationIssue[]): void {\n if (style === undefined) {\n return;\n }\n if (!isRecord(style)) {\n errors.push({\n code: JmValidationCode.StyleRange,\n path: 'style',\n message: '\"style\" must be an object.',\n });\n return;\n }\n\n const themeName = style.theme;\n if (themeName !== undefined) {\n if (typeof themeName !== 'string') {\n errors.push({\n code: JmValidationCode.ThemeUnknown,\n path: 'style/theme',\n message: '\"style.theme\" must be a string.',\n });\n } else if (!(themeName in JSMIND_THEME_PRESETS)) {\n errors.push({\n code: JmValidationCode.ThemeUnknown,\n path: 'style/theme',\n message: `Unknown theme ${JSON.stringify(themeName)}. Known themes: ${Object.keys(JSMIND_THEME_PRESETS).join(', ')}.`,\n });\n }\n }\n\n if (style.tones !== undefined) {\n if (!isRecord(style.tones)) {\n errors.push({\n code: JmValidationCode.StyleRange,\n path: 'style/tones',\n message: '\"style.tones\" must be an object.',\n });\n } else {\n for (const toneName of Object.keys(style.tones)) {\n if (!TONES.has(toneName)) {\n errors.push({\n code: JmValidationCode.Tone,\n path: `style/tones/${toneName}`,\n message: `Unknown tone ${JSON.stringify(toneName)}.`,\n });\n }\n }\n }\n }\n\n for (const section of ['node', 'line', 'expander'] as const) {\n if (style[section] === undefined) {\n continue;\n }\n if (!isRecord(style[section])) {\n errors.push({\n code: JmValidationCode.StyleRange,\n path: `style/${section}`,\n message: `\"style.${section}\" must be an object.`,\n });\n }\n }\n}\n","/**\n * @fileoverview A headless browser, driven over the DevTools protocol.\n *\n * Exporting an image needs a rendering engine: the picture is produced by\n * handing markup back to the browser, so there has to be one. That is the only\n * external requirement the CLI has, and it is confined to this file.\n *\n * Talking CDP directly keeps the package dependency-free - no puppeteer, no\n * playwright. Node's built-in WebSocket and fetch are enough.\n *\n * @packageDocumentation\n *\n * Excluded from the unit coverage figure (see `test:coverage` in package.json).\n * This file is a driver: spawn a process, speak a protocol over a socket, wait\n * for replies. Testing it without a browser would mean mocking `spawn`, the\n * DevTools socket and the file system - which asserts that the mocks were\n * called, not that a browser produces an image. The UI suite runs the real\n * thing against the built bundle; that bundle is why the coverage tool cannot\n * attribute the lines back here.\n */\n\nimport { spawn, spawnSync } from 'node:child_process';\nimport { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { fileURLToPath } from 'node:url';\n\nimport { CliExit, CliError } from './exit.ts';\n\n/** Where a Chromium binary is normally installed. */\nconst BROWSER_CANDIDATES = [\n process.env.CHROME_PATH,\n process.env.CHROMIUM_PATH,\n '/usr/bin/chromium',\n '/usr/bin/chromium-browser',\n '/usr/bin/google-chrome',\n '/usr/bin/google-chrome-stable',\n '/snap/bin/chromium',\n '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',\n '/Applications/Chromium.app/Contents/MacOS/Chromium',\n];\n\n/** A CDP session on a blank page, with the jsMind bundle already loaded. */\nexport interface JmBrowserSession {\n /**\n * Evaluates a function body in the page and returns its value.\n *\n * @param expression - JavaScript to run; may return a promise.\n * @returns Whatever the expression resolves to, by value.\n */\n evaluate: (expression: string) => Promise<unknown>;\n /** Closes the browser and removes the temporary profile. */\n close: () => Promise<void>;\n}\n\n/** Locates a Chromium binary, or explains what to install. */\nfunction findBrowser(): string {\n for (const candidate of BROWSER_CANDIDATES) {\n if (candidate && existsSync(candidate)) {\n return candidate;\n }\n }\n // `which` last: PATH may point somewhere the fixed list does not cover.\n for (const name of ['chromium', 'chromium-browser', 'google-chrome', 'google-chrome-stable']) {\n const found = whichSync(name);\n if (found) {\n return found;\n }\n }\n throw new CliError(\n 'No Chromium found. Image export needs a browser: install chromium, ' +\n 'or point CHROME_PATH at a Chrome or Chromium binary.',\n CliExit.IoError\n );\n}\n\n/** Blocking `which`, without pulling in a dependency for it. */\nfunction whichSync(name: string): string | null {\n const result = spawnSync('which', [name], { encoding: 'utf8' });\n if (result.status !== 0) {\n return null;\n }\n const path = (result.stdout ?? '').trim();\n return path.length > 0 ? path : null;\n}\n\n/** Resolves the bundled jsMind build the page should load. */\nexport function resolveBundlePath(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n // Running from dist/ puts the bundle beside this file; running from src/cli/\n // puts it two levels up. Both are normal during development.\n const candidates = [\n resolve(here, 'jsmind.js'),\n resolve(here, '../../dist/jsmind.js'),\n ];\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n throw new CliError(\n `Cannot find the jsMind bundle (looked in ${candidates.join(', ')}). Run a build first.`,\n CliExit.IoError\n );\n}\n\n/** A CDP message carrying a result or an error. */\ninterface CdpMessage {\n id?: number;\n result?: Record<string, unknown>;\n error?: { message?: string };\n}\n\n/** Thrown internally when the page itself raises. */\nclass PageError extends Error {}\n\n/**\n * Expression that imports the ESM bundle.\n *\n * The bundle is an ES module (`export`, plus a `globalThis.jsMind` assignment).\n * Evaluating that source as a classic script is a syntax error, which is how\n * the CLI used to load the old UMD build. A blob URL is a module.\n *\n * @param source - Contents of `dist/jsmind.js`.\n * @returns An async expression for `Runtime.evaluate`.\n */\nfunction bundleImportExpression(source: string): string {\n return `(async () => {\n const url = URL.createObjectURL(new Blob([${JSON.stringify(source)}], { type: 'text/javascript' }));\n try {\n await import(url);\n } finally {\n URL.revokeObjectURL(url);\n }\n })()`;\n}\n\n/**\n * Starts a headless browser with jsMind loaded on a blank page.\n *\n * @param width - CSS width of the viewport.\n * @param height - CSS height of the viewport.\n * @returns A session that can evaluate expressions and must be closed.\n * @throws {@link CliError} If no browser is found or it fails to start.\n */\nexport async function openBrowser(width: number, height: number): Promise<JmBrowserSession> {\n const binary = findBrowser();\n const bundle = readFileSync(resolveBundlePath(), 'utf8');\n const port = 9222 + Math.floor(Math.random() * 2000);\n const profile = mkdtempSync(join(tmpdir(), 'jsmind-cli-'));\n\n const chrome = spawn(\n binary,\n [\n '--headless=new',\n `--remote-debugging-port=${port}`,\n `--user-data-dir=${profile}`,\n '--no-sandbox',\n '--disable-gpu',\n '--disable-dev-shm-usage',\n // Without this the scrollbars land in the picture.\n '--hide-scrollbars',\n 'about:blank',\n ],\n { stdio: ['ignore', 'ignore', 'pipe'] }\n );\n\n let exited: number | null = null;\n chrome.on('exit', code => {\n exited = code ?? -1;\n });\n\n let socket: WebSocket | null = null;\n const cleanup = async (): Promise<void> => {\n socket?.close();\n if (exited === null) {\n chrome.kill('SIGKILL');\n await new Promise(done => setTimeout(done, 200));\n }\n try {\n rmSync(profile, { recursive: true, force: true });\n } catch {\n // The profile is temporary; failing to remove it is not worth a word.\n }\n };\n\n try {\n const version = await waitForDevTools(port, () => exited);\n socket = new WebSocket(version.webSocketDebuggerUrl);\n await new Promise<void>((ok, fail) => {\n socket!.onopen = () => ok();\n socket!.onerror = () => fail(new CliError('Cannot connect to the browser.', CliExit.IoError));\n });\n\n let nextId = 0;\n let sessionId = '';\n const pending = new Map<number, (message: CdpMessage) => void>();\n socket.onmessage = event => {\n const message = JSON.parse(String(event.data)) as CdpMessage;\n if (message.id !== undefined) {\n const settle = pending.get(message.id);\n if (settle) {\n pending.delete(message.id);\n settle(message);\n }\n }\n };\n\n const send = (method: string, params: Record<string, unknown> = {}): Promise<CdpMessage> =>\n new Promise(done => {\n const id = ++nextId;\n pending.set(id, done);\n socket!.send(\n JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })\n );\n });\n\n const target = await send('Target.createTarget', { url: 'about:blank' });\n const attached = await send('Target.attachToTarget', {\n targetId: target.result!.targetId,\n flatten: true,\n });\n sessionId = attached.result!.sessionId as string;\n\n await send('Page.enable');\n await send('Runtime.enable');\n await send('Emulation.setDeviceMetricsOverride', {\n width,\n height,\n deviceScaleFactor: 1,\n mobile: false,\n });\n\n const frameTree = await send('Page.getFrameTree');\n const frameId = (frameTree.result!.frameTree as { frame: { id: string } }).frame.id;\n await send('Page.setDocumentContent', {\n frameId,\n html:\n '<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>' +\n 'html,body{margin:0;padding:0;background:#ffffff}' +\n `#stage{width:${width}px;height:${height}px}` +\n '</style></head><body><div id=\"stage\"></div></body></html>',\n });\n const loaded = await send('Runtime.evaluate', {\n expression: bundleImportExpression(bundle),\n awaitPromise: true,\n });\n const loadError = loaded.result?.exceptionDetails as\n | { exception?: { description?: string }; text?: string }\n | undefined;\n if (loadError) {\n throw new CliError(\n loadError.exception?.description ?? loadError.text ?? 'Could not load the jsMind bundle.',\n CliExit.IoError\n );\n }\n\n const evaluate = async (expression: string): Promise<unknown> => {\n const message = await send('Runtime.evaluate', {\n expression,\n returnByValue: true,\n awaitPromise: true,\n });\n const details = message.result?.exceptionDetails as\n | { exception?: { description?: string }; text?: string }\n | undefined;\n if (details) {\n throw new PageError(\n details.exception?.description ?? details.text ?? 'the page raised an error'\n );\n }\n const result = message.result?.result as { value?: unknown } | undefined;\n return result?.value;\n };\n\n return { evaluate, close: cleanup };\n } catch (error) {\n await cleanup();\n throw error;\n }\n}\n\n/** Polls the DevTools endpoint until the browser answers. */\nasync function waitForDevTools(\n port: number,\n hasExited: () => number | null\n): Promise<{ webSocketDebuggerUrl: string }> {\n for (let attempt = 0; attempt < 150; attempt++) {\n const code = hasExited();\n if (code !== null) {\n throw new CliError(`The browser exited while starting (code ${code}).`, CliExit.IoError);\n }\n try {\n const response = await fetch(`http://127.0.0.1:${port}/json/version`);\n if (response.ok) {\n return (await response.json()) as { webSocketDebuggerUrl: string };\n }\n } catch {\n // Not listening yet.\n }\n await new Promise(done => setTimeout(done, 200));\n }\n throw new CliError('The browser did not start in time.', CliExit.IoError);\n}\n\n/** True when an error came from the page rather than the harness. */\nexport function isPageError(error: unknown): error is PageError {\n return error instanceof PageError;\n}\n","/**\n * @fileoverview Turns the rendered content of the view's shadow root into an image.\n *\n * The browser has no API that converts a DOM subtree into pixels. Element\n * Capture and Region Capture come closest, but both sit on top of the Screen\n * Capture API and need the user to grant a capture prompt, which rules them out\n * for an export a script can call.\n *\n * What every DOM-to-image library does instead, and what this does, is hand the\n * markup back to the browser as an SVG `<foreignObject>` and let the rendering\n * engine paint it. Canvas only appears at the very end, to turn those pixels\n * into a file: `drawImage` then `toBlob`. Nothing is redrawn by hand, so the\n * output matches the view exactly, including text wrapping, shadows and the\n * theme.\n *\n * Excluded from the unit coverage figure (see `test:coverage` in package.json).\n * Everything left here talks to the browser - cloneNode, Image, canvas - so the\n * unit suite cannot reach a line of it. The UI suite exercises it for real,\n * against the built bundle, but a bundle carries no source line numbers to\n * report coverage against. The parts worth asserting in isolation live in\n * `export-svg.ts`; what remains is calls into browser APIs with no logic to check.\n */\n\nimport { JsMindError } from '../common/error.ts';\nimport { collectHostVariables, escapeAttribute, escapeText } from './export-svg.ts';\n\n/** Image formats a caller may ask for. */\nexport const JmImageType = {\n Png: 'image/png',\n Jpeg: 'image/jpeg',\n Webp: 'image/webp',\n} as const;\n\nexport type JmImageType = typeof JmImageType[keyof typeof JmImageType];\n\n/** Options for {@link captureShadowContent}. */\nexport interface JmExportImageOptions {\n /**\n * Device pixel ratio to render at. 2 gives a crisp result on high-density\n * screens and stays cheap; 1 mirrors what the user sees.\n */\n scale?: number;\n /** Output format. JPEG and WebP are lossy, PNG is not. */\n type?: JmImageType;\n /**\n * Quality for the lossy formats, 0 to 1. Ignored for PNG, where the browser\n * rejects a quality argument.\n */\n quality?: number;\n}\n\n/** What a capture produced. */\nexport interface JmExportImageResult {\n blob: Blob;\n /** Pixel width of the image, i.e. the content width times `scale`. */\n width: number;\n /** Pixel height of the image. */\n height: number;\n /** Content width in CSS pixels, before scaling. */\n cssWidth: number;\n /** Content height in CSS pixels, before scaling. */\n cssHeight: number;\n}\n\nconst DEFAULT_SCALE = 2;\n\n/**\n * Reads the shadow root's stylesheet back out.\n *\n * External stylesheets cannot reach into a shadow tree, which is why the view\n * carries its CSS as a string in the first place - that same string is what gets\n * inlined here.\n */\nfunction collectStyles(root: ShadowRoot): string {\n const sheets = root.querySelectorAll('style');\n return Array.from(sheets)\n .map(sheet => sheet.textContent ?? '')\n .join('\\n');\n}\n\n/**\n * Renders the shadow root's content to an image blob.\n *\n * The size is the content's own size, as laid out: the view sizes the map to\n * the larger of the container and the content, so whitespace the map does not\n * fill is kept and a map larger than its container is not cropped.\n *\n * @param host - The element the shadow root is attached to.\n * @param root - The view's shadow root.\n * @param size - The content size in CSS pixels, from the view.\n * @param options - Scale, format and quality.\n * @returns The encoded image plus its dimensions.\n * @throws {@link JsMindError} If there is nothing to capture, if the generated\n * SVG does not parse, or if the browser refuses to encode the canvas.\n */\nexport async function captureShadowContent(\n host: HTMLElement,\n root: ShadowRoot,\n size: { width: number; height: number },\n options: JmExportImageOptions = {}\n): Promise<JmExportImageResult> {\n const scale = options.scale ?? DEFAULT_SCALE;\n const type = options.type ?? JmImageType.Png;\n\n const inner = root.querySelector<HTMLElement>('.jsmind-inner');\n if (!inner) {\n throw new JsMindError('Nothing to capture: the view has no rendered content.');\n }\n\n // The size comes from the caller, not from the element. The inner container\n // is sized by its own container through CSS, so `clientWidth` reports the\n // viewport, not the map: a map larger than the box would be captured\n // cropped to the box. The view keeps the real size separately and hands it\n // over here.\n const cssWidth = size.width;\n const cssHeight = size.height;\n if (cssWidth === 0 || cssHeight === 0) {\n throw new JsMindError(\n `Nothing to capture: the rendered content has no size (${cssWidth}x${cssHeight}).`\n );\n }\n\n const clone = inner.cloneNode(true) as HTMLElement;\n clone.style.position = 'absolute';\n clone.style.left = '0';\n clone.style.top = '0';\n clone.style.margin = '0';\n // The container scrolls; inside a picture that would paint scrollbars.\n clone.style.overflow = 'visible';\n // It is already positioned in the export, not offset by a view pan.\n clone.style.transform = 'none';\n\n // `outerHTML` of a live <svg> carries no xmlns: the element is in the SVG\n // namespace already, so the serializer omits it. Reparsed as XHTML it is an\n // unknown element and paints nothing at all - which is how the edge layer\n // silently disappears from the export.\n for (const svg of Array.from(clone.querySelectorAll('svg'))) {\n svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');\n }\n\n const hostStyle = getComputedStyle(host);\n const wrapperStyle = escapeAttribute(\n [\n `width:${cssWidth}px`,\n `height:${cssHeight}px`,\n 'position:relative',\n 'overflow:hidden',\n `background:${hostStyle.backgroundColor}`,\n `font-family:${hostStyle.fontFamily}`,\n collectHostVariables(host.getAttribute('style')),\n ]\n .filter(Boolean)\n .join(';')\n );\n\n const svg =\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${cssWidth}\" height=\"${cssHeight}\">` +\n '<foreignObject x=\"0\" y=\"0\" width=\"100%\" height=\"100%\">' +\n `<div xmlns=\"http://www.w3.org/1999/xhtml\" style=\"${wrapperStyle}\">` +\n `<style>${escapeText(collectStyles(root))}</style>` +\n clone.outerHTML +\n '</div></foreignObject></svg>';\n\n const parsed = new DOMParser().parseFromString(svg, 'image/svg+xml');\n if (parsed.querySelector('parsererror')) {\n throw new JsMindError('Failed to render the view to an image: the generated SVG is malformed.');\n }\n\n // A blob: URL taints the canvas once the SVG carries a foreignObject, so\n // toBlob throws SecurityError. A data: URL keeps the document same-origin.\n const dataUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;\n const image = await loadImage(dataUrl);\n\n const canvas = document.createElement('canvas');\n canvas.width = Math.round(cssWidth * scale);\n canvas.height = Math.round(cssHeight * scale);\n\n const context = canvas.getContext('2d');\n if (!context) {\n throw new JsMindError('Failed to render the view to an image: 2D canvas is unavailable.');\n }\n context.scale(scale, scale);\n context.drawImage(image, 0, 0);\n\n const blob = await encodeCanvas(canvas, type, options.quality);\n\n return {\n blob,\n width: canvas.width,\n height: canvas.height,\n cssWidth,\n cssHeight,\n };\n}\n\n/** Loads a data URL into a decoded image. */\nfunction loadImage(src: string): Promise<HTMLImageElement> {\n return new Promise((resolve, reject) => {\n const image = new Image();\n image.onload = () => resolve(image);\n // The error event carries no detail beyond \"failed to load\", so the\n // message has to say where to look.\n image.onerror = () =>\n reject(new JsMindError('Failed to render the view to an image: the SVG did not load.'));\n image.src = src;\n });\n}\n\n/** Encodes a canvas, passing a quality only for the lossy formats. */\nfunction encodeCanvas(\n canvas: HTMLCanvasElement,\n type: JmImageType,\n quality: number | undefined\n): Promise<Blob> {\n return new Promise((resolve, reject) => {\n const done = (blob: Blob | null): void => {\n if (blob === null) {\n reject(new JsMindError(`Failed to encode the image as ${type}.`));\n } else {\n resolve(blob);\n }\n };\n // PNG has no quality knob; passing one makes some browsers treat the\n // argument as a format hint and fall back to a different encoder.\n if (type === JmImageType.Png || quality === undefined) {\n canvas.toBlob(done, type);\n } else {\n canvas.toBlob(done, type, quality);\n }\n });\n}\n","/**\n * `jsmind export` — render a mind map file to a PNG.\n *\n * The rendering itself happens in a browser, because the picture is produced by\n * handing the markup back to a rendering engine. This command only drives it:\n * load, open, ask the page for a blob, write the bytes.\n *\n * @packageDocumentation\n */\n\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\n\nimport { validateMindData } from '../../serialization/validation.ts';\nimport { readJsonFile } from '../io.ts';\nimport { CliExit, CliError } from '../exit.ts';\nimport { openBrowser, isPageError } from '../browser.ts';\nimport { JmImageType } from '../../view/export.ts';\n\n/** Viewport the map is laid out in when the caller does not say. */\nexport const DEFAULT_WIDTH = 1200;\n\n/** Viewport height, same default reasoning. */\nexport const DEFAULT_HEIGHT = 800;\n\n/** Rendered at 2x by default: crisp on a dense screen, still cheap. */\nexport const DEFAULT_SCALE = 2;\n\n/** Arguments accepted by {@link runExport}. */\nexport interface ExportOptions {\n /** Path to the mind map JSON. */\n file: string;\n /** Where to write the image. */\n output: string;\n /** Viewport width the map is laid out in. */\n width: number;\n /** Viewport height the map is laid out in. */\n height: number;\n /** Output pixel ratio. */\n scale: number;\n /** One of {@link JmImageType}. */\n type: string;\n /** Emit machine-readable output. */\n asJson: boolean;\n}\n\n/** What the page reports back. */\ninterface PageResult {\n base64: string;\n width: number;\n height: number;\n cssWidth: number;\n cssHeight: number;\n bytes: number;\n}\n\n/**\n * Renders a mind map file to an image.\n *\n * @param options - Paths, viewport, scale and format.\n * @returns The exit code: 0 on success.\n * @throws {@link CliError} For usage, data, IO and browser failures.\n */\nexport async function runExport(options: ExportOptions): Promise<number> {\n const data = readJsonFile(options.file);\n\n // Validate before starting a browser: a bad file should fail in\n // milliseconds, not after a Chrome launch.\n const validation = validateMindData(data);\n if (!validation.valid) {\n process.stderr.write(`${options.file}: ${validation.errors.length} problem(s)\\n`);\n for (const issue of validation.errors.slice(0, 10)) {\n process.stderr.write(` ${issue.code} ${issue.path || '<root>'}\\n ${issue.message}\\n`);\n }\n return CliExit.InvalidData;\n }\n\n const session = await openBrowser(options.width, options.height);\n\n try {\n const script = `\n (async () => {\n const stage = document.getElementById('stage');\n const jm = await jsMind.create(stage);\n const mind = jsMind.Serializer.create('json')\n .deserialize(JSON.parse(${JSON.stringify(JSON.stringify(data))}));\n await jm.open(mind);\n\n // Fonts before frames: layout measured against a fallback face\n // stays measured against it, so a map that ends up in a web font\n // would be exported with the wrong metrics - and the picture\n // would look plausible, just not like the screen. document.fonts.ready\n // resolves once they are loaded and applied; the two frames\n // after it let the relayout that the swap triggered finish.\n if (document.fonts) {\n await document.fonts.ready;\n }\n await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));\n\n const result = await jm.exportImage({\n scale: ${JSON.stringify(options.scale)},\n type: ${JSON.stringify(options.type)},\n });\n\n const base64 = await new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => {\n const text = String(reader.result);\n resolve(text.slice(text.indexOf(',') + 1));\n };\n reader.onerror = () => reject(new Error('could not read the blob'));\n reader.readAsDataURL(result.blob);\n });\n\n return {\n base64,\n width: result.width,\n height: result.height,\n cssWidth: result.cssWidth,\n cssHeight: result.cssHeight,\n bytes: result.blob.size,\n };\n })()\n `;\n\n const result = (await session.evaluate(script)) as PageResult;\n const bytes = Buffer.from(result.base64, 'base64');\n // The caller may well name a path under a directory that does not exist\n // yet (`tmp/preview.png` in CI is exactly that); creating it is cheaper\n // than making every caller write the mkdir themselves.\n mkdirSync(dirname(options.output), { recursive: true });\n writeFileSync(options.output, bytes, { flag: 'w' });\n\n if (options.asJson) {\n process.stdout.write(\n `${JSON.stringify(\n {\n output: options.output,\n width: result.width,\n height: result.height,\n cssWidth: Math.round(result.cssWidth),\n cssHeight: Math.round(result.cssHeight),\n bytes: bytes.length,\n type: options.type,\n },\n null,\n 2\n )}\\n`\n );\n } else {\n process.stdout.write(\n `${options.output}: ${result.width}x${result.height} ` +\n `(${(bytes.length / 1024).toFixed(1)} KB)\\n`\n );\n }\n\n return CliExit.Ok;\n } catch (error) {\n if (isPageError(error)) {\n // The page could not render: bad data for the renderer, or a browser\n // that cannot encode the canvas. Neither is a crash of this tool.\n throw new CliError(`Rendering failed: ${error.message}`, CliExit.IoError);\n }\n throw error;\n } finally {\n await session.close();\n }\n}\n\n/** The formats this command will accept on the command line. */\nexport const EXPORT_TYPES: readonly string[] = Object.values(JmImageType);\n\n/**\n * Describes the export command for `--help`.\n */\nexport function describeExport(): string {\n return [\n 'Usage: jsmind export <file> <out.png> [options]',\n '',\n 'Renders a mind map to an image. The size is the map\\'s own size:',\n 'whitespace inside the viewport is kept, and a map larger than the',\n 'viewport is not cropped.',\n '',\n 'Options:',\n ' --width <px> Viewport width to lay the map out in (default 1200)',\n ' --height <px> Viewport height (default 800)',\n ' --scale <n> Output pixel ratio (default 2)',\n ' --type <format> image/png, image/jpeg or image/webp (default image/png)',\n ' --json Machine-readable output',\n '',\n 'Requires a Chromium binary. Set CHROME_PATH if it is not in a',\n 'standard location.',\n ].join('\\n');\n}\n","/**\n * `jsmind validate` — check a mind map file without touching it.\n *\n * @packageDocumentation\n */\n\nimport { validateMindData } from '../../serialization/validation.ts';\nimport { readJsonFile } from '../io.ts';\nimport { CliExit, usageError } from '../exit.ts';\n\n/**\n * Runs the validate command.\n *\n * @param file - Path to the mind map JSON.\n * @param asJson - Emit machine-readable output instead of prose.\n * @returns The exit code: 0 when valid, 1 when the data is invalid.\n * @throws {@link CliError} With `IoError` when the file cannot be read.\n */\nexport function runValidate(file: string, asJson: boolean): number {\n const data = readJsonFile(file);\n const result = validateMindData(data);\n\n if (asJson) {\n process.stdout.write(\n `${JSON.stringify({ valid: result.valid, errors: result.errors }, null, 2)}\\n`\n );\n return result.valid ? CliExit.Ok : CliExit.InvalidData;\n }\n\n if (result.valid) {\n process.stdout.write(`${file}: valid\\n`);\n return CliExit.Ok;\n }\n\n // One line per issue, code first so it lines up for scanning.\n process.stderr.write(`${file}: ${result.errors.length} problem(s)\\n\\n`);\n for (const issue of result.errors) {\n process.stderr.write(` ${issue.code} ${issue.path || '<root>'}\\n ${issue.message}\\n`);\n }\n return CliExit.InvalidData;\n}\n\n/**\n * Describes the validate command for `--help`.\n */\nexport const validateHelp = `jsmind validate <file> [--json]\n\nChecks a v2 mind map file against the format specification and reports every\nproblem found. Does not modify the file.\n\nExit codes:\n 0 valid\n 1 invalid data\n 3 file cannot be read`;\n\n/**\n * Throws when the argument list does not fit the command.\n *\n * @param positional - Positional arguments after the command name.\n */\nexport function assertValidateArgs(positional: string[]): void {\n if (positional.length === 0) {\n throw usageError('validate requires a file path');\n }\n if (positional.length > 1) {\n throw usageError(`validate takes one file, got ${positional.length}`);\n }\n}\n","import { JsMindError } from '../common/error.ts';\nimport type { JmObserver } from './index.ts';\n\n/**\n * Manager for observers of an observed object.\n *\n * @public\n */\nexport class JmObserverManager<T> {\n /** The object being observed. */\n observedObject: T;\n\n /** @internal */\n _observers: JmObserver<T>[];\n\n /**\n * Creates an observer manager for an observed object.\n *\n * @param observedObject - The object to observe.\n */\n constructor(observedObject: T) {\n this.observedObject = observedObject;\n this._observers = [];\n }\n\n /**\n * Adds an observer to the observed object.\n *\n * @param observer - An object that contains an `update(observedObject, event)` method.\n * @throws {@link JsMindError} If the observer is not a valid JmObserver instance.\n */\n addObserver(observer: JmObserver<T>): void {\n if(!observer || !('update' in observer) || typeof observer.update !== 'function') {\n throw new JsMindError('observer is not a valid JmObserver instance');\n }\n this._observers.push(observer);\n }\n\n /**\n * Removes an observer that was previously added by the `addObserver` method.\n *\n * @param observer - The observer to remove.\n */\n removeObserver(observer: JmObserver<T>): void {\n this._observers = this._observers.filter(o => o !== observer);\n }\n\n /**\n * Removes all observers from the object.\n */\n clearObservers(): void {\n this._observers = [];\n }\n\n /**\n * Notifies the event to all observers.\n *\n * @remarks\n * This is an asynchronous method. Each observer is notified in a separate\n * asynchronous operation.\n *\n * @param event - Events are defined by different observed objects, which\n * represent specific information about the changes.\n */\n async notifyObservers(event: unknown): Promise<void> {\n this._observers.forEach(async (observer: JmObserver<T>) => {\n await new Promise<void>((resolve) => {\n setTimeout(() => {\n observer.update(this.observedObject, event);\n resolve();\n });\n });\n }\n );\n }\n}\n\n","/**\n * Metadata for the mind map.\n *\n * @public\n */\n\nimport { mergeObjects } from './object.ts';\nexport interface MindMetadata {\n /** The author of the mind map. */\n author: string;\n /** The name of the mind map. */\n name: string;\n /** The version of the mind map. */\n version: string;\n}\n\n/**\n * Configuration options for the mind map.\n *\n * @public\n */\nexport interface MindOptions {\n rootNodeId: string;\n}\n\nexport interface ViewPadding {\n left: number;\n right: number;\n top: number;\n bottom: number;\n}\n\nexport const ViewExpanderStyle = {\n Char: 'char',\n Number: 'number'\n} as const;\n\ntype ViewExpanderStyle = typeof ViewExpanderStyle[keyof typeof ViewExpanderStyle];\n\nexport interface ViewExpanderOptions {\n style: ViewExpanderStyle;\n // expanded: string;\n // collapsed: string;\n}\nexport interface ViewOptions {\n padding: ViewPadding;\n expander: ViewExpanderOptions;\n}\n\nexport interface LayoutOptions {\n parentChildSpace: number;\n siblingSpace: number;\n cousinSpace: number;\n expanderSize: number;\n}\n\n/**\n * Options for JsMind.\n *\n * @public\n */\nexport interface JsMindOptions {\n mind: MindOptions;\n view: ViewOptions;\n layout: LayoutOptions;\n}\n\nexport const DEFAULT_METADATA: MindMetadata = {\n author: 'hizzgdev@163.com',\n name: 'jsMind Mindmap',\n version: '1.0'\n};\n\nexport const DEFAULT_OPTIONS: JsMindOptions = {\n mind: {\n rootNodeId: 'root'\n },\n view: {\n padding: {\n left: 100,\n right: 100,\n top: 50,\n bottom: 50\n },\n expander: {\n style: ViewExpanderStyle.Char\n // expanded: '\\u229D', // ⊝\n // collapsed: '\\u2295' // ⊕\n }\n },\n layout: {\n parentChildSpace: 30,\n siblingSpace: 20,\n cousinSpace: 15,\n expanderSize: 13\n }\n};\n\n/**\n * Merges the provided options with the default options and returns a new options object.\n *\n * @param options - Partial options to merge with default options\n * @returns A new merged options object\n *\n * @public\n */\nexport function mergeJsMindOptions(options?: Partial<JsMindOptions>): JsMindOptions {\n if (!options) {\n return { ...DEFAULT_OPTIONS };\n }\n\n return {\n mind: {\n ...mergeObjects(DEFAULT_OPTIONS.mind, options.mind)\n },\n view: {\n ...mergeObjects(DEFAULT_OPTIONS.view, options.view)\n },\n layout: {\n ...mergeObjects(DEFAULT_OPTIONS.layout, options.layout)\n }\n };\n}\n","/**\n * Interface for generating unique IDs.\n *\n * @remarks\n * IdGenerator is an interface for generating unique IDs.\n *\n * @example\n * ```typescript\n * class MyIdGenerator extends IdGenerator {\n * constructor() {\n * super();\n * this._seq = 0;\n * }\n * newId() {\n * return 'my' + (this._seq++);\n * }\n * }\n * ```\n *\n * @public\n */\nexport class IdGenerator {\n /**\n * Generates a new unique ID.\n *\n * @returns A new unique ID.\n * @throws {@link Error} If not implemented.\n */\n newId(): string {\n throw new Error('not implemented');\n }\n}\n\n/**\n * Simple implementation of IdGenerator.\n *\n * @public\n */\nexport class SimpleIdGenerator extends IdGenerator {\n /** The seed value for ID generation. */\n seed: number;\n\n /** The sequence counter. */\n seq: number;\n\n /** The prefix for generated IDs. */\n prefix: string;\n\n /**\n * Creates a new SimpleIdGenerator instance.\n *\n * @param prefix - Optional prefix for generated IDs. Defaults to empty string.\n */\n constructor(prefix?: string) {\n super();\n this.seed = new Date().getTime();\n this.seq = 0;\n this.prefix = prefix || '';\n }\n\n /**\n * Generates a new unique ID.\n *\n * @returns A new unique ID with the format: prefix + (seed + seq).toString(36)\n */\n newId(): string {\n this.seq++;\n return this.prefix + (this.seed + this.seq).toString(36);\n }\n}\n\n/**\n * Global ID generator instance.\n *\n * @public\n */\nexport const GLOBAL_ID_GENERATOR = new SimpleIdGenerator('jm-');\n\n","\n\n/**\n * Enumeration of mind map event types.\n *\n * @public\n */\nexport const JmMindEventType = {\n /** Event fired when a node is added. */\n NodeAdded: 1,\n /** Event fired when a node is removed. */\n NodeRemoved: 2,\n /** Event fired when a node is updated. */\n NodeUpdated: 3,\n /** Event fired when a node is moved. */\n NodeMoved: 4,\n /** Event fired when an edge is added. */\n EdgeAdded: 5,\n /** Event fired when an edge is removed. */\n EdgeRemoved: 6,\n} as const;\n\nexport type JmMindEventType = typeof JmMindEventType[keyof typeof JmMindEventType];\n","import { JmMindEventType } from './index.ts';\nimport type { JmNode, JmNodeSide} from '../data/node.ts';\nimport type { JmEdge } from '../data/edge.ts';\n\n/**\n * Event data containing the state change in JmMind.\n *\n * @public\n */\nexport class JmMindEvent {\n /** The type of the event. */\n readonly type: JmMindEventType;\n\n /** The event data. */\n readonly data: JmMindEventData;\n\n /**\n * Creates a new JmMindEvent instance.\n *\n * @param type - The type of the event.\n * @param data - The event data.\n */\n constructor(type: JmMindEventType, data: JmMindEventData) {\n this.type = type;\n this.data = data;\n }\n\n static onNodeAdded(node: JmNode) {\n return new JmMindEvent(JmMindEventType.NodeAdded, new JmMindEventDataOnNodeAdded(node));\n }\n\n static onNodeRemoved(node: JmNode, removedNodeIds: string[], removedEdgeIds: string[]) {\n return new JmMindEvent(JmMindEventType.NodeRemoved, new JmMindEventDataOnNodeRemoved(node, removedNodeIds, removedEdgeIds));\n }\n\n static onNodeUpdated(node: JmNode, property: string, originValue: unknown, newValue: unknown) {\n return new JmMindEvent(JmMindEventType.NodeUpdated, new JmMindEventDataOnNodeUpdated(node, property, originValue, newValue));\n }\n\n static onNodeMoved(node: JmNode, oldParentId: string | null, oldPosition: number | null, oldSide: JmNodeSide | null) {\n return new JmMindEvent(JmMindEventType.NodeMoved, new JmMindEventDataOnNodeMoved(node, oldParentId, oldPosition, oldSide));\n }\n\n static onEdgeAdded(edge: JmEdge) {\n return new JmMindEvent(JmMindEventType.EdgeAdded, new JmMindEventDataOnEdgeAdded(edge));\n }\n\n static onEdgeRemoved(edge: JmEdge) {\n return new JmMindEvent(JmMindEventType.EdgeRemoved, new JmMindEventDataOnEdgeRemoved(edge));\n }\n\n}\n\n\nexport class JmMindEventDataOnNodeAdded {\n readonly node: JmNode;\n\n constructor(node: JmNode) {\n this.node = node;\n }\n}\n\nexport class JmMindEventDataOnNodeRemoved {\n readonly node: JmNode;\n\n readonly removedNodeIds: string[];\n\n readonly removedEdgeIds: string[];\n\n constructor(node: JmNode, removedNodeIds: string[], removedEdgeIds: string[]) {\n this.node = node;\n this.removedNodeIds = removedNodeIds.slice();\n this.removedEdgeIds = removedEdgeIds.slice();\n }\n}\n\nexport class JmMindEventDataOnNodeUpdated {\n readonly node: JmNode;\n\n readonly property: string;\n\n readonly originValue: unknown;\n\n readonly newValue: unknown;\n\n constructor(node: JmNode, property: string, originValue: unknown, newValue: unknown) {\n this.node = node;\n this.property = property;\n this.originValue = originValue;\n this.newValue = newValue;\n }\n}\n\nexport class JmMindEventDataOnNodeMoved {\n readonly node: JmNode;\n\n readonly oldParentId: string | null;\n\n readonly oldPosition: number | null;\n\n readonly oldSide: JmNodeSide | null;\n\n constructor(node: JmNode, oldParentId: string | null, oldPosition: number | null, oldSide: JmNodeSide | null) {\n this.node = node;\n this.oldParentId = oldParentId;\n this.oldPosition = oldPosition;\n this.oldSide = oldSide;\n }\n}\n\nexport class JmMindEventDataOnEdgeAdded {\n readonly edge: JmEdge;\n\n constructor(edge: JmEdge) {\n this.edge = edge;\n }\n}\n\nexport class JmMindEventDataOnEdgeRemoved {\n readonly edge: JmEdge;\n\n constructor(edge: JmEdge) {\n this.edge = edge;\n }\n}\n\nexport type JmMindEventData = JmMindEventDataOnNodeRemoved | JmMindEventDataOnNodeAdded | JmMindEventDataOnNodeUpdated | JmMindEventDataOnNodeMoved | JmMindEventDataOnEdgeAdded | JmMindEventDataOnEdgeRemoved;\n","import { JmObserverManager } from '../observer/manager.ts';\nimport { JmEdge, type EdgeCreationOptions, type JmEdgeType } from './data/edge.ts';\nimport { JmNode, type NodeCreationOptions, type NodeDestinationOptions, JmNodeSide } from './data/node.ts';\nimport { JmNodeContent } from './data/node-content.ts';\nimport { type MindMetadata, type MindOptions, DEFAULT_METADATA, DEFAULT_OPTIONS } from '../common/option.ts';\nimport { mergeObjects } from '../common/object.ts';\nimport { SimpleIdGenerator } from '../generation/index.ts';\nimport type { JmStyle } from './data/style.ts';\n\nimport { JmMindEvent } from './event/data.ts';\nimport { JsMindError } from '../common/error.ts';\n\n/**\n * Represents a mind map with nodes and edges.\n *\n * @public\n */\nexport class JmMind {\n /** Metadata for the mind map. */\n meta: MindMetadata;\n\n /** Configuration options for the mind map. */\n options: MindOptions;\n\n /**\n * Style declaration for the mind map.\n *\n * @remarks\n * This mind map inherits from `style.theme` (default `\"default\"`) and\n * overrides whatever else the declaration lists. Resolution and deep\n * merging happen at render time via `resolveJmStyle`, not here — this\n * field only stores what the file said.\n */\n style?: JmStyle;\n\n /** Manager for observers of this mind map. */\n observerManager: JmObserverManager<JmMind>;\n\n /** Manager for node operations. */\n nodeManager: JmNodeManager;\n\n /** @internal Internal ID generator for nodes and edges. */\n _idGenerator: SimpleIdGenerator;\n\n /** @internal Dictionary of all nodes by ID. */\n _nodes: Record<string, JmNode>;\n\n /** @internal Dictionary of all edges by ID. */\n _edges: Record<string, JmEdge>;\n\n /** @internal The root node of the mind map. */\n _root: JmNode;\n\n /**\n * Creates a new mind map.\n *\n * @param metadata - Metadata for the mind map.\n * @param options - Configuration options for the mind map.\n */\n constructor(metadata: Partial<MindMetadata> = {}, options: Partial<MindOptions> = {}) {\n this.meta = mergeObjects(DEFAULT_METADATA, metadata) as MindMetadata;\n this.options = mergeObjects(DEFAULT_OPTIONS.mind, options) as MindOptions;\n this.observerManager = new JmObserverManager<JmMind>(this);\n this.nodeManager = new JmNodeManager(this);\n this._idGenerator = new SimpleIdGenerator('jm-');\n this._nodes = {};\n this._edges = {};\n this._root = this._createRootNode();\n }\n\n /**\n * Gets the root node.\n *\n * @returns The root node.\n */\n get root(): JmNode {\n return this.lite(this._root);\n }\n\n /**\n * Adds an edge between two nodes.\n *\n * @param sourceNodeId - The source node ID.\n * @param targetNodeId - The target node ID.\n * @param type - The edge type.\n * @param options - Optional edge creation options.\n * @returns The created edge.\n * @throws {@link JsMindError} If the source or target node does not exist.\n */\n addEdge(sourceNodeId: string, targetNodeId: string, type: JmEdgeType, options?: EdgeCreationOptions): JmEdge {\n // Validate nodes exist\n this._getNodeById(sourceNodeId);\n this._getNodeById(targetNodeId);\n\n const edgeId = (options && options.edgeId) || this._idGenerator.newId();\n const label = (options && options.label) || null;\n const edge = new JmEdge(edgeId, sourceNodeId, targetNodeId, type, label);\n if (options && options.style !== undefined) {\n edge.style = options.style;\n }\n this._edges[edgeId] = edge;\n\n // Emit event\n this.observerManager.notifyObservers(JmMindEvent.onEdgeAdded(edge));\n\n return edge;\n }\n\n\n addChildNode(content: unknown, parentId: string): JmNode {\n if(!parentId) {\n throw new JsMindError('parentId is required for addChildNode');\n }\n if(!content) {\n throw new JsMindError('content is required for addChildNode');\n }\n\n let nodeContent: JmNodeContent;\n if(content instanceof JmNodeContent) {\n nodeContent = content;\n } else if(typeof content === 'string') {\n nodeContent = JmNodeContent.createText(content);\n } else {\n throw new JsMindError('content must be a string or a JmNodeContent object');\n }\n return this.addNode(nodeContent, { parentId: parentId });\n }\n\n /**\n * Adds a new node to the mind map at a specific destination.\n *\n * @param content - Content for the new node.\n * @param destOptions - Destination options (required).\n * @param nodeOptions - Optional node creation options.\n * @returns The created node.\n * @throws {@link JsMindError} If destOptions.parentId is missing.\n */\n addNode(content: JmNodeContent, destOptions: NodeDestinationOptions, nodeOptions?: NodeCreationOptions): JmNode {\n // Validate destination options\n if (!destOptions || !destOptions.parentId) {\n throw new JsMindError('destOptions.parentId is required for addNode');\n }\n\n // Get target parent\n const targetParent = this._getNodeById(destOptions.parentId);\n\n // Create node content\n const nodeContent = content instanceof JmNodeContent ? content : JmNodeContent.fromObject(content);\n\n // Create and initialize the node\n const node = this._newNode(nodeContent, nodeOptions);\n\n // Use existing helper method for placement\n this._addNodeToParent(node, targetParent, destOptions.position);\n\n // Apply destination side if specified\n if (destOptions.side !== undefined && destOptions.side !== null) {\n node.side = destOptions.side;\n }\n\n // Emit event\n this.observerManager.notifyObservers(JmMindEvent.onNodeAdded(node));\n\n return this.lite(node);\n }\n\n /**\n * Finds a node from the mind map by the given ID.\n *\n * @param nodeId - The given node ID.\n * @returns The corresponding node in this mind map if it exists, otherwise null.\n */\n findNodeById(nodeId: string): JmNode | null {\n const node = this._nodes[nodeId];\n return !!node ? this.lite(node) : null;\n }\n\n /**\n * Gets all edges for a specific node.\n *\n * @param nodeId - The node ID.\n * @param type - Optional edge type filter.\n * @returns Array of edges involving the node.\n */\n getEdges(nodeId: string, type: JmEdgeType | null = null): JmEdge[] {\n return Object.values(this._edges).filter(edge => {\n return (edge.sourceNodeId === nodeId || edge.targetNodeId === nodeId) &&\n (!type || edge.type === type);\n });\n }\n\n /**\n * Moves a node to a new parent and position.\n *\n * @param nodeId - The ID of the node to move.\n * @param destOptions - Destination options.\n * @returns The moved node.\n * @throws {@link JsMindError} If destOptions are missing, node not found, or invalid move operation.\n */\n moveNode(nodeId: string, destOptions: NodeDestinationOptions): JmNode {\n if (!destOptions || Object.keys(destOptions).length === 0) {\n throw new JsMindError('destOptions are required for moveNode operation');\n }\n\n const node = this._getNodeById(nodeId);\n if (!node) {\n throw new JsMindError(`Node with ID '${nodeId}' not found`);\n }\n\n // Skip all logic for root node - it cannot be moved\n if (node === this.root) {\n return this.lite(node);\n }\n\n // Extract options\n const targetParentId = destOptions.parentId;\n const targetPosition = destOptions.position;\n const targetSide = destOptions.side;\n\n // Capture original values before any changes\n const oldParent = node.parent;\n const oldPosition = node.parent ? node.parent.children.indexOf(node) : -1;\n const oldSide = node.side;\n\n // 1. Update parent and position if the node parent is provided and changed\n if (targetParentId && (!node.parent || node.parent.id !== targetParentId)) {\n const targetParent = this._getNodeById(targetParentId);\n if (!targetParent) {\n throw new JsMindError(`Target parent with ID '${targetParentId}' not found`);\n }\n\n // Validate that we're not moving a node to be its own descendant\n if (targetParent.isDescendant(node)) {\n throw new JsMindError('Cannot move a node to be its own descendant');\n }\n\n // Remove from current parent\n this._removeNodeFromParent(node);\n\n // Add to new parent at specified position and create edge\n this._addNodeToParent(node, targetParent, targetPosition);\n }\n\n // 2. Reposition if the node parent is not provided or is not changed, and the targetPosition is provided and changed\n if ((!targetParentId || (node.parent && node.parent.id === targetParentId)) &&\n targetPosition !== undefined && targetPosition !== null) {\n this._repositionNode(node, targetPosition);\n }\n\n // 3. Update side if the target side is provided and changed\n if (targetSide !== undefined && targetSide !== null) {\n node.side = targetSide;\n }\n\n // 4. Emit event only if something actually changed\n this._emitNodeMovedEventIfChanged(node, oldParent, oldPosition, oldSide);\n\n return this.lite(node);\n }\n\n /**\n * Removes an edge by ID.\n *\n * @param edgeId - The edge ID to remove.\n * @returns True if the edge was removed, false if not found.\n */\n removeEdge(edgeId: string): boolean {\n const edge = this._edges[edgeId];\n if (edge) {\n delete this._edges[edgeId];\n\n // Emit event\n this.observerManager.notifyObservers(JmMindEvent.onEdgeRemoved(edge));\n return true;\n }\n return false;\n }\n\n /**\n * Removes a node and all its descendants.\n *\n * @param nodeId - The ID of the node to remove.\n * @throws {@link JsMindError} If trying to remove the root node.\n */\n removeNode(nodeId: string): void {\n const node = this._getNodeById(nodeId);\n if(nodeId == this._root.id) {\n throw new JsMindError('root node can not be removed');\n }\n\n // remove node from parent's children\n const nodeIndex = node.parent!.children.indexOf(node);\n node.parent!.children.splice(nodeIndex, 1);\n\n // identify all nodes that need to be cleared\n const nodeIds = node.getAllSubnodeIds();\n nodeIds.push(node.id);\n\n // remove those nodes\n nodeIds.forEach((id)=> delete this._nodes[id]);\n\n // remove all relevant edges\n const edgeIds = Object.values(this._edges)\n .filter((e)=>nodeIds.includes(e.sourceNodeId) || nodeIds.includes(e.targetNodeId))\n .map((e) => e.id);\n edgeIds.forEach((id) => delete this._edges[id]);\n\n // emit event\n this.observerManager.notifyObservers(JmMindEvent.onNodeRemoved(node, nodeIds, edgeIds));\n }\n\n /**\n * Adds a node to a new parent at a specific position.\n *\n * @private\n * @param node - The node to add.\n * @param targetParent - The new parent node.\n * @param targetPosition - The position index among siblings.\n */\n _addNodeToParent(node: JmNode, targetParent: JmNode, targetPosition?: number | null): void {\n node.parent = targetParent;\n\n if (targetPosition === undefined || targetPosition === null) {\n // Add to the end if no position specified\n targetParent.children.push(node);\n } else {\n // Insert at specific position\n const position = Math.max(0, Math.min(targetPosition, targetParent.children.length));\n targetParent.children.splice(position, 0, node);\n }\n }\n\n /**\n * Creates the root node.\n *\n * @private\n * @returns The created root node.\n */\n _createRootNode(): JmNode {\n const nodeOptions = {\n nodeId: this.options.rootNodeId,\n side: JmNodeSide.Center\n };\n return this._newNode(JmNodeContent.createText(this.meta.name), nodeOptions);\n }\n\n /**\n * Emits NodeMoved event only if something actually changed.\n *\n * @private\n * @param node - The node that was moved.\n * @param oldParent - The old parent node.\n * @param oldPosition - The old position index.\n * @param oldSide - The old side.\n */\n _emitNodeMovedEventIfChanged(node: JmNode, oldParent: JmNode | null, oldPosition: number, oldSide: JmNodeSide | null): void {\n // Compare actual updated node properties with old values\n const parentChanged = oldParent!.id !== node.parent!.id;\n const positionChanged = oldPosition !== node.parent!.children.indexOf(node);\n const sideChanged = oldSide !== node.side;\n\n if (parentChanged || positionChanged || sideChanged) {\n const oldParentId = parentChanged ? oldParent!.id : null;\n const oldPositionData = positionChanged ? oldPosition : null;\n const oldSideData = sideChanged ? oldSide : null;\n this.observerManager.notifyObservers(JmMindEvent.onNodeMoved(node, oldParentId, oldPositionData, oldSideData));\n }\n }\n\n /**\n * Creates a new node and adds it to the mind map.\n *\n * @private\n * @param content - Content for the node.\n * @param nodeOptions - Optional node creation options.\n * @returns The created node.\n */\n _newNode(content: JmNodeContent, nodeOptions?: NodeCreationOptions): JmNode {\n const nodeId = (nodeOptions && nodeOptions.nodeId) || this._idGenerator.newId();\n const node = new JmNode(nodeId, content);\n if (nodeOptions) {\n if (nodeOptions.folded !== undefined) {\n node.folded = nodeOptions.folded;\n }\n if (nodeOptions.side !== undefined) {\n node.side = nodeOptions.side;\n }\n if (nodeOptions.data !== undefined) {\n node.data = nodeOptions.data;\n }\n if (nodeOptions.style !== undefined) {\n node.style = nodeOptions.style;\n }\n }\n this._nodes[nodeId] = node;\n return node;\n }\n\n /**\n * Handles node update events.\n *\n * @private\n * @param node - The node that was updated.\n * @param prop - The property that was updated.\n * @param originValue - The original value.\n * @param newValue - The new value.\n */\n _onNodeUpdated(node: JmNode, prop: string, originValue: unknown, newValue: unknown): void {\n this.observerManager.notifyObservers(JmMindEvent.onNodeUpdated(node, prop, originValue, newValue));\n }\n\n /**\n * Removes a node from its current parent.\n *\n * @private\n * @param node - The node to remove from parent.\n */\n _removeNodeFromParent(node: JmNode): void {\n if (!node.parent) {\n return;\n }\n\n const parent = node.parent;\n const index = parent.children.indexOf(node);\n if (index > -1) {\n parent.children.splice(index, 1);\n }\n node.parent = null;\n }\n\n /**\n * Repositions a node within the same parent (optimized operation).\n *\n * @private\n * @param node - The node to reposition.\n * @param targetPosition - The new position index among siblings.\n */\n _repositionNode(node: JmNode, targetPosition: number): void {\n if (targetPosition === undefined || targetPosition === null) {\n return;\n }\n\n const parent = node.parent!;\n const currentIndex = parent.children.indexOf(node);\n const newPosition = Math.max(0, Math.min(targetPosition, parent.children.length));\n\n if (currentIndex !== newPosition) {\n parent.children.splice(currentIndex, 1);\n parent.children.splice(newPosition, 0, node);\n }\n }\n\n /**\n * Retrieves a node by node ID.\n *\n * @private\n * @param nodeId - The node ID.\n * @returns The corresponding node.\n * @throws {@link JsMindError} If the node doesn't exist.\n */\n _getNodeById(nodeId: string): JmNode {\n const node = this._nodes[nodeId];\n if(!!node) {\n return node;\n }\n throw new JsMindError(`node[id=${nodeId}] does not exist`);\n }\n\n private lite(node: JmNode): JmNode {\n return this.nodeManager.manage(node);\n }\n}\n\n/**\n * Manager for node operations with proxy-based access control.\n *\n * @internal\n */\nclass JmNodeManager {\n /** The mind map instance. */\n mind: JmMind;\n\n /** Set of readonly field names. */\n readonlyFields: Set<string>;\n\n /** Set of unsafe array method names. */\n unsafeArrayMethods: Set<string>;\n\n /**\n * Creates a new JmNodeManager instance.\n *\n * @param mind - The mind map instance.\n */\n constructor(mind: JmMind) {\n this.mind = mind;\n this.readonlyFields = new Set(['id', 'parent', 'children', 'data']);\n this.unsafeArrayMethods = new Set(['fill', 'pop', 'push', 'shift', 'unshift', 'reverse', 'sort', 'splice']);\n }\n\n /**\n * Manages a node with proxy-based access control.\n *\n * @param node - The node to manage.\n * @returns The managed node with proxy.\n */\n manage(node: JmNode): JmNode {\n return new Proxy(node, {\n get: this.getterTrap.bind(this),\n set: this.setterTrap.bind(this)\n }) as JmNode;\n }\n\n /**\n * Getter trap for the proxy.\n *\n * @param node - The node.\n * @param prop - The property name.\n * @returns The property value.\n */\n getterTrap(node: JmNode, prop: string | symbol): unknown {\n const ori = (node as unknown as Record<string | symbol, unknown>)[prop];\n if(prop === 'children') {\n const itemManagedArray = (ori as JmNode[]).map((n: JmNode)=>this.manage(n));\n return new Proxy(itemManagedArray, {\n get: (arr: JmNode[], prop: string | symbol) =>{\n if(this.unsafeArrayMethods.has(prop as string)) {\n return function() {\n throw new JsMindError(`unsupported method ${String(prop)} on node.children, please follow the document to operate the mindmap.`);\n };\n }\n return arr[prop as keyof typeof arr];\n }\n });\n }\n if(prop === 'parent') {\n return !!ori ? this.manage(ori as JmNode) : null;\n }\n return ori;\n }\n\n /**\n * Setter trap for the proxy.\n *\n * @param node - The node.\n * @param prop - The property name.\n * @param value - The new value.\n * @returns True if the operation succeeded.\n * @throws {@link JsMindError} If trying to set a readonly property.\n */\n setterTrap(node: JmNode, prop: string | symbol, value: unknown): boolean {\n if(this.readonlyFields.has(prop as string)) {\n throw new JsMindError(`the property[${String(prop)}] is readonly`);\n }\n const ori = (node as unknown as Record<string | symbol, unknown>)[prop];\n if(ori !== value) {\n (node as unknown as Record<string | symbol, unknown>)[prop] = value;\n this.mind._onNodeUpdated(node, prop as string, ori, value);\n }\n return true;\n }\n\n}\n\n","/**\n * JSON serializer for JsMind mind maps.\n *\n * @packageDocumentation\n */\nimport type { JmMindSerializer } from './serializer.ts';\nimport { JmMind } from '../model/mind.ts';\nimport { JmNode } from '../model/data/node.ts';\nimport { JmNodeContent } from '../model/data/node-content.ts';\nimport { JmEdge, type JmEdgeType } from '../model/data/edge.ts';\nimport { JsMindError } from '../common/error.ts';\nimport type { MindMetadata } from '../common/option.ts';\nimport type { JmNodeSide } from '../model/data/node.ts';\nimport type { JmNodeContentType } from '../model/data/node-content.ts';\nimport type { JmNodeStyle, JmLineStyle, JmStyle } from '../model/data/style.ts';\nimport { validateMindData, type JmValidationIssue, type JmValidationResult } from './validation.ts';\n\n/**\n * Format identifier written to every v2 data file.\n *\n * @public\n */\nexport const JSMIND_FORMAT_V2 = 'jsmind_v2';\n\n/**\n * Serialized node data structure.\n *\n * @public\n */\nexport interface SerializedNode {\n id: string;\n content: {\n type: JmNodeContentType;\n value: unknown;\n };\n parent: string | null;\n children: string[];\n folded: boolean;\n side: JmNodeSide;\n data: Record<string, unknown>;\n /** Visual overrides for the node. Absent when the node uses the theme as-is. */\n style?: JmNodeStyle;\n}\n\n/**\n * Serialized edge data structure.\n *\n * @public\n */\nexport interface SerializedEdge {\n id: string;\n sourceNodeId: string;\n targetNodeId: string;\n type: JmEdgeType;\n label: string | null;\n /** Visual style of the edge line. */\n style?: JmLineStyle;\n}\n\n/**\n * Serialized mind map data structure.\n *\n * @public\n */\nexport interface SerializedMindMap {\n /** Format identifier. Always `jsmind_v2` for data written by this version. */\n format?: string;\n /** Style declaration: which theme to inherit from, plus overrides. */\n style?: JmStyle;\n meta: MindMetadata;\n root: string;\n nodes: Record<string, SerializedNode>;\n edges: Record<string, SerializedEdge>;\n}\n\n/**\n * JSON serializer for mind maps.\n *\n * @public\n */\nexport class JmMindJsonSerializer implements JmMindSerializer {\n /**\n * Gets the format name this serializer supports.\n *\n * @returns The format name.\n */\n getFormatName(): string {\n return 'json';\n }\n\n /**\n * Serializes a mind map to JSON format.\n *\n * @param mind - The mind map to serialize.\n * @returns The serialized JSON data.\n * @throws {@link JsMindError} If the mind map is not provided.\n */\n serialize(mind: JmMind): SerializedMindMap {\n if (!mind) {\n throw new JsMindError('Mind map is required for serialization');\n }\n\n const serializedData: SerializedMindMap = {\n format: JSMIND_FORMAT_V2,\n meta: mind.meta,\n root: mind._root.id,\n nodes: {},\n edges: {}\n };\n\n if (mind.style !== undefined) {\n serializedData.style = mind.style;\n }\n\n // Serialize all nodes\n Object.values(mind._nodes).forEach(node => {\n serializedData.nodes[node.id] = this._serializeNode(node);\n });\n\n // Serialize all additional edges\n Object.values(mind._edges).forEach(edge => {\n serializedData.edges[edge.id] = this._serializeEdge(edge);\n });\n\n return serializedData;\n }\n\n /**\n * Deserializes JSON data to a mind map.\n *\n * @param data - The JSON data to deserialize.\n * @returns The deserialized mind map.\n * @throws {@link JsMindError} If the JSON data format is invalid.\n */\n deserialize(data: SerializedMindMap): JmMind {\n const result = this.check(data);\n if (!result.valid) {\n throw new JsMindError(\n `Invalid JSON data format: ${summarise(result.errors)}`,\n { errors: result.errors },\n result.errors[0].code\n );\n }\n\n // Create mind map with metadata and options\n const mind = new JmMind(data.meta, { rootNodeId: data.root });\n if (data.style !== undefined) {\n mind.style = data.style;\n }\n\n // Restore nodes\n Object.values(data.nodes).forEach((nodeData: SerializedNode) => {\n const node = this._deserializeNode(nodeData);\n mind._nodes[node.id] = node;\n });\n\n // Restore additional edges\n if (data.edges) {\n Object.values(data.edges).forEach((edgeData: SerializedEdge) => {\n const edge = this._deserializeEdge(edgeData);\n mind._edges[edge.id] = edge;\n });\n }\n\n // Restore root\n mind._root = mind._nodes[data.root];\n\n // Restore parent-child relationships\n this._restoreNodeRelationships(mind, data);\n\n return mind;\n }\n\n /**\n * Validates if the data can be deserialized by this serializer.\n *\n * @param data - The data to validate.\n * @returns True if the data is valid for this format.\n */\n validate(data: unknown): data is SerializedMindMap {\n return this.check(data).valid;\n }\n\n /**\n * Validates data and returns every problem found.\n *\n * @remarks\n * Use this instead of `validate` when the caller needs to know *why* data\n * was rejected. Each issue carries a stable `code`, a `path` into the\n * document, and a message written for humans.\n *\n * @param data - The data to validate.\n * @returns Every issue found; `valid` is true only when there are none.\n */\n check(data: unknown): JmValidationResult {\n return validateMindData(data);\n }\n\n /**\n * Serializes a single node.\n *\n * @private\n * @param node - The node to serialize.\n * @returns The serialized node data.\n */\n _serializeNode(node: JmNode): SerializedNode {\n return {\n id: node.id,\n content: {\n type: node.content.type,\n value: node.content.value\n },\n parent: node.parent ? node.parent.id : null,\n children: node.children.map(child => child.id),\n folded: node.folded,\n side: node.side,\n data: { ...node.data },\n ...(node.style ? { style: copyNodeStyle(node.style) } : {})\n };\n }\n\n /**\n * Deserializes a single node.\n *\n * @private\n * @param nodeData - The node data to deserialize.\n * @returns The deserialized node.\n */\n _deserializeNode(nodeData: SerializedNode): JmNode {\n const content = new JmNodeContent(nodeData.content.type, nodeData.content.value);\n const node = new JmNode(nodeData.id, content);\n\n node.folded = nodeData.folded;\n node.side = nodeData.side;\n node.data = { ...nodeData.data };\n if (nodeData.style) {\n node.style = copyNodeStyle(nodeData.style);\n }\n\n return node;\n }\n\n /**\n * Serializes a single edge.\n *\n * @private\n * @param edge - The edge to serialize.\n * @returns The serialized edge data.\n */\n _serializeEdge(edge: JmEdge): SerializedEdge {\n return {\n id: edge.id,\n sourceNodeId: edge.sourceNodeId,\n targetNodeId: edge.targetNodeId,\n type: edge.type,\n label: edge.label,\n ...(edge.style ? { style: copyLineStyle(edge.style) } : {})\n };\n }\n\n /**\n * Deserializes a single edge.\n *\n * @private\n * @param edgeData - The edge data to deserialize.\n * @returns The deserialized edge.\n */\n _deserializeEdge(edgeData: SerializedEdge): JmEdge {\n const edge = new JmEdge(\n edgeData.id,\n edgeData.sourceNodeId,\n edgeData.targetNodeId,\n edgeData.type,\n edgeData.label\n );\n if (edgeData.style) {\n edge.style = copyLineStyle(edgeData.style);\n }\n return edge;\n }\n\n /**\n * Restores parent-child relationships between nodes.\n *\n * @private\n * @param mind - The mind map to restore relationships for.\n * @param data - The serialized data containing parent and children information.\n */\n _restoreNodeRelationships(mind: JmMind, data: SerializedMindMap): void {\n // Restore parent relationships\n Object.values(data.nodes).forEach((nodeData: SerializedNode) => {\n const node = mind._nodes[nodeData.id];\n if (nodeData.parent !== null) {\n const parentNode = mind._nodes[nodeData.parent];\n if (parentNode) {\n node.parent = parentNode;\n }\n } else {\n node.parent = null;\n }\n });\n\n // Restore children relationships\n Object.values(data.nodes).forEach((nodeData: SerializedNode) => {\n const node = mind._nodes[nodeData.id];\n node.children = nodeData.children\n .map((childId: string) => mind._nodes[childId])\n .filter((child: JmNode | undefined) => child !== undefined) as JmNode[];\n });\n }\n}\n\n/**\n * Summarises validation issues into one readable sentence.\n *\n * @remarks\n * The first issue carries the most useful detail; the remaining count tells\n * the reader whether to expect more. Full detail is in `error.data.errors`.\n *\n * @param errors - Issues to summarise.\n * @returns A single human-readable line.\n */\nfunction summarise(errors: JmValidationIssue[]): string {\n const first = errors[0];\n const rest = errors.length - 1;\n const suffix = rest > 0 ? ` (and ${rest} more)` : '';\n return `${first.code} at ${first.path || '<root>'}: ${first.message}${suffix}`;\n}\n\n/**\n * Copies a node style so the serialized snapshot does not share nested objects\n * with the live model.\n *\n * @remarks\n * `incoming` is the only nested field, so a two-level copy covers the whole\n * structure. Sharing it would let a later edit to `node.style.incoming` reach\n * back into data that was already serialized.\n *\n * @param style - The style to copy.\n * @returns A detached copy.\n */\nfunction copyNodeStyle(style: JmNodeStyle): JmNodeStyle {\n return style.incoming\n ? { ...style, incoming: copyLineStyle(style.incoming) }\n : { ...style };\n}\n\n/**\n * Copies a line style.\n *\n * @remarks\n * `JmLineStyle` holds scalars only, so a spread is a full copy. Kept as a\n * named function so node styles and edge styles go through one path — if the\n * shape ever grows a nested field, only this function needs to change.\n *\n * @param style - The line style to copy.\n * @returns A detached copy.\n */\nfunction copyLineStyle(style: JmLineStyle): JmLineStyle {\n return { ...style };\n}\n","/**\n * Rendering of validation issues for humans.\n *\n * @packageDocumentation\n */\n\nimport type { JmValidationIssue } from '../serialization/validation.ts';\n\n/**\n * Renders validation issues as an indented block.\n *\n * @remarks\n * Code first so a reader can scan a column of caps-lock tokens and find the one\n * that matters, path second because that is what they need to act on.\n *\n * @param errors - Issues to render.\n * @returns One block of text, no trailing newline.\n */\nexport function formatIssues(errors: JmValidationIssue[]): string {\n return errors\n .map(issue => ` ${issue.code} ${issue.path || '<root>'}\\n ${issue.message}`)\n .join('\\n');\n}\n","/**\n * Load → mutate → write → verify → roll back, shared by every mutating\n * command.\n *\n * @remarks\n * The post-write validation is not optional. A CLI that can silently corrupt a\n * file is worse than no CLI: an agent would keep using the damaged document.\n * Every mutation therefore runs the full integrity check against what actually\n * landed on disk and restores the original bytes when it fails.\n *\n * @packageDocumentation\n */\n\nimport { JmMindJsonSerializer, type SerializedMindMap } from '../serialization/json.ts';\nimport { validateMindData } from '../serialization/validation.ts';\nimport { formatIssues } from './format.ts';\nimport type { JmMind } from '../model/mind.ts';\nimport { readJsonFile, renderJson, writeJsonFile, restoreFile, type WriteOptions } from './io.ts';\nimport { dataError } from './exit.ts';\nimport { readFileSync } from 'node:fs';\n\n/**\n * Runs one mutating command against a file.\n *\n * @remarks\n * Three protections apply: `dryRun` never touches the file, `backup` keeps a\n * `.bak`, and `output` redirects the write. When none are set the input file is\n * rewritten in place, which is the agent's normal workflow.\n *\n * @param file - Input mind map.\n * @param options - Dry-run / backup / output settings.\n * @param mutate - Receives the loaded mind map, returns the value to report.\n * @returns The reported value, with the exit code assumed to be 0.\n * @throws {@link CliError} With `InvalidData` when the file or result does not\n * validate, or `IoError` when the file cannot be read or written.\n */\nexport function runMutation<T>(\n file: string,\n options: WriteOptions,\n mutate: (mind: JmMind) => T\n): T {\n const serializer = new JmMindJsonSerializer();\n\n // Refuse to operate on a document that is already broken: any change we make\n // would be layered on top of existing damage and the post-write check would\n // blame our edit.\n const original = readJsonFile(file);\n const before = validateMindData(original);\n if (!before.valid) {\n throw dataError(\n `Refusing to modify ${file}: it does not validate.\\n${formatIssues(before.errors)}`\n );\n }\n\n const mind = serializer.deserialize(original as SerializedMindMap);\n const value = mutate(mind);\n\n const next = serializer.serialize(mind);\n const target = options.output ?? file;\n\n if (options.dryRun) {\n process.stdout.write(`${renderJson(next)}`);\n return value;\n }\n\n // Capture the exact bytes before writing so a failed check can put them back.\n let previous: string | null = null;\n try {\n previous = readFileSync(target, 'utf8');\n } catch {\n // Target did not exist (--output to a new path). Nothing to restore.\n }\n\n writeJsonFile(next, target, options);\n\n const after = validateMindData(next);\n if (!after.valid) {\n if (previous !== null) {\n restoreFile(target, previous);\n }\n throw dataError(\n `Validation failed after write, ${previous === null ? 'new file left in place' : 'rolled back'}:\\n` +\n `${formatIssues(after.errors)}\\nFile unchanged.`\n );\n }\n\n return value;\n}\n\n","/**\n * Helpers shared by more than one command group.\n *\n * @remarks\n * Only things that are genuinely identical between groups live here. When two\n * call sites look alike but answer different questions, they stay separate —\n * merging those is how a shared helper turns into a function with a mode flag.\n *\n * @packageDocumentation\n */\n\nimport { JmNodeSide } from '../model/data/node.ts';\nimport { JmNodeContent } from '../model/data/node-content.ts';\nimport type { JmNode } from '../model/data/node.ts';\nimport type { JmNodeStyle } from '../model/data/style.ts';\nimport type { JmMindJsonSerializer, SerializedMindMap } from '../serialization/json.ts';\nimport { JsMindError } from '../common/error.ts';\nimport type { JmValidationIssue } from '../serialization/validation.ts';\nimport { formatIssues } from './format.ts';\nimport { dataError, usageError } from './exit.ts';\n\n/**\n * Synonyms accepted for each side, and the value they normalise to.\n *\n * @remarks\n * The model deliberately names its sides A and B rather than left and right, so\n * the values stay usable if a vertical layout ever arrives. The command line\n * cannot be that abstract — nobody types `--side b` — so the words live here, in\n * one table, and every accepted spelling normalises to the same numeric value.\n *\n * When a vertical layout lands, `up` and `down` are added to this table pointing\n * at the existing values. The words change; the data does not.\n *\n * Current mapping, per the JmNodeSide comments in the model:\n *\n * | word | value | model name |\n * |--------|-------|------------|\n * | left | -1 | SideB |\n * | center | 0 | Center |\n * | right | 1 | SideA |\n */\nconst SIDE_SYNONYMS: Record<string, JmNodeSide> = {\n left: JmNodeSide.SideB,\n center: JmNodeSide.Center,\n right: JmNodeSide.SideA,\n};\n\n/**\n * Every spelling the `--side` option accepts.\n *\n * @remarks\n * Derived from the table rather than restated, so an error message cannot drift\n * away from what the parser actually accepts.\n */\nconst SIDE_WORDS = Object.keys(SIDE_SYNONYMS).join(', ');\n\n/**\n * Converts a `--side` value to the numeric enum.\n *\n * @param raw - Value from the command line.\n * @returns The normalised side.\n * @throws {@link CliError} With `Usage` for an unknown name.\n */\nexport function parseSide(raw: string): JmNodeSide {\n const value = SIDE_SYNONYMS[raw];\n if (value === undefined) {\n throw usageError(`--side must be one of ${SIDE_WORDS}, got \"${raw}\"`);\n }\n return value;\n}\n\n/**\n * Converts a numeric side to its display word — the inverse of {@link parseSide}.\n *\n * @param side - The raw value from a node.\n * @returns `\"left\"`, `\"center\"`, or `\"right\"`.\n * @remarks\n * The model stores sides as −1 / 0 / 1 so a vertical layout can reuse the same\n * values with different words later. This function is the place that picks the\n * current word, and it is deliberately the only place: if a vertical layout ever\n * lands, changing these three strings changes every caller at once.\n */\nexport function formatSide(side: JmNodeSide): string {\n if (side === JmNodeSide.SideB) return 'left';\n if (side === JmNodeSide.SideA) return 'right';\n return 'center';\n}\n\n/**\n * Writes a command result in the shape the caller asked for.\n *\n * @param asJson - Emit JSON instead of prose.\n * @param prose - Human-readable summary.\n * @param payload - Machine-readable result.\n */\nexport function report(asJson: boolean, prose: string, payload: Record<string, unknown>): void {\n process.stdout.write(asJson ? `${JSON.stringify(payload, null, 2)}\\n` : `${prose}\\n`);\n}\n\n/**\n * Describes a node's style block for output.\n *\n * @param style - The node's overrides, if any.\n * @returns A plain object, or `null` when the node overrides nothing.\n * @remarks\n * A style block records only what differs from the theme, and that shape is\n * carried through unchanged: a field the caller never set is absent here too.\n * Reporting defaults would make every described node longer for information the\n * theme already implies, and this output is read on every discovery step.\n */\nexport function describeStyle(style: JmNodeStyle | undefined): Record<string, unknown> | null {\n return style === undefined ? null : (structuredClone(style) as Record<string, unknown>);\n}\n\n/**\n * Describes a node for output.\n *\n * @remarks\n * `parent` and `children` hold live JmNode references, not ids. Serialising a\n * node as-is walks straight back into the tree and blows the stack, so every id\n * crossing this boundary is extracted explicitly.\n *\n * `side` is emitted as the word that `parseSide()` accepts (`\"left\"` / `\"center\"`\n * / `\"right\"`), not the internal number, so an agent can copy the value straight\n * into `jsmind node set-side`.\n *\n * `folded` appears only when `true` — every node defaults to unfolded, and\n * reporting a key the caller never set would add noise to every response.\n *\n * `style` is included only when the node overrides something. A command can set\n * it, so a discovery command has to be able to show it - otherwise the only way\n * to confirm a style change is to render an image and look, which costs a vision\n * call per check and is unreliable at that.\n *\n * @param node - Node to describe.\n * @returns Plain object for output.\n */\nexport function describeNode(node: JmNode): Record<string, unknown> {\n const described: Record<string, unknown> = {\n id: node.id,\n text: node.content.value,\n parent: node.parent === null ? null : node.parent.id,\n children: node.children.map(child => child.id),\n side: formatSide(node.side),\n };\n // folded only when the node is collapsed — the default is false for every\n // node and reporting it would add a key the caller never asked for.\n if (node.folded) {\n described.folded = true;\n }\n const style = describeStyle(node.style);\n if (style !== null) {\n described.style = style;\n }\n return described;\n}\n\n/**\n * Describes an edge for output.\n *\n * @param edge - Edge to describe.\n * @returns Plain object for output.\n */\nexport function describeEdge(edge: {\n id: string;\n sourceNodeId: string;\n targetNodeId: string;\n type: string;\n label: string | null;\n}): Record<string, unknown> {\n return {\n id: edge.id,\n source: edge.sourceNodeId,\n target: edge.targetNodeId,\n type: edge.type,\n label: edge.label,\n };\n}\n\n/**\n * Loads a mind map, reporting structural faults as data errors.\n *\n * @remarks\n * `deserialize()` already validates — it calls the same `validateMindData()`\n * internally — so validating here first would run the check twice. Measured at\n * 5000 nodes the duplicate pass costs about as much as the real one, roughly\n * 40% of the load time. The catch below is not defensive padding: it is the\n * only way to keep a single validation while still converting the error.\n *\n * Every read path goes through here so a structural fault surfaces as\n * `InvalidData` (exit 1) rather than escaping as a raw `JsMindError` and landing\n * in the generic runtime branch (exit 3).\n *\n * @param serializer - Serializer to use.\n * @param doc - Parsed document.\n * @param file - Path, for the error message.\n * @returns The loaded mind map.\n * @throws {@link CliError} With `InvalidData` when the document is invalid.\n */\nexport function loadMindOrThrow(\n serializer: JmMindJsonSerializer,\n doc: unknown,\n file: string\n): ReturnType<JmMindJsonSerializer['deserialize']> {\n try {\n return serializer.deserialize(doc as SerializedMindMap);\n } catch (err) {\n if (err instanceof JsMindError) {\n const issues = (err.data as { errors?: JmValidationIssue[] }).errors;\n throw dataError(`${file} does not validate:\\n${formatIssues(issues ?? [])}`);\n }\n throw err;\n }\n}\n\n/**\n * Builds a text content object for a new node.\n *\n * @param text - Label text.\n * @returns A JmNodeContent of type text.\n */\nexport function textContent(text: string): JmNodeContent {\n return JmNodeContent.createText(text);\n}\n","/**\n * `jsmind mind *` — structure and edge commands.\n *\n * @remarks\n * Each command is a thin wrapper over a `JmMind` method. Locators are ids only:\n * pointing at a node by path or by text is deliberately not offered, because\n * both are ambiguous in a document the agent has not read.\n *\n * @packageDocumentation\n */\n\nimport { JmMindJsonSerializer } from '../../serialization/json.ts';\nimport type { JmNodeSide } from '../../model/data/node.ts';\nimport { JmNodeContent } from '../../model/data/node-content.ts';\nimport { JmEdgeType } from '../../model/data/edge.ts';\nimport type { JmMind } from '../../model/mind.ts';\nimport { runMutation } from '../mutate.ts';\nimport {\n optionalIntOption,\n optionalOption,\n readJsonFile,\n requireOption,\n type WriteOptions,\n} from '../io.ts';\nimport { CliExit, usageError, dataError } from '../exit.ts';\nimport { parseSide, report, describeNode, describeEdge, loadMindOrThrow } from '../shared.ts';\n\n/** Subcommands this group understands. */\nconst SUBCOMMANDS = [\n 'find',\n 'add-child',\n 'add-node',\n 'move',\n 'remove-node',\n 'add-edge',\n 'remove-edge',\n 'list-edges',\n] as const;\n\n\n/**\n * Runs a `mind` subcommand.\n *\n * @param file - Mind map file.\n * @param subcommand - Which subcommand.\n * @param values - Parsed options.\n * @param options - Dry-run / backup / output settings.\n * @returns Exit code.\n */\nexport function runMind(\n file: string,\n subcommand: string,\n values: Record<string, unknown>,\n options: WriteOptions\n): number {\n if (!(SUBCOMMANDS as readonly string[]).includes(subcommand)) {\n throw usageError(\n `Unknown mind subcommand: ${subcommand}\\nKnown: ${SUBCOMMANDS.join(', ')}`\n );\n }\n\n const asJson = values.json === true;\n\n // Read-only subcommands do not need the mutation pipeline.\n if (subcommand === 'find') {\n const nodeId = requireOption(values, 'node-id');\n const doc = readJsonFile(file);\n const mind = loadMindOrThrow(new JmMindJsonSerializer(), doc, file);\n const node = mind.findNodeById(nodeId);\n if (node === null) {\n throw dataError(`No node with id \"${nodeId}\" in ${file}`);\n }\n process.stdout.write(`${JSON.stringify(describeNode(node), null, 2)}\\n`);\n return CliExit.Ok;\n }\n\n if (subcommand === 'list-edges') {\n const nodeId = requireOption(values, 'node-id');\n const doc = readJsonFile(file);\n const mind = loadMindOrThrow(new JmMindJsonSerializer(), doc, file);\n if (mind.findNodeById(nodeId) === null) {\n throw dataError(`No node with id \"${nodeId}\" in ${file}`);\n }\n const edges = mind.getEdges(nodeId);\n process.stdout.write(`${JSON.stringify(edges.map(describeEdge), null, 2)}\\n`);\n return CliExit.Ok;\n }\n\n switch (subcommand) {\n case 'add-child': {\n const parentId = requireOption(values, 'parent-id');\n const text = requireOption(values, 'text');\n const created = runMutation(file, options, (mind: JmMind) => {\n const node = mind.addChildNode(text, parentId);\n return node.id;\n });\n report(asJson, `added ${created} under ${parentId}`, { id: created });\n return CliExit.Ok;\n }\n\n case 'add-node': {\n const parentId = requireOption(values, 'parent-id');\n const text = requireOption(values, 'text');\n const position = optionalIntOption(values, 'position');\n const sideRaw = optionalOption(values, 'side');\n const created = runMutation(file, options, (mind: JmMind) => {\n const dest: { parentId: string; position?: number; side?: JmNodeSide } = {\n parentId,\n };\n if (position !== undefined) {\n dest.position = position;\n }\n if (sideRaw !== undefined) {\n dest.side = parseSide(sideRaw);\n }\n const node = mind.addNode(JmNodeContent.createText(text), dest);\n return node.id;\n });\n report(asJson, `added ${created} under ${parentId}`, { id: created });\n return CliExit.Ok;\n }\n\n case 'move': {\n const nodeId = requireOption(values, 'node-id');\n const parentId = requireOption(values, 'parent-id');\n const position = optionalIntOption(values, 'position');\n runMutation(file, options, (mind: JmMind) => {\n const dest: { parentId: string; position?: number } = { parentId };\n if (position !== undefined) {\n dest.position = position;\n }\n mind.moveNode(nodeId, dest);\n return nodeId;\n });\n report(asJson, `moved ${nodeId} under ${parentId}`, { id: nodeId, parent: parentId });\n return CliExit.Ok;\n }\n\n case 'remove-node': {\n const nodeId = requireOption(values, 'node-id');\n runMutation(file, options, (mind: JmMind) => {\n mind.removeNode(nodeId);\n return nodeId;\n });\n report(asJson, `removed ${nodeId}`, { id: nodeId });\n return CliExit.Ok;\n }\n\n case 'add-edge': {\n const sourceId = requireOption(values, 'source-id');\n const targetId = requireOption(values, 'target-id');\n const typeRaw = optionalOption(values, 'type') ?? JmEdgeType.Link;\n const label = optionalOption(values, 'label') ?? null;\n const created = runMutation(file, options, (mind: JmMind) => {\n const edge = mind.addEdge(\n sourceId,\n targetId,\n typeRaw as JmEdgeType,\n label === null ? undefined : { label }\n );\n return edge.id;\n });\n report(asJson, `added edge ${created}`, { id: created });\n return CliExit.Ok;\n }\n\n case 'remove-edge': {\n const edgeId = requireOption(values, 'edge-id');\n runMutation(file, options, (mind: JmMind) => {\n if (!mind.removeEdge(edgeId)) {\n throw dataError(`No edge with id \"${edgeId}\" in ${file}`);\n }\n return edgeId;\n });\n report(asJson, `removed edge ${edgeId}`, { id: edgeId });\n return CliExit.Ok;\n }\n\n default:\n throw usageError(`Unhandled mind subcommand: ${subcommand}`);\n }\n}\n\n/**\n * Describes the `mind` command group for `--help`.\n */\nexport const mindHelp = `jsmind mind <subcommand> <file> [options]\n\nStructure and edges (mirrors JmMind methods). Locators are ids only.\n\n find --node-id <id> Show one node\n list-edges --node-id <id> Edges touching a node\n add-child --parent-id <id> --text <text> Add a leaf (JmMind.addChildNode)\n add-node --parent-id <id> --text <text> Add with placement (JmMind.addNode)\n [--position <n>] [--side left|center|right]\n move --node-id <id> --parent-id <id> Reparent (JmMind.moveNode)\n [--position <n>]\n remove-node --node-id <id> Remove the node, its whole\n subtree, and every edge touching any of them\n add-edge --source-id <id> --target-id <id> Add a relation (JmMind.addEdge)\n [--type link] [--label <text>]\n remove-edge --edge-id <id> Remove a relation\n\nEvery mutating subcommand validates the result and rolls back on failure.`;\n","/**\n * Reading, writing and deleting a nested field by path.\n *\n * @remarks\n * A command that lets a caller set one field of a nested object needs the same\n * three operations whatever the object is: set a value somewhere down a path,\n * remove one, and report what is there. Keeping those here rather than beside\n * one command means the next command that reaches into a nested field does not\n * write them again - and does not have to know, as this module does not, which\n * fields exist.\n *\n * Paths are plain string arrays. `['incoming', 'color']` is `style.incoming.color`.\n * Nothing here assumes a depth or a name.\n *\n * @packageDocumentation\n */\n\n/**\n * A route into a nested object.\n *\n * @public\n */\nexport type FieldPath = readonly string[];\n\n/**\n * Turns a command-line flag name into a path.\n *\n * @param flag - Flag name without leading dashes, e.g. `incoming.color` or\n * `font-size`.\n * @returns The path, e.g. `['incoming', 'color']` or `['fontSize']`.\n * @remarks\n * Dots mark a level, dashes join the words of one level. That split means the\n * flag name is the only place a field's location is written down: the path is\n * derived, so the two cannot drift apart.\n */\nexport function flagToPath(flag: string): FieldPath {\n return flag.split('.').map(segment => segment.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase()));\n}\n\n/**\n * Renders a path as a flag name.\n *\n * @param path - Route into an object.\n * @returns The flag name that addresses it.\n */\nexport function pathToFlag(path: FieldPath): string {\n return path\n .map(segment => segment.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`))\n .join('.');\n}\n\n/**\n * Reads the value at a path.\n *\n * @param target - Object to read from.\n * @param path - Route into it.\n * @returns The value, or `undefined` when any level is missing.\n */\nexport function getAtPath(target: unknown, path: FieldPath): unknown {\n let current: unknown = target;\n for (const key of path) {\n if (current === null || typeof current !== 'object') {\n return undefined;\n }\n current = (current as Record<string, unknown>)[key];\n }\n return current;\n}\n\n/**\n * Writes a value at a path, creating intermediate objects.\n *\n * @param target - Object to write into, mutated in place.\n * @param path - Route into it.\n * @param value - Value to store.\n * @remarks\n * Intermediate objects are created as plain objects. A path that runs through a\n * non-object would have to overwrite it, so it stops instead: that is a\n * contradiction in the caller's data, not something to paper over.\n */\nexport function setAtPath(target: Record<string, unknown>, path: FieldPath, value: unknown): void {\n if (path.length === 0) {\n throw new Error('setAtPath needs a non-empty path');\n }\n let current = target;\n for (const key of path.slice(0, -1)) {\n const next = current[key];\n if (next === undefined) {\n const created: Record<string, unknown> = {};\n current[key] = created;\n current = created;\n continue;\n }\n if (next === null || typeof next !== 'object') {\n throw new Error(`Cannot descend into \"${key}\": it holds a ${typeof next}, not an object`);\n }\n current = next as Record<string, unknown>;\n }\n current[path[path.length - 1]] = value;\n}\n\n/**\n * Removes the value at a path.\n *\n * @param target - Object to modify, mutated in place.\n * @param path - Route into it.\n * @returns Whether anything was removed.\n * @remarks\n * Intermediate objects left empty by the removal are dropped as well. Without\n * that, clearing the last field of a nested block leaves `{ incoming: {} }`\n * behind, which means the same as absent but does not serialise to nothing.\n */\nexport function deleteAtPath(target: Record<string, unknown>, path: FieldPath): boolean {\n if (path.length === 0) {\n return false;\n }\n\n const chain: Record<string, unknown>[] = [target];\n let current: unknown = target;\n for (const key of path.slice(0, -1)) {\n if (current === null || typeof current !== 'object') {\n return false;\n }\n current = (current as Record<string, unknown>)[key];\n if (current === null || typeof current !== 'object') {\n return false;\n }\n chain.push(current as Record<string, unknown>);\n }\n\n const leaf = path[path.length - 1];\n const holder = chain[chain.length - 1];\n if (!(leaf in holder)) {\n return false;\n }\n delete holder[leaf];\n if (path.length === 1) {\n return true;\n }\n\n // Walk back up dropping containers this removal emptied.\n for (let i = chain.length - 1; i > 0; i -= 1) {\n if (Object.keys(chain[i]).length > 0) {\n break;\n }\n delete chain[i - 1][path[i - 1]];\n }\n return true;\n}\n","/**\n * `jsmind node *` — node attribute commands.\n *\n * @remarks\n * These map to `JmNode`'s writable fields (`content` / `folded` / `side` /\n * `style`), not to `JmMind` methods. That split is not cosmetic: `id`,\n * `parent` and `children` are on the model's readonly list, so moving a node or\n * changing its parent goes through `mind` instead. Everything here is a plain\n * field assignment.\n *\n * @packageDocumentation\n */\n\nimport { JmNodeContent } from '../../model/data/node-content.ts';\nimport type { JmMind } from '../../model/mind.ts';\nimport {\n JmFontWeight,\n JmLineCurve,\n JmLinePattern,\n JmTone,\n type JmNodeStyle,\n} from '../../model/data/style.ts';\nimport { runMutation } from '../mutate.ts';\nimport { enumOption, numberOption, requireOption, type WriteOptions } from '../io.ts';\nimport { describeStyle, parseSide, report } from '../shared.ts';\nimport { deleteAtPath, flagToPath, setAtPath } from '../field-path.ts';\nimport { CliExit, usageError, dataError } from '../exit.ts';\n\n/** Subcommands this group understands. */\nconst SUBCOMMANDS = ['set-text', 'set-folded', 'set-side', 'set-style'] as const;\n\n/**\n * Parses a boolean flag value written as a word.\n *\n * @param raw - `true` / `false` as given on the command line.\n * @returns The boolean.\n * @throws {@link CliError} With `Usage` for anything else.\n */\nfunction parseBoolean(raw: string): boolean {\n if (raw === 'true') {\n return true;\n }\n if (raw === 'false') {\n return false;\n }\n throw usageError(`Expected true or false, got \"${raw}\"`);\n}\n\n/**\n * Accepted values, read from the model's own enums.\n *\n * @remarks\n * Not restated here. A hand-written copy of these lists drifts: the first\n * version of this file listed six tones while `JmTone` had seven, so `--tone\n * accent` was rejected as a bad value when it was perfectly legal. Nothing\n * failed loudly - the missing entry only showed up when someone used it.\n */\nconst TONE_WORDS = Object.values(JmTone);\nconst FONT_WEIGHT_WORDS = Object.values(JmFontWeight);\nconst LINE_PATTERN_WORDS = Object.values(JmLinePattern);\nconst LINE_CURVE_WORDS = Object.values(JmLineCurve);\n\n/**\n * One style field reachable from the command line.\n *\n * @remarks\n * The flag name is the only place a field's location is written down. Its path\n * into {@link JmNodeStyle} is derived by {@link flagToPath}, so a field cannot\n * be declared at one place and addressed at another.\n */\ninterface StyleField {\n /** Flag name without leading dashes. Dots mark a level. */\n flag: string;\n /** Validates and converts the raw argument. */\n parse: (raw: unknown) => unknown;\n}\n\n/** Every style field the command accepts. */\nconst STYLE_FIELDS: StyleField[] = [\n { flag: 'tone', parse: raw => enumOption(raw, JmTone.Default, TONE_WORDS, 'tone') },\n { flag: 'background', parse: raw => String(raw) },\n { flag: 'color', parse: raw => String(raw) },\n { flag: 'border-color', parse: raw => String(raw) },\n { flag: 'border-width', parse: raw => numberOption(raw, 1, 'border-width') },\n {\n flag: 'border-style',\n parse: raw => enumOption(raw, JmLinePattern.Solid, LINE_PATTERN_WORDS, 'border-style'),\n },\n { flag: 'font-size', parse: raw => numberOption(raw, 1, 'font-size') },\n {\n flag: 'font-weight',\n parse: raw => enumOption(raw, JmFontWeight.Normal, FONT_WEIGHT_WORDS, 'font-weight'),\n },\n { flag: 'incoming.color', parse: raw => String(raw) },\n { flag: 'incoming.width', parse: raw => numberOption(raw, 1, 'incoming-width') },\n {\n flag: 'incoming.pattern',\n parse: raw => enumOption(raw, JmLinePattern.Solid, LINE_PATTERN_WORDS, 'incoming.pattern'),\n },\n {\n flag: 'incoming.curve',\n parse: raw => enumOption(raw, JmLineCurve.Bezier, LINE_CURVE_WORDS, 'incoming.curve'),\n },\n];\n\n/**\n * Normalises a field name given to `--clear`.\n *\n * @param name - Name as typed: `incoming.color`, `font-size` or `fontSize`.\n * @returns The flag spelling this module compares against.\n * @remarks\n * Both spellings are natural at different moments - reading the file shows\n * `fontSize`, typing the command shows `--font-size` - so both are accepted\n * rather than making the user remember which one `--clear` wants.\n */\nfunction normalizeClearName(name: string): string {\n return name\n .trim()\n .split('.')\n .map(segment =>\n segment\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .toLowerCase()\n )\n .join('.');\n}\n\n/**\n * A validated instruction from the command line, ready to apply.\n *\n * @remarks\n * Parsing and applying are separated so an invalid argument fails before the\n * file is read. The split was not cosmetic: bad flags used to surface only\n * after the document had been loaded and a temporary copy made, which is wasted\n * work and, when the file is also missing, the wrong error.\n */\ninterface StylePatch {\n /** Drop every override on the node. Excludes the other two. */\n reset: boolean;\n /** Flags whose keys should be removed, restoring the theme's value. */\n clear: string[];\n /** Flags to set, already parsed and range-checked. */\n set: { flag: string; value: unknown }[];\n}\n\n/**\n * Validates the style flags and turns them into a patch.\n *\n * @param values - Parsed options.\n * @returns The patch to apply.\n * @throws {@link CliError} With `Usage` when the flags do not make sense.\n * @remarks\n * Touches no file. Every check here is about the arguments alone.\n */\nfunction parseStyleArgs(values: Record<string, unknown>): StylePatch {\n const set: StylePatch['set'] = [];\n for (const field of STYLE_FIELDS) {\n const raw = values[field.flag];\n if (raw === undefined) {\n continue;\n }\n set.push({ flag: field.flag, value: field.parse(raw) });\n }\n\n const clear: string[] = [];\n const clearRaw = values.clear;\n if (clearRaw !== undefined) {\n if (typeof clearRaw !== 'string') {\n throw usageError('--clear expects a comma-separated list of fields');\n }\n for (const name of clearRaw\n .split(',')\n .map(s => s.trim())\n .filter(s => s !== '')) {\n const normalized = normalizeClearName(name);\n if (!STYLE_FIELDS.some(f => f.flag === normalized)) {\n throw usageError(\n `--clear does not know \"${name}\". Known fields: ${STYLE_FIELDS.map(f => f.flag).join(', ')}`\n );\n }\n clear.push(normalized);\n }\n }\n\n // `--reset` is exhaustive: it says the node should carry no overrides at\n // all, so anything combined with it is either redundant or a contradiction.\n if (values.reset === true) {\n const conflicting = [...set.map(s => s.flag), ...(clear.length > 0 ? ['clear'] : [])];\n if (conflicting.length > 0) {\n throw usageError(\n `--reset clears every style field, so it cannot be combined with ${conflicting\n .map(f => `--${f}`)\n .join(', ')}`\n );\n }\n return { reset: true, clear: [], set: [] };\n }\n\n if (set.length === 0 && clear.length === 0) {\n throw usageError(\n `set-style needs at least one field, --clear or --reset.\\nFields: ${STYLE_FIELDS.map(f => `--${f.flag}`).join(', ')}`\n );\n }\n\n return { reset: false, clear, set };\n}\n\n/**\n * Applies a patch to a node's current style.\n *\n * @param current - The node's current style, if any.\n * @param patch - Validated instruction.\n * @returns The new style, or `undefined` when nothing should be stored.\n * @remarks\n * A style block records only what differs from the theme, so this never merges\n * against theme values - only against the node's own overrides. An empty result\n * becomes `undefined` rather than `{}`: both resolve identically, but only the\n * former serialises to nothing.\n */\nfunction applyStyle(current: JmNodeStyle | undefined, patch: StylePatch): JmNodeStyle | undefined {\n if (patch.reset) {\n return undefined;\n }\n\n const style: Record<string, unknown> =\n current === undefined ? {} : (structuredClone(current) as Record<string, unknown>);\n\n for (const flag of patch.clear) {\n deleteAtPath(style, flagToPath(flag));\n }\n for (const { flag, value } of patch.set) {\n setAtPath(style, flagToPath(flag), value);\n }\n\n return Object.keys(style).length === 0 ? undefined : (style as JmNodeStyle);\n}\n\n/**\n * Runs a `node` subcommand.\n *\n * @param file - Mind map file.\n * @param subcommand - Which subcommand.\n * @param values - Parsed options.\n * @param options - Dry-run / backup / output settings.\n * @returns Exit code.\n */\nexport function runNode(\n file: string,\n subcommand: string,\n values: Record<string, unknown>,\n options: WriteOptions\n): number {\n if (!(SUBCOMMANDS as readonly string[]).includes(subcommand)) {\n throw usageError(\n `Unknown node subcommand: ${subcommand}\\nKnown: ${SUBCOMMANDS.join(', ')}`\n );\n }\n\n const nodeId = requireOption(values, 'node-id');\n const asJson = values.json === true;\n\n switch (subcommand) {\n case 'set-text': {\n const text = requireOption(values, 'text');\n runMutation(file, options, (mind: JmMind) => {\n const node = mind.findNodeById(nodeId);\n if (node === null) {\n throw dataError(`No node with id \"${nodeId}\" in ${file}`);\n }\n node.content = new JmNodeContent(node.content.type, text);\n return nodeId;\n });\n report(asJson, `set text of ${nodeId}`, { id: nodeId, text });\n return CliExit.Ok;\n }\n\n case 'set-folded': {\n const raw = requireOption(values, 'folded');\n const folded = parseBoolean(raw);\n runMutation(file, options, (mind: JmMind) => {\n const node = mind.findNodeById(nodeId);\n if (node === null) {\n throw dataError(`No node with id \"${nodeId}\" in ${file}`);\n }\n node.folded = folded;\n return nodeId;\n });\n report(asJson, `set folded of ${nodeId} to ${folded}`, { id: nodeId, folded });\n return CliExit.Ok;\n }\n\n case 'set-side': {\n const raw = requireOption(values, 'side');\n const side = parseSide(raw);\n runMutation(file, options, (mind: JmMind) => {\n const node = mind.findNodeById(nodeId);\n if (node === null) {\n throw dataError(`No node with id \"${nodeId}\" in ${file}`);\n }\n node.side = side;\n return nodeId;\n });\n report(asJson, `set side of ${nodeId} to ${raw}`, { id: nodeId, side: raw });\n return CliExit.Ok;\n }\n\n case 'set-style': {\n // Validate before touching the file: a bad flag should not depend on\n // whether the document happens to load.\n const patch = parseStyleArgs(values);\n // Report what the mutation produced, not the arguments: `--clear` and\n // `--reset` remove fields, so the result is not derivable from the\n // flags. Reading the file again to find out would also be wrong under\n // --dry-run, where nothing was written and the reread returns the old\n // value.\n const applied = runMutation(file, options, (mind: JmMind) => {\n const node = mind.findNodeById(nodeId);\n if (node === null) {\n throw dataError(`No node with id \"${nodeId}\" in ${file}`);\n }\n node.style = applyStyle(node.style, patch);\n return describeStyle(node.style);\n });\n report(\n asJson,\n applied === null\n ? `cleared style of ${nodeId}`\n : `set style of ${nodeId}: ${JSON.stringify(applied)}`,\n { id: nodeId, style: applied }\n );\n return CliExit.Ok;\n }\n\n default:\n throw usageError(`Unhandled node subcommand: ${subcommand}`);\n }\n}\n\n/**\n * Describes the `node` command group for `--help`.\n */\nexport const nodeHelp = `jsmind node <subcommand> <file> --node-id <id> [options]\n\nNode attributes (JmNode writable fields). Structure goes through \\`jsmind mind\\`.\n\n set-text --node-id <id> --text <text> Change the label\n set-folded --node-id <id> --folded true|false Collapse or expand\n set-side --node-id <id> --side left|center|right\n set-style --node-id <id> [style fields] Override the theme for one node\n\nset-style fields (any combination, applied in one write). A dot marks a level, so\n--incoming.color addresses \\`style.incoming.color\\`. Accepted values are read from\nthe model's own enums, so this list cannot fall behind them:\n\n --tone <value> ${TONE_WORDS.join(' | ')}\n --background <color>\n --color <color>\n --border-color <color>\n --border-width <number> positive\n --border-style <value> ${LINE_PATTERN_WORDS.join(' | ')}\n --font-size <number> positive\n --font-weight <value> ${FONT_WEIGHT_WORDS.join(' | ')}\n --incoming.color <color>\n --incoming.width <number> positive\n --incoming.pattern <value> ${LINE_PATTERN_WORDS.join(' | ')}\n --incoming.curve <value> ${LINE_CURVE_WORDS.join(' | ')}\n\nClearing, when the theme's value should come back:\n\n --clear <fields> Comma-separated field names in the same spelling\n --reset Drop every override on this node\n\nA style block records only what differs from the theme, so removing a key is what\nrestores the theme's value. There is no \\`unset\\` sentinel - an absent key means an\nabsent override. \\`--reset\\` cannot be combined with fields or \\`--clear\\`.\n\nColours are not checked beyond being strings; the theme accepts any CSS colour.\nTones, patterns and weights are checked here so a bad value names the flag you\ntyped rather than a JSON path.\n\nWhy the split: id, parent and children are readonly on the model, so they are only\nreachable through JmMind methods (\\`jsmind mind\\`). These fields are plain assignments.\n\nEvery subcommand validates the result and rolls back on failure.`;\n","/**\n * `jsmind context` — the agent's discovery step.\n *\n * @remarks\n * This is the only command allowed to fuzzy-match, because it is what an agent\n * runs before it knows any ids. Everything downstream takes ids only.\n *\n * Two constraints shape the output: ids come first so they can be copied\n * straight into the next command, and node text is flattened to one line so a\n * multi-line label cannot break the tree's shape.\n *\n * @packageDocumentation\n */\n\nimport { JmMindJsonSerializer } from '../../serialization/json.ts';\nimport type { JmNode } from '../../model/data/node.ts';\nimport type { JmMind } from '../../model/mind.ts';\nimport { readJsonFile } from '../io.ts';\nimport { describeStyle, formatSide, loadMindOrThrow } from '../shared.ts';\nimport { CliExit, dataError } from '../exit.ts';\n\n/** Default number of levels shown below the root. */\nconst DEFAULT_DEPTH = 2;\n\n/** Default truncation width for node text. */\nconst DEFAULT_MAX_TEXT = 40;\n\n/** Options accepted by the context command. */\nexport interface ContextOptions {\n file: string;\n focus?: string;\n depth: number;\n maxText: number;\n fullText: boolean;\n idsOnly: boolean;\n asJson: boolean;\n}\n\n/**\n * Collapses a label to a single line.\n *\n * @param text - Raw node text.\n * @returns Text with every run of whitespace squeezed to one space.\n */\nfunction flatten(text: string): string {\n return text.replace(/\\s+/g, ' ').trim();\n}\n\n/**\n * Truncates text to the configured width.\n *\n * @param text - Already flattened text.\n * @param maxText - Maximum characters.\n * @param fullText - When true, no truncation happens.\n * @returns The text, ending in an ellipsis when it was cut.\n */\nfunction clip(text: string, maxText: number, fullText: boolean): string {\n if (fullText || text.length <= maxText) {\n return text;\n }\n // -1 so the ellipsis is inside the budget rather than on top of it.\n return `${text.slice(0, Math.max(0, maxText - 1))}…`;\n}\n\n/**\n * Reads a node's label as a string.\n *\n * @param node - Node to read.\n * @returns The text, or an empty string for non-text content.\n */\nfunction textOf(node: JmNode): string {\n const value = node.content.value;\n return typeof value === 'string' ? value : '';\n}\n\n/**\n * Walks the tree depth-first, collecting ids by depth.\n *\n * @param root - Where to start.\n * @param depth - Levels to descend (0 = root only).\n * @returns Entries in display order.\n */\nfunction outline(root: JmNode, depth: number): { node: JmNode; level: number }[] {\n const out: { node: JmNode; level: number }[] = [];\n\n const walk = (node: JmNode, level: number): void => {\n if (level > depth) {\n return;\n }\n out.push({ node, level });\n for (const child of node.children) {\n walk(child, level + 1);\n }\n };\n\n walk(root, 0);\n return out;\n}\n\n/**\n * Finds nodes whose text contains the focus string, case-insensitively.\n *\n * @param nodes - Every node to consider.\n * @param focus - Needle.\n * @returns Matches in document order.\n */\nfunction matchNodes(nodes: JmNode[], focus: string): JmNode[] {\n const needle = focus.toLowerCase();\n return nodes.filter(node => flatten(textOf(node)).toLowerCase()\n .includes(needle));\n}\n\n/**\n * Collects every node reachable from the root.\n *\n * @param root - Root node.\n * @returns All nodes in depth-first order.\n */\nfunction allNodes(root: JmNode): JmNode[] {\n const out: JmNode[] = [];\n const walk = (node: JmNode): void => {\n out.push(node);\n for (const child of node.children) {\n walk(child);\n }\n };\n walk(root);\n return out;\n}\n\n/**\n * Ranks suggestions for a focus string that matched nothing.\n *\n * @remarks\n * Scored by how many characters of the needle appear in order in the label —\n * a cheap resemblance measure that needs no dictionary and still puts the\n * obviously-closest candidates first.\n *\n * @param nodes - Candidates.\n * @param focus - The needle that missed.\n * @returns Up to five nodes, closest first.\n */\nfunction suggest(nodes: JmNode[], focus: string): JmNode[] {\n const needle = focus.toLowerCase();\n\n const scored = nodes\n .map(node => {\n const label = flatten(textOf(node)).toLowerCase();\n let cursor = 0;\n let hits = 0;\n for (const char of needle) {\n const at = label.indexOf(char, cursor);\n if (at >= 0) {\n hits += 1;\n cursor = at + 1;\n }\n }\n return { node, hits };\n })\n .filter(entry => entry.hits > 0)\n .sort((a, b) => b.hits - a.hits || a.node.id.localeCompare(b.node.id))\n .map(entry => entry.node);\n\n if (scored.length > 0) {\n return scored.slice(0, 5);\n }\n\n // Nothing resembles the needle at all. Returning an empty list would leave\n // the agent with no ids and no next move, so fall back to the top of the\n // tree: shallow nodes are the most likely starting points for a second\n // attempt, and they are always cheap to show.\n return nodes.slice(0, 8);\n}\n\n/**\n * Flattens a nested style block to dotted keys.\n *\n * @param style - Style object, possibly nested.\n * @param prefix - Key prefix accumulated so far.\n * @returns Stringified values keyed by dotted path.\n * @remarks\n * A dotted key is the flag that set it, so a value shown here can be changed or\n * cleared by writing that same spelling back.\n */\nfunction flattenStyle(style: Record<string, unknown>, prefix = ''): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(style)) {\n const path = prefix === '' ? key : `${prefix}.${key}`;\n if (value !== null && typeof value === 'object') {\n Object.assign(out, flattenStyle(value as Record<string, unknown>, path));\n } else {\n out[path] = String(value);\n }\n }\n return out;\n}\n\n/**\n * Summarises a node's state for the text output — side (when it is meaningful),\n * folded, and any style overrides.\n *\n * @param node - Node to summarise.\n * @param level - Depth in the printed tree: 0 is the root, 1 is a direct child\n * of the root.\n * @returns A ` {side=left tone=danger}` suffix, or an empty string when the\n * node has nothing to report.\n * @remarks\n * `side` is only meaningful for the root and the root's direct children, so it\n * is shown only when `level` is 0 or 1. Deeper nodes inherit layout from their\n * ancestor on the root; printing `side` there would look like a fact the agent\n * should act on. `folded` appears only when the node is collapsed, and style\n * overrides appear when the node differs from the theme. After a parent is\n * moved to the other side, descendants are left alone: their stored `side` is\n * not rewritten, and it is not printed either.\n */\nfunction stateSummary(node: JmNode, level: number): string {\n const parts: string[] = [];\n\n // side is only meaningful for the root and the root's direct children.\n if (level <= 1) {\n const sideLabel = formatSide(node.side);\n parts.push(`side=${sideLabel}`);\n }\n\n if (node.folded) {\n parts.push('folded');\n }\n\n const style = describeStyle(node.style);\n if (style !== null) {\n for (const [key, value] of Object.entries(flattenStyle(style))) {\n parts.push(`${key}=${value}`);\n }\n }\n\n if (parts.length === 0) {\n return '';\n }\n return ` {${parts.join(' ')}}`;\n}\n\n/**\n * Renders entries as aligned text.\n *\n * @param entries - Nodes with their depth.\n * @param options - Truncation settings.\n * @returns Lines ready to print.\n */\nfunction renderTree(\n entries: { node: JmNode; level: number }[],\n options: ContextOptions\n): string[] {\n const width = Math.max(...entries.map(entry => entry.node.id.length), 2);\n\n return entries.map(({ node, level }) => {\n const id = node.id.padEnd(width);\n if (options.idsOnly) {\n return id.trimEnd();\n }\n const label = clip(flatten(textOf(node)), options.maxText, options.fullText);\n // Three spaces per level, after the id column.\n return `${id} ${' '.repeat(level)}${label}${stateSummary(node, level)}`;\n });\n}\n\n/**\n * Runs the context command.\n *\n * @param options - Parsed options.\n * @returns Exit code.\n */\nexport function runContext(options: ContextOptions): number {\n const doc = readJsonFile(options.file);\n // Same loader as every other read path: a structural fault must surface as\n // InvalidData rather than escaping as a raw JsMindError and landing in the\n // generic exit-3 branch.\n const mind: JmMind = loadMindOrThrow(new JmMindJsonSerializer(), doc, options.file);\n const root = mind.findNodeById(mind.root?.id ?? '');\n\n if (root === null) {\n throw dataError(`Cannot locate the root node in ${options.file}`);\n }\n\n const every = allNodes(root);\n\n // --focus: show matches and their surrounding structure.\n if (options.focus !== undefined && options.focus.length > 0) {\n const matches = matchNodes(every, options.focus);\n\n if (matches.length === 0) {\n const candidates = suggest(every, options.focus);\n if (options.asJson) {\n process.stdout.write(\n `${JSON.stringify(\n {\n matched: false,\n focus: options.focus,\n candidates: candidates.map(node => ({\n id: node.id,\n text: clip(flatten(textOf(node)), options.maxText, options.fullText),\n })),\n },\n null,\n 2\n )}\\n`\n );\n } else {\n process.stderr.write(`No node matches \"${options.focus}\".`);\n if (candidates.length > 0) {\n process.stderr.write(' Candidates from the top of the tree:\\n');\n for (const node of candidates) {\n const label = clip(flatten(textOf(node)), options.maxText, options.fullText);\n process.stderr.write(` ${node.id.padEnd(6)} ${label}\\n`);\n }\n } else {\n process.stderr.write('\\n');\n }\n }\n // A miss is not a data error: the file is fine, the search found\n // nothing. Usage stays 0 so an agent can read the candidates and\n // carry on rather than treating it as a failed run.\n return CliExit.Ok;\n }\n\n // Show each match plus its ancestors, so the agent sees where it sits.\n const shown = new Set<string>();\n const entries: { node: JmNode; level: number }[] = [];\n for (const match of matches) {\n const chain: JmNode[] = [];\n let cursor: JmNode | null = match;\n while (cursor !== null) {\n chain.unshift(cursor);\n cursor = cursor.parent;\n }\n chain.forEach((node, level) => {\n if (shown.has(node.id)) {\n return;\n }\n shown.add(node.id);\n entries.push({ node, level });\n });\n }\n\n emit(entries, options);\n return CliExit.Ok;\n }\n\n emit(outline(root, options.depth), options);\n return CliExit.Ok;\n}\n\n/**\n * Writes entries in the requested shape.\n *\n * @param entries - Nodes with depth.\n * @param options - Output settings.\n */\nfunction emit(entries: { node: JmNode; level: number }[], options: ContextOptions): void {\n if (options.asJson) {\n const payload = entries.map(({ node, level }) => {\n const entry: Record<string, unknown> = {\n id: node.id,\n level,\n text: options.idsOnly\n ? undefined\n : clip(flatten(textOf(node)), options.maxText, options.fullText),\n };\n // Same rule as the text output: side only for the root and its\n // direct children. Deeper nodes keep whatever side is stored; it\n // is just not printed, and it is not rewritten when a parent moves.\n if (level <= 1) {\n entry.side = formatSide(node.side);\n }\n if (node.folded) {\n entry.folded = true;\n }\n // Only when the node overrides something. A style block records the\n // difference from the theme, so a node that overrode nothing would\n // contribute the same absent entry every time - length for\n // information the theme already implies, on an output an agent reads\n // at every step.\n const style = describeStyle(node.style);\n if (style !== null) {\n entry.style = style;\n }\n return entry;\n });\n process.stdout.write(`${JSON.stringify(payload, null, 2)}\\n`);\n return;\n }\n\n for (const line of renderTree(entries, options)) {\n process.stdout.write(`${line}\\n`);\n }\n}\n\n/** Default depth, re-exported for the dispatcher. */\nexport { DEFAULT_DEPTH, DEFAULT_MAX_TEXT };\n\n/**\n * Describes the context command for `--help`.\n */\nexport const contextHelp = `jsmind context <file> [options]\n\nDiscovery step: shows the tree so an agent can find the ids it needs.\n\n --focus <text> Fuzzy-match node text; shows matches with their ancestors\n --depth <n> Levels below the root to show (default ${DEFAULT_DEPTH})\n --max-text <n> Truncate labels at n characters (default ${DEFAULT_MAX_TEXT})\n --full-text Do not truncate\n --ids-only Print ids only\n --json Machine-readable output\n\nIds are printed in a left-aligned column so they can be copied into the next\ncommand. Multi-line labels are flattened, and truncation ends in an ellipsis.\nEach line may end with a {…} block. side is shown only for the root and the\nroot's direct children. folded appears when the node is collapsed, and style\noverrides appear when the node differs from the theme.\n\nWhen --focus matches nothing, the closest candidates are listed instead.`;\n","/**\n * `jsmind create` — start a new mind map file.\n *\n * @remarks\n * Every other command needs a mind map to exist already; this is the only one\n * that produces one from nothing. Without it the CLI can edit maps but not\n * begin one, which leaves the agent hand-writing the initial JSON — exactly\n * what the CLI exists to prevent.\n *\n * The document is built through `JmMind` and `serialize()` rather than assembled\n * as a literal, so a new file cannot drift away from what the serialiser emits\n * for every other map.\n *\n * @packageDocumentation\n */\n\nimport { existsSync } from 'node:fs';\nimport { JmMindJsonSerializer } from '../../serialization/json.ts';\nimport { JmMind } from '../../model/mind.ts';\nimport { JmNodeContent } from '../../model/data/node-content.ts';\nimport { validateMindData } from '../../serialization/validation.ts';\nimport { formatIssues } from '../format.ts';\nimport { renderJson, writeJsonFile } from '../io.ts';\nimport { CliExit, dataError, usageError } from '../exit.ts';\n\n/** Options accepted by the create command. */\nexport interface CreateOptions {\n file: string;\n title: string;\n name?: string;\n author?: string;\n force: boolean;\n dryRun: boolean;\n backup: boolean;\n}\n\n/**\n * Runs the create command.\n *\n * @param options - Parsed options.\n * @returns Exit code.\n */\nexport function runCreate(options: CreateOptions): number {\n // Refuse to clobber by default. The same principle as every mutating\n // command: do not quietly destroy something that is already there.\n if (existsSync(options.file) && !options.force) {\n throw usageError(\n `${options.file} already exists. Use --force to overwrite, or pick another path.`\n );\n }\n\n // Build the object only from the fields that were actually given.\n //\n // Do not \"simplify\" this to `new JmMind({ name, author })`: mergeObjects\n // spreads user values over the defaults, and a present-but-undefined key\n // overwrites the default with undefined rather than being skipped. That\n // silently produces a document missing meta.name and meta.author, which the\n // validator then rejects as E_META.\n const metadata: { name?: string; author?: string } = {};\n // A mind map is normally named after its root. Defaulting name to title\n // means the common case needs one flag instead of two, and a document that\n // says \"jsMind Mindmap\" while its root says something else needs an\n // explicit --name to happen.\n metadata.name = options.name ?? options.title;\n if (options.author !== undefined) {\n metadata.author = options.author;\n }\n\n const mind = new JmMind(metadata);\n mind.root.content = new JmNodeContent('text', options.title);\n\n const serializer = new JmMindJsonSerializer();\n const doc = serializer.serialize(mind);\n\n // Check its own output before touching the disk. If the serialiser ever\n // emits something the validator rejects, that is a bug in this project,\n // not in the caller's data — the message says so.\n const check = validateMindData(doc);\n if (!check.valid) {\n throw dataError(\n `Refusing to write ${options.file}: the document built for it does not validate.\\n` +\n `This is a bug in jsmind, not in your input.\\n${formatIssues(check.errors)}`\n );\n }\n\n if (options.dryRun) {\n process.stdout.write(renderJson(doc));\n return CliExit.Ok;\n }\n\n writeJsonFile(doc, options.file, { dryRun: false, backup: options.backup });\n process.stdout.write(`created ${options.file}\\n`);\n return CliExit.Ok;\n}\n\n/**\n * Describes the create command for `--help`.\n */\nexport const createHelp = `jsmind create <file> --title <title> [options]\n\nStart a new mind map containing a single root node.\n\n --title <title> Root node label; also becomes meta.name (required)\n --name <name> Override meta.name when it should differ from the title\n --author <author> Author recorded in meta\n --force Overwrite the file if it already exists\n --backup Keep a .bak copy of the file being overwritten\n --dry-run Print the document instead of writing it\n\nRefuses to overwrite an existing file without --force. Every other command\nassumes a file exists; this is where one comes from.`;\n","#!/usr/bin/env node\n/**\n * jsMind v2 command line entry point.\n *\n * @remarks\n * The CLI is the agent-facing surface: it exposes the data layer (model +\n * serialization) without dragging in the renderer, so it runs on plain Node.\n *\n * Commands are grouped by what they operate on:\n *\n * cross-boundary validate, context — whole-document operations\n * mind structure and edges — JmMind methods\n * node node attributes — JmNode writable fields\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from 'node:util';\nimport { CliError, CliExit, usageError } from './exit.ts';\nimport {\n enumOption,\n intOption,\n numberOption,\n requireOption,\n type WriteOptions,\n} from './io.ts';\nimport {\n runExport,\n EXPORT_TYPES,\n DEFAULT_WIDTH,\n DEFAULT_HEIGHT,\n DEFAULT_SCALE,\n} from './commands/export.ts';\nimport { JmImageType } from '../view/export.ts';\nimport { runValidate, validateHelp, assertValidateArgs } from './commands/validate.ts';\nimport { runMind, mindHelp } from './commands/mind.ts';\nimport { runNode, nodeHelp } from './commands/node.ts';\nimport { runContext, contextHelp, DEFAULT_DEPTH, DEFAULT_MAX_TEXT } from './commands/context.ts';\nimport { runCreate, createHelp } from './commands/create.ts';\n\nconst PROGRAM = 'jsmind';\n\nexport const HELP = `${PROGRAM} v2 — mind map data commands\n\nUsage: ${PROGRAM} <command> [options]\n\nCross-boundary commands:\n create <file> --title <title> Start a new mind map\n validate <file> Check a file against the format spec\n export <file> <out.png> Render to an image (needs a browser)\n context <file> [options] Discovery: show the tree and its ids\n\nStructure and edges:\n mind <sub> <file> [options] JmMind methods (see: jsmind mind --help)\n\nNode attributes:\n node <sub> <file> [options] JmNode writable fields (see: jsmind node --help)\n\nOptions:\n --json Machine-readable output\n --dry-run Show what would change, write nothing\n --output <path> Write somewhere other than the input file\n --backup Keep a .bak copy before overwriting\n -h, --help Show this help\n\nExit codes:\n 0 success\n 1 invalid data\n 2 usage error\n 3 IO or runtime error\n\n${createHelp}\n\n${validateHelp}\n\n${contextHelp}\n\n${mindHelp}\n\n${nodeHelp}`;\n\n/**\n * Parsed incoming arguments.\n */\ninterface ParsedArgs {\n values: Record<string, unknown>;\n positionals: string[];\n}\n\n/**\n * Parses argv into options and positionals.\n *\n * @returns Parsed arguments, with the program and command stripped from\n * positionals.\n * @throws {@link CliError} With `Usage` when the command line cannot be parsed.\n */\nfunction parse(argv: string[]): ParsedArgs {\n try {\n const { values, positionals } = parseArgs({\n args: argv,\n allowPositionals: true,\n strict: true,\n options: {\n 'json': { type: 'boolean', default: false },\n 'dry-run': { type: 'boolean', default: false },\n 'output': { type: 'string' },\n 'backup': { type: 'boolean', default: false },\n 'help': { type: 'boolean', short: 'h', default: false },\n // locators\n 'node-id': { type: 'string' },\n 'parent-id': { type: 'string' },\n 'edge-id': { type: 'string' },\n 'source-id': { type: 'string' },\n 'target-id': { type: 'string' },\n // payloads\n 'text': { type: 'string' },\n 'folded': { type: 'string' },\n 'side': { type: 'string' },\n 'position': { type: 'string' },\n 'type': { type: 'string' },\n 'label': { type: 'string' },\n // node style (set-style). Strings, including the numeric ones: the command\n // parses and range-checks them itself so a bad value names the flag\n // rather than a JSON path. Dots mark a level, matching the path each\n // flag addresses.\n 'tone': { type: 'string' },\n 'background': { type: 'string' },\n 'color': { type: 'string' },\n 'border-color': { type: 'string' },\n 'border-width': { type: 'string' },\n 'border-style': { type: 'string' },\n 'font-size': { type: 'string' },\n 'font-weight': { type: 'string' },\n 'incoming.color': { type: 'string' },\n 'incoming.width': { type: 'string' },\n 'incoming.pattern': { type: 'string' },\n 'incoming.curve': { type: 'string' },\n 'clear': { type: 'string' },\n 'reset': { type: 'boolean', default: false },\n // context\n 'focus': { type: 'string' },\n 'depth': { type: 'string' },\n 'max-text': { type: 'string' },\n 'full-text': { type: 'boolean', default: false },\n 'ids-only': { type: 'boolean', default: false },\n // create\n 'title': { type: 'string' },\n 'name': { type: 'string' },\n 'author': { type: 'string' },\n 'force': { type: 'boolean', default: false },\n // export\n 'width': { type: 'string' },\n 'height': { type: 'string' },\n 'scale': { type: 'string' },\n },\n });\n return { values: values as Record<string, unknown>, positionals };\n } catch (err) {\n // parseArgs throws a plain Error with a decent message; promote it so\n // the caller gets exit code 2 instead of a stack trace.\n throw usageError((err as Error).message);\n }\n}\n\n/**\n * Reads the write-behaviour flags.\n *\n * @param values - Parsed options.\n * @returns Write options for the mutation pipeline.\n */\nfunction writeOptions(values: Record<string, unknown>): WriteOptions {\n const result: WriteOptions = {\n dryRun: values['dry-run'] === true,\n backup: values.backup === true,\n };\n if (typeof values.output === 'string') {\n result.output = values.output;\n }\n return result;\n}\n\n/**\n * Dispatches one parsed invocation.\n *\n * @param parsed - Options and positionals.\n * @returns Exit code.\n * @throws {@link CliError} When the command fails.\n */\nfunction dispatch(parsed: ParsedArgs): number | Promise<number> {\n const [command, ...rest] = parsed.positionals;\n const asJson = parsed.values.json === true;\n\n if (parsed.values.help === true || command === undefined || command === 'help') {\n process.stdout.write(`${HELP}\\n`);\n return CliExit.Ok;\n }\n\n switch (command) {\n case 'export': {\n const [file, output, ...extra] = rest;\n if (file === undefined || output === undefined) {\n throw usageError('export requires an input file and an output image path');\n }\n if (extra.length > 0) {\n throw usageError(`Unexpected arguments: ${extra.join(' ')}`);\n }\n return runExport({\n file,\n output,\n width: numberOption(parsed.values.width, DEFAULT_WIDTH, 'width'),\n height: numberOption(parsed.values.height, DEFAULT_HEIGHT, 'height'),\n scale: numberOption(parsed.values.scale, DEFAULT_SCALE, 'scale'),\n type: enumOption(parsed.values.type, JmImageType.Png, EXPORT_TYPES, 'type'),\n asJson,\n });\n }\n case 'validate': {\n assertValidateArgs(rest);\n return runValidate(rest[0], asJson);\n }\n case 'create': {\n const [file, ...extra] = rest;\n if (file === undefined) {\n throw usageError('create requires a file path');\n }\n if (extra.length > 0) {\n throw usageError(`Unexpected arguments: ${extra.join(' ')}`);\n }\n const options: Parameters<typeof runCreate>[0] = {\n file,\n title: requireOption(parsed.values, 'title'),\n force: parsed.values.force === true,\n dryRun: parsed.values['dry-run'] === true,\n // --output is deliberately not forwarded: for create the path\n // is already a positional argument, and an output redirect\n // would give two competing answers to \"where does this go\".\n backup: parsed.values.backup === true,\n };\n if (typeof parsed.values.name === 'string') {\n options.name = parsed.values.name;\n }\n if (typeof parsed.values.author === 'string') {\n options.author = parsed.values.author;\n }\n return runCreate(options);\n }\n case 'context': {\n const [file, ...extra] = rest;\n if (file === undefined) {\n throw usageError('context requires a file path');\n }\n if (extra.length > 0) {\n throw usageError(`Unexpected arguments: ${extra.join(' ')}`);\n }\n const options: Parameters<typeof runContext>[0] = {\n file,\n depth: intOption(parsed.values.depth, DEFAULT_DEPTH, 'depth'),\n maxText: intOption(parsed.values['max-text'], DEFAULT_MAX_TEXT, 'max-text'),\n fullText: parsed.values['full-text'] === true,\n idsOnly: parsed.values['ids-only'] === true,\n asJson,\n };\n if (typeof parsed.values.focus === 'string') {\n options.focus = parsed.values.focus;\n }\n return runContext(options);\n }\n case 'mind': {\n const [subcommand, file, ...extra] = rest;\n if (subcommand === undefined || file === undefined) {\n throw usageError(`mind requires a subcommand and a file\\n\\n${mindHelp}`);\n }\n if (extra.length > 0) {\n throw usageError(`Unexpected arguments: ${extra.join(' ')}`);\n }\n return runMind(file, subcommand, parsed.values, writeOptions(parsed.values));\n }\n case 'node': {\n const [subcommand, file, ...extra] = rest;\n if (subcommand === undefined || file === undefined) {\n throw usageError(`node requires a subcommand and a file\\n\\n${nodeHelp}`);\n }\n if (extra.length > 0) {\n throw usageError(`Unexpected arguments: ${extra.join(' ')}`);\n }\n return runNode(file, subcommand, parsed.values, writeOptions(parsed.values));\n }\n default:\n throw usageError(`Unknown command: ${command}\\n\\nRun \"${PROGRAM} --help\" for usage.`);\n }\n}\n\n/**\n * Runs the CLI and terminates the process.\n *\n * @param argv - Arguments after the executable and script path.\n */\nasync function main(argv: string[]): Promise<void> {\n try {\n process.exitCode = await dispatch(parse(argv));\n } catch (err) {\n if (err instanceof CliError) {\n process.stderr.write(`${err.message}\\n`);\n process.exitCode = err.exit;\n return;\n }\n // Anything unexpected is a runtime failure, not a usage problem — the\n // caller should stop and look rather than retry with a different\n // command line.\n process.stderr.write(`Unexpected failure: ${(err as Error).message}\\n`);\n process.exitCode = CliExit.IoError;\n }\n}\n\nvoid main(process.argv.slice(2));\n"],"names":["SUBCOMMANDS"],"mappings":";;;;;;;;;;;;;;;AAAA;;;;;;;;;;AAUG;AAEH;;;;AAIG;AACI,MAAM,OAAO,GAAG;;AAEnB,IAAA,EAAE,EAAE,CAAC;;AAEL,IAAA,WAAW,EAAE,CAAC;;AAEd,IAAA,KAAK,EAAE,CAAC;;AAER,IAAA,OAAO,EAAE,CAAC;CACJ;AAIV;;;;AAIG;AACG,MAAO,QAAS,SAAQ,KAAK,CAAA;;AAEtB,IAAA,IAAI;AAEb;;;AAGG;IACH,WAAA,CAAY,OAAe,EAAE,IAAa,EAAA;QACtC,KAAK,CAAC,OAAO,CAAC;AACd,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI;AAChB,QAAA,IAAI,CAAC,IAAI,GAAG,UAAU;IAC1B;AACH;AAED;;;;;AAKG;AACG,SAAU,UAAU,CAAC,OAAe,EAAA;IACtC,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC;AAC/C;AAEA;;;;;AAKG;AACG,SAAU,SAAS,CAAC,OAAe,EAAA;IACrC,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC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