import { withWorkspaceExtensions } from "./extension-scope.ts"; import type { CommandDefinition, ExtensionApi, ExtensionModule } from "@unbrained/pm-cli/sdk/authoring"; import * as nativeSdk from "@unbrained/pm-cli/sdk"; import { readFileSync, writeFileSync, createReadStream, mkdirSync } from "node:fs"; import { basename, resolve } from "node:path"; import { spawnSync, type SpawnSyncReturns } from "node:child_process"; import { createHash } from "node:crypto"; import { certifyCompleteListResult, inspectCompleteListResult, listAllComplete, readSettingsWithMetadata, resolveRuntimeFieldRegistry, runWorkspaceTransactionGc, create as createNativeCsv, update as updateNativeCsv, resolveRuntimeStatusRegistry, isTerminalStatus } from "@unbrained/pm-cli/sdk"; import { captureSettings, inSettingsTransaction, normalizePinnedStatus, pinCreateDefaults, readPinnedSettings as readSettings, rethrowSettingsChange, settingsDigest, useSettings, verifySettings, withSettings, withSettingsFence } from "./settings-snapshot.ts"; import type { SettingsSnapshot } from "./settings-snapshot.ts"; import { importLineage, writeLineageBundle, LineageRefusal } from "./lineage.ts"; import type { LineageField } from "./lineage.ts"; import { applyEditSession, exportEditSession, EditRefusal } from "./roundtrip.ts"; import { buildMutationIntent, mutationScopeArguments, matchesMutationScope } from "./mutation-intent.ts"; import { registerJoinCommands } from "./join-plans.ts"; import { registerTableSchemaCommands } from "./table-schema.ts"; import { admitCSV, AdmissionRefusal, admissionPreviewFailure, admissionSettingsChanged, withAdmissionTargetChecks, assertCSVAdmission, findAdmissionFailure, normalizeAdmissionFilter, parseAdmissionOptions, readAdmittedSource, registerAdmissionCommand, requireAdmissionCapability } from "./admission.ts"; import type { AdmissionOptions, AdmissionTargetChecks } from "./admission.ts"; import { captureUpdateCompensation, compensateUpdate, inspectUpdate, readUpdateDocument, UPDATE_COMPENSATION_VERSION } from "./atomic-update.ts"; import type { WorkspaceTransactionStep, WorkspaceTransactionCommitResult, WorkspaceTransactionStepInspection, WorkspaceTransactionJsonValue, CommitWorkspaceTransactionOptions, PmSettings, BulkItemMutation, ItemStatus as NativeItemStatus, } from "@unbrained/pm-cli/sdk"; // --------------------------------------------------------------------------- // Error contract // --------------------------------------------------------------------------- // pm's extension command runtime only treats a thrown error as a cleanly // handled non-zero exit when the error carries a numeric `exitCode` property // (see @unbrained/pm-cli runCommandHandler). A plain `Error` makes the runtime // fall through to its "unhandled" path, which RE-INVOKES the command handler a // second time and exits with a generic code. We mirror the SDK's EXIT_CODE // contract here rather than importing it: standalone-installed extensions load // only their own `dist/`, so `@unbrained/pm-cli` is not resolvable at runtime. const EXIT_CODE = { GENERIC_FAILURE: 1, USAGE: 2, NOT_FOUND: 3, } as const; /** * Error carrying a semantic process exit code, thrown by every failure path * the command runtime must turn into a clean nonzero exit (including the * complete-list refusals). Exported so regression tests can assert the * typed failure instead of matching on message text alone. */ export class CommandError extends Error { /** Numeric exit code the runtime propagates to the shell. */ exitCode: number; /** Optional stable category for snapshot-sensitive mutation refusals. */ code?: string; constructor(message: string, exitCode: number = EXIT_CODE.GENERIC_FAILURE, code?: string) { super(message); this.name = "CommandError"; this.exitCode = exitCode; if (code) this.code = code; } } // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- type ItemStatus = NativeItemStatus; interface PmItem { id: string; title: string; body?: string; status: ItemStatus; priority?: number; type?: string; tags?: string[]; created_at?: string; updated_at?: string; deadline?: string; parent?: string; assignee?: string; sprint?: string; release?: string; blocked_by?: string; /** Derived on export from the csv-source: provenance tag (not a stored field). */ csv_source?: string; } // Columns accepted on import (order independent — driven by header row). // The relational/planning fields (parent, assignee, sprint, release, // blocked_by) all map to real `pm create`/`pm update` flags verified against // the installed CLI (--parent, --assignee, --sprint, --release, --blocked-by). const IMPORT_COLUMNS = [ "title", "type", "status", "priority", "tags", "deadline", "body", "parent", "assignee", "sprint", "release", "blocked_by", ] as const; // Columns written on export (fixed order) const EXPORT_COLUMNS: Array = [ "id", "title", "type", "status", "priority", "tags", "deadline", "body", "parent", "assignee", "sprint", "release", "blocked_by", "csv_source", "created_at", "updated_at", ]; /** Recognized status values for the `csv validate` report. */ const KNOWN_STATUSES: ReadonlySet = new Set([ "open", "todo", "new", "in_progress", "wip", "in progress", "doing", "blocked", "on_hold", "on hold", "closed", "done", "complete", "completed", "canceled", "cancelled", "draft", ]); /** Supported file encodings for `--encoding` on import. */ const SUPPORTED_ENCODINGS = ["utf-8", "utf8", "utf16le", "latin1"] as const; type SupportedEncoding = (typeof SUPPORTED_ENCODINGS)[number]; // --------------------------------------------------------------------------- // CSV parser — no external dependencies // --------------------------------------------------------------------------- /** * Parse a full CSV string into rows of string arrays. * Handles: * - Quoted fields (double-quotes), including embedded newlines inside quotes * - Escaped quotes ("" inside a quoted field → single ") * - Custom delimiter * - CRLF and LF line endings * - Explicit quoted empty records at EOF, without inventing a row after a final newline */ function parseCSV(text: string, delimiter: string = ","): string[][] { const rows: string[][] = []; let row: string[] = []; let field = ""; let inQuotes = false; let recordStarted = false; let i = 0; while (i < text.length) { const ch = text[i]; recordStarted = true; if (inQuotes) { if (ch === '"') { // Peek ahead: "" means escaped quote if (text[i + 1] === '"') { field += '"'; i += 2; continue; } // Closing quote inQuotes = false; i++; continue; } // Any other character (including newlines) inside quotes field += ch; i++; continue; } // Not in quotes if (ch === '"') { inQuotes = true; i++; continue; } if (ch === delimiter) { row.push(field); field = ""; i++; continue; } if (ch === "\r" && text[i + 1] === "\n") { row.push(field); field = ""; rows.push(row); row = []; recordStarted = false; i += 2; continue; } if (ch === "\n") { row.push(field); field = ""; rows.push(row); row = []; recordStarted = false; i++; continue; } field += ch; i++; } // An explicit quoted empty field starts a record even though its value is empty. if (recordStarted) { row.push(field); rows.push(row); } return rows; } /** * Strip a leading UTF-8 BOM (U+FEFF) if present. Files exported by Excel and * many Windows tools start with a BOM; without removing it the first header * name silently becomes "title" and the required-column check fails. */ function stripBOM(text: string): string { return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text; } /** * Serialize a single field value for CSV output. * Wraps in double-quotes when the value contains the delimiter, quotes, or newlines. */ function serializeField(value: string, delimiter: string): string { const needsQuoting = value.includes(delimiter) || value.includes('"') || value.includes("\n") || value.includes("\r"); if (!needsQuoting) return value; // Escape embedded double-quotes by doubling them return `"${value.replace(/"/g, '""')}"`; } interface SerializeOptions { delimiter: string; /** Line terminator. RFC-4180 mandates CRLF; we default to LF for unix-friendliness. */ eol?: "\n" | "\r\n"; } /** * Serialize a full array of rows into a CSV string. */ function serializeCSV( rows: string[][], delimiterOrOpts: string | SerializeOptions, ): string { const opts: SerializeOptions = typeof delimiterOrOpts === "string" ? { delimiter: delimiterOrOpts } : delimiterOrOpts; const eol = opts.eol ?? "\n"; return rows .map((row) => row.map((f) => serializeField(f, opts.delimiter)).join(opts.delimiter)) .join(eol); } // --------------------------------------------------------------------------- // Streaming CSV parser — for large files that should not be held in memory. // Same RFC-4180 state machine as parseCSV, but fed incrementally so quoted // fields spanning chunk boundaries are handled correctly. // --------------------------------------------------------------------------- /** * Incremental CSV state machine. Feed text via {@link push} and call * {@link end} when the input is exhausted. Each complete row is emitted to the * `onRow` callback exactly as in {@link parseCSV}. */ export interface CSVParserLimits { maxFieldCodeUnits: number; maxRecordCodeUnits: number; maxColumns: number; } class StreamingCSVParser { private delimiter: string; private onRow: (row: string[]) => void; private field = ""; private row: string[] = []; private inQuotes = false; private recordStarted = false; private pendingBoundaryChar = ""; private limits?: CSVParserLimits; private recordCodeUnits = 0; constructor(delimiter: string, onRow: (row: string[]) => void, limits?: CSVParserLimits) { this.delimiter = delimiter; this.onRow = onRow; this.limits = limits; } /** Bound allocations before appending even an unterminated adversarial field. */ private appendField(value: string): void { if (this.limits && (this.field.length + value.length > this.limits.maxFieldCodeUnits || this.recordCodeUnits + value.length > this.limits.maxRecordCodeUnits)) throw new RangeError("csv_record_limit"); this.field += value; this.recordCodeUnits += value.length; } /** Bound empty fields too, so delimiter-only input cannot grow an unbounded array. */ private finishField(): void { if (this.limits && this.row.length >= this.limits.maxColumns) throw new RangeError("csv_column_limit"); this.row.push(this.field); this.field = ""; } push(text: string): void { text = this.pendingBoundaryChar + text; this.pendingBoundaryChar = ""; let i = 0; while (i < text.length) { const ch = text[i]; this.recordStarted = true; if (this.inQuotes) { if (ch === '"') { if (i + 1 === text.length) { this.pendingBoundaryChar = ch; return; } if (text[i + 1] === '"') { this.appendField('"'); i += 2; continue; } this.inQuotes = false; i++; continue; } this.appendField(ch); i++; continue; } if (ch === '"') { this.inQuotes = true; i++; continue; } if (ch === this.delimiter) { this.finishField(); i++; continue; } if (ch === "\r" && text[i + 1] === "\n") { this.finishField(); this.onRow(this.row); this.row = []; this.recordCodeUnits = 0; this.recordStarted = false; i += 2; continue; } if (ch === "\r" && i + 1 === text.length) { this.pendingBoundaryChar = ch; return; } if (ch === "\n") { this.finishField(); this.onRow(this.row); this.row = []; this.recordCodeUnits = 0; this.recordStarted = false; i++; continue; } this.appendField(ch); i++; } } end(): void { if (this.pendingBoundaryChar === '"' && this.inQuotes) { this.inQuotes = false; } else if (this.pendingBoundaryChar !== "") { this.appendField(this.pendingBoundaryChar); } this.pendingBoundaryChar = ""; if (this.limits && this.inQuotes) throw new SyntaxError("csv_unterminated_quote"); if (this.recordStarted) { this.finishField(); this.onRow(this.row); this.field = ""; this.row = []; this.recordStarted = false; this.recordCodeUnits = 0; } } } /** * Stream a CSV file from disk, emitting each parsed row to `onRow`. Uses a * readable stream so the file is never fully loaded into memory. The BOM is * stripped from the first chunk. If `onRow` throws, the stream is destroyed and * the returned promise rejects with that error. */ function streamCSVFile( filePath: string, delimiter: string, encoding: SupportedEncoding, onRow: (row: string[]) => void, ): Promise { const bufEnc: BufferEncoding = encoding === "utf-8" ? "utf8" : (encoding as BufferEncoding); return (async () => { const stream = createReadStream(filePath, { encoding: bufEnc }); const parser = new StreamingCSVParser(delimiter, onRow); let firstChunk = true; try { for await (const chunk of stream) { // createReadStream was constructed with an encoding, so Node guarantees // string chunks even though the broad async-iterator type retains Buffer. const text = firstChunk ? stripBOM(chunk as string) : chunk as string; firstChunk = false; parser.push(text); } parser.end(); } catch (error: unknown) { stream.destroy(); throw error; } })(); } // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- /** * Read a boolean option honoring both the kebab-case long flag and the * camelCase key the runtime normalizes it to (e.g. `--dry-run` -> `dryRun`). * Without this, `ctx.options["dry-run"]` is silently `undefined`. */ function readBoolOption(options: Record, ...keys: string[]): boolean { for (const key of keys) { if (Object.hasOwn(options, key) && options[key] !== undefined) return Boolean(options[key]); } return false; } /** * Whether the CSV header row should be omitted. The host parses `--no-header` * as the negation of the registered positive `--header` flag (setting * `header=false`); the literal `no-header`/`noHeader` keys are accepted as a * fallback for the exporter-capability path. Precedence: an explicit * `header=false` (i.e. `--no-header`) always wins. Shared by the `csv export` * command and the `csv-export` exporter so the two paths can't drift. */ function readNoHeaderOption(options: Record): boolean { return options["header"] === false || readBoolOption(options, "no-header", "noHeader"); } /** * Resolve a user-supplied delimiter, accepting friendly aliases so TSV is easy: * --delimiter tab --delimiter "\t" --delimiter ";" * A literal backslash-t is interpreted as a tab. */ function resolveDelimiter(raw: string | undefined): string { if (raw === undefined || raw === "") return ","; const lower = raw.toLowerCase(); if (lower === "tab" || lower === "\\t" || lower === "tsv") return "\t"; if (lower === "comma") return ","; if (lower === "semicolon") return ";"; if (lower === "pipe") return "|"; return raw; } /** * Provenance tag prefix used for idempotent upsert. When the importer is told * to key on a column, the created item is tagged `csv-key:` so a later * re-import can find and update the same item instead of duplicating it. */ const KEY_TAG_PREFIX = "csv-key:"; // Provenance tag prefix written when `--source