Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(planka-import): add PLANKA to Kaneo migration CLI

Andrej5c91febedf4e
diff --git a/packages/planka-import/LICENSE b/packages/planka-import/LICENSE
new file mode 100644
index 000000000..85db1d012
--- /dev/null
+++ b/packages/planka-import/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Kaneo MCP contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/planka-import/README.md b/packages/planka-import/README.md
new file mode 100644
index 000000000..c2f5ee8aa
--- /dev/null
+++ b/packages/planka-import/README.md
@@ -0,0 +1,97 @@
+# @kaneo/planka-import
+
+Migrate your [PLANKA](https://planka.app) boards into [Kaneo](https://kaneo.app).
+
+PLANKA has no export feature, so this tool reads your boards through PLANKA's
+REST API and recreates them in Kaneo through Kaneo's public API. Nothing is
+written to PLANKA, and your PLANKA credentials never leave your machine.
+
+## Usage
+
+```bash
+npx @kaneo/planka-import --planka-url https://planka.example.com --dry-run
+```
+
+A dry run reads PLANKA only and prints exactly what would be created. When the
+plan looks right, add your Kaneo credentials and drop `--dry-run`:
+
+```bash
+npx @kaneo/planka-import \
+ --planka-url https://planka.example.com \
+ --kaneo-url https://app.kaneo.app \
+ --kaneo-api-key kaneo_xxx \
+ --workspace ws_123
+```
+
+You'll be prompted for your PLANKA login and for which boards to migrate.
+
+Create a Kaneo API key under **Settings → API keys**. Self-hosting? Point
+`--kaneo-url` at your own instance.
+
+## What carries over
+
+| PLANKA | Kaneo |
+| --- | --- |
+| Board | Project |
+| List | Column (`Closed` lists become the final column) |
+| Card | Task |
+| Card description | Task description |
+| Checklists (task lists) | Markdown checkboxes appended to the description |
+| Labels | Labels, with their original colors |
+| Card members | Assignee, matched by email address |
+| Due date | Due date |
+| Comments | Comments, prefixed with the original author and date |
+
+One Kaneo project is created per PLANKA **board**, since the board is what holds
+lists and cards. If a PLANKA project has several boards, each Kaneo project is
+named `Project – Board`.
+
+## What doesn't
+
+- **Attachments.** Counted and reported, but not transferred.
+- **Archive and trash lists.** Skipped by design; only active and closed lists
+ are migrated.
+- **Comment authorship.** Kaneo attributes every imported comment to the owner
+ of the API key, so the original author and date are preserved in the comment
+ body instead.
+- **Priorities.** PLANKA has no priority field, so every task starts at
+ `no-priority`.
+- **Custom fields, stopwatches, and card subscriptions.** No Kaneo equivalent.
+
+Assignees only match when the person already exists in the target Kaneo
+workspace with the same email address. Invite your team first, then import, and
+assignments come across on the first run.
+
+## Options
+
+| Flag | Description |
+| --- | --- |
+| `--planka-url <url>` | PLANKA instance URL (required) |
+| `--planka-user <user>` | Email or username (prompted if omitted) |
+| `--planka-password <pass>` | Password (or set `PLANKA_PASSWORD`) |
+| `--planka-token <token>` | Use an existing access token instead of logging in |
+| `--kaneo-url <url>` | Kaneo instance URL (default `https://app.kaneo.app`) |
+| `--kaneo-api-key <key>` | Kaneo API key (or set `KANEO_API_KEY`) |
+| `--workspace <id>` | Target workspace (prompted if omitted) |
+| `--project <name\|id>` | Migrate only this PLANKA project (repeatable) |
+| `--all` | Migrate every board without prompting |
+| `--dry-run` | Report what would happen, write nothing |
+| `--skip-comments` | Don't migrate comments |
+| `--icon <name>` | Lucide icon for created projects (default `Layout`) |
+| `--report <path>` | Write a JSON report |
+| `-y, --yes` | Skip the confirmation prompt |
+
+If your PLANKA account has two-factor authentication enabled, password login
+won't work. Grab a token from your browser's dev tools and pass
+`--planka-token` instead.
+
+## Re-running
+
+The importer always creates new projects; it does not update ones it created
+earlier. If an import goes wrong, delete the created Kaneo project and run it
+again. Board-level failures are isolated, so one broken board won't stop the
+rest, and the summary tells you which ones failed.
+
+## License
+
+MIT
diff --git a/packages/planka-import/package.json b/packages/planka-import/package.json
new file mode 100644
index 000000000..9a69992a8
--- /dev/null
+++ b/packages/planka-import/package.json
@@ -0,0 +1,56 @@
+{
+ "name": "@kaneo/planka-import",
+ "version": "0.1.0",
+ "description": "Migrate PLANKA boards into Kaneo: projects, lists, cards, labels, assignees, checklists and comments, over the public APIs of both",
+ "license": "MIT",
+ "author": "Kaneo (https://kaneo.app)",
+ "homepage": "https://kaneo.app/docs/core/migrations/from-planka",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/usekaneo/kaneo/",
+ "directory": "packages/planka-import"
+ },
+ "type": "module",
+ "bin": {
+ "kaneo-planka-import": "dist/index.js"
+ },
+ "publishConfig": {
+ "access": "public"
+ },
+ "files": [
+ "dist",
+ "README.md",
+ "LICENSE"
+ ],
+ "keywords": [
+ "planka",
+ "kaneo",
+ "migration",
+ "import",
+ "kanban",
+ "project-management",
+ "cli"
+ ],
+ "engines": {
+ "node": ">=20"
+ },
+ "scripts": {
+ "build": "tsc -p tsconfig.json",
+ "prepublishOnly": "pnpm run build",
+ "lint": "biome check --write .",
+ "start": "node dist/index.js",
+ "test": "vitest run --config vitest.config.ts",
+ "test:watch": "vitest --config vitest.config.ts"
+ },
+ "dependencies": {
+ "prompts": "^2.4.2"
+ },
+ "devDependencies": {
+ "@kaneo/typescript-config": "workspace:*",
+ "@types/node": "^26.1.2",
+ "@types/prompts": "^2.4.9",
+ "tsx": "^4.23.9",
+ "typescript": "^7.0.2",
+ "vitest": "^4.1.10"
+ }
+}
diff --git a/packages/planka-import/src/args.test.ts b/packages/planka-import/src/args.test.ts
new file mode 100644
index 000000000..434297884
--- /dev/null
+++ b/packages/planka-import/src/args.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from "vitest";
+import { parseArgs } from "./args.js";
+
+describe("parseArgs", () => {
+ it("returns defaults for an empty argv", () => {
+ const parsed = parseArgs([]);
+
+ expect(parsed.projects).toEqual([]);
+ expect(parsed.dryRun).toBe(false);
+ expect(parsed.all).toBe(false);
+ });
+
+ it("parses space-separated values", () => {
+ const parsed = parseArgs([
+ "--planka-url",
+ "https://planka.acme.com",
+ "--workspace",
+ "ws_1",
+ ]);
+
+ expect(parsed.plankaUrl).toBe("https://planka.acme.com");
+ expect(parsed.workspace).toBe("ws_1");
+ });
+
+ it("parses inline --flag=value form", () => {
+ const parsed = parseArgs(["--kaneo-api-key=kaneo_abc"]);
+
+ expect(parsed.kaneoApiKey).toBe("kaneo_abc");
+ });
+
+ it("collects repeated --project flags", () => {
+ const parsed = parseArgs([
+ "--project",
+ "Marketing",
+ "--project=Engineering",
+ ]);
+
+ expect(parsed.projects).toEqual(["Marketing", "Engineering"]);
+ });
+
+ it("parses boolean flags and their short forms", () => {
+ const parsed = parseArgs(["--dry-run", "--skip-comments", "-y"]);
+
+ expect(parsed.dryRun).toBe(true);
+ expect(parsed.skipComments).toBe(true);
+ expect(parsed.yes).toBe(true);
+ });
+
+ it("keeps a value that looks like a flag when given inline", () => {
+ const parsed = parseArgs(["--planka-password=--weird--"]);
+
+ expect(parsed.plankaPassword).toBe("--weird--");
+ });
+
+ it("rejects unknown options", () => {
+ expect(() => parseArgs(["--nope"])).toThrow("Unknown option: --nope");
+ });
+
+ it("rejects a flag that is missing its value", () => {
+ expect(() => parseArgs(["--workspace"])).toThrow(
+ "--workspace requires a value",
+ );
+ });
+});
diff --git a/packages/planka-import/src/args.ts b/packages/planka-import/src/args.ts
new file mode 100644
index 000000000..ec22dd546
--- /dev/null
+++ b/packages/planka-import/src/args.ts
@@ -0,0 +1,136 @@
+export type ParsedArgs = {
+ plankaUrl?: string;
+ plankaUser?: string;
+ plankaPassword?: string;
+ plankaToken?: string;
+ kaneoUrl?: string;
+ kaneoApiKey?: string;
+ workspace?: string;
+ projects: string[];
+ icon?: string;
+ report?: string;
+ all: boolean;
+ dryRun: boolean;
+ skipComments: boolean;
+ yes: boolean;
+ help: boolean;
+ version: boolean;
+};
+
+const STRING_FLAGS: Record<string, keyof ParsedArgs> = {
+ "--planka-url": "plankaUrl",
+ "--planka-user": "plankaUser",
+ "--planka-password": "plankaPassword",
+ "--planka-token": "plankaToken",
+ "--kaneo-url": "kaneoUrl",
+ "--kaneo-api-key": "kaneoApiKey",
+ "--workspace": "workspace",
+ "--icon": "icon",
+ "--report": "report",
+};
+
+const BOOLEAN_FLAGS: Record<string, keyof ParsedArgs> = {
+ "--all": "all",
+ "--dry-run": "dryRun",
+ "--skip-comments": "skipComments",
+ "--yes": "yes",
+ "-y": "yes",
+ "--help": "help",
+ "-h": "help",
+ "--version": "version",
+ "-v": "version",
+};
+
+export function parseArgs(argv: string[]): ParsedArgs {
+ const parsed: ParsedArgs = {
+ projects: [],
+ all: false,
+ dryRun: false,
+ skipComments: false,
+ yes: false,
+ help: false,
+ version: false,
+ };
+
+ for (let index = 0; index < argv.length; index++) {
+ const raw = argv[index] as string;
+ const equals = raw.indexOf("=");
+ const flag = equals === -1 ? raw : raw.slice(0, equals);
+ const inlineValue = equals === -1 ? undefined : raw.slice(equals + 1);
+
+ if (flag in BOOLEAN_FLAGS) {
+ const key = BOOLEAN_FLAGS[flag] as
+ | "all"
+ | "dryRun"
+ | "skipComments"
+ | "yes"
+ | "help"
+ | "version";
+ parsed[key] = true;
+ continue;
+ }
+
+ if (flag === "--project") {
+ const value = inlineValue ?? argv[++index];
+ if (value === undefined) throw new Error("--project requires a value");
+ parsed.projects.push(value);
+ continue;
+ }
+
+ if (flag in STRING_FLAGS) {
+ const value = inlineValue ?? argv[++index];
+ if (value === undefined) throw new Error(`${flag} requires a value`);
+ const key = STRING_FLAGS[flag] as Exclude<
+ keyof ParsedArgs,
+ | "projects"
+ | "all"
+ | "dryRun"
+ | "skipComments"
+ | "yes"
+ | "help"
+ | "version"
+ >;
+ parsed[key] = value;
+ continue;
+ }
+
+ throw new Error(`Unknown option: ${flag}`);
+ }
+
+ return parsed;
+}
+
+export const HELP_TEXT = `kaneo-planka-import — migrate PLANKA boards into Kaneo
+
+Usage:
+ npx @kaneo/planka-import --planka-url <url> --kaneo-api-key <key> [options]
+
+PLANKA source:
+ --planka-url <url> PLANKA instance URL (required)
+ --planka-user <user> Email or username (prompted if omitted)
+ --planka-password <pass> Password (env PLANKA_PASSWORD, or prompted)
+ --planka-token <token> Use an existing access token instead of logging in
+
+Kaneo target:
+ --kaneo-url <url> Kaneo instance URL (default https://app.kaneo.app)
+ --kaneo-api-key <key> Kaneo API key (env KANEO_API_KEY)
+ --workspace <id> Target workspace ID (prompted if omitted)
+
+Selection:
+ --project <name|id> Migrate only this PLANKA project (repeatable)
+ --all Migrate every project without prompting
+
+Behaviour:
+ --dry-run Report what would be migrated, write nothing
+ --skip-comments Do not migrate card comments
+ --icon <name> Lucide icon for created projects (default Layout)
+ --report <path> Write a JSON report to this path
+ -y, --yes Do not ask for confirmation before writing
+ -h, --help Show this help
+ -v, --version Show the version
+
+Examples:
+ npx @kaneo/planka-import --planka-url https://planka.acme.com --dry-run
+ npx @kaneo/planka-import --planka-url https://planka.acme.com \\
+ --kaneo-api-key kaneo_xxx --workspace ws_123 --all
+`;
diff --git a/packages/planka-import/src/colors.ts b/packages/planka-import/src/colors.ts
new file mode 100644
index 000000000..e9a481dee
--- /dev/null
+++ b/packages/planka-import/src/colors.ts
@@ -0,0 +1,57 @@
+// PLANKA stores label and list colors as names; Kaneo stores hex. Values are
+// read off PLANKA's own stylesheet so migrated labels keep their exact color.
+const LABEL_COLORS: Record<string, string> = {
+ "muddy-grey": "#69655a",
+ "autumn-leafs": "#c9b037",
+ "morning-sky": "#52b9d5",
+ "antique-blue": "#6c99bb",
+ "egg-yellow": "#f9c423",
+ "desert-sand": "#fad371",
+ "dark-granite": "#8b8680",
+ "fresh-salad": "#ced85e",
+ "lagoon-blue": "#109dc0",
+ "midnight-blue": "#0a63a0",
+ "light-orange": "#fdae5f",
+ "pumpkin-orange": "#ed9223",
+ "light-concrete": "#afb0a4",
+ "sunny-grass": "#beca02",
+ "navy-blue": "#1d7299",
+ "lilac-eyes": "#406cbd",
+ "apricot-red": "#fc736c",
+ "orange-peel": "#de692f",
+ // Gradient in PLANKA; collapsed to its dominant stop.
+ "silver-glint": "#92908d",
+ "bright-moss": "#96b352",
+ "deep-ocean": "#004c70",
+ "summer-sky": "#5d9cec",
+ "berry-red": "#e83855",
+ "light-cocoa": "#a85540",
+ "grey-stone": "#aab2bd",
+ "tank-green": "#8aa177",
+ "coral-green": "#2b6a6c",
+ "sugar-plum": "#7e86c7",
+ "pink-tulip": "#e34f7c",
+ "shady-rust": "#87564a",
+ "wet-rock": "#83949b",
+ "wet-moss": "#4a8753",
+ "turquoise-sea": "#00858a",
+ "lavender-fields": "#b287bd",
+ "piggy-red": "#f97394",
+ "light-mud": "#c7a57a",
+ "gun-metal": "#4f6573",
+ "modern-green": "#77ce87",
+ "french-coast": "#00b4b1",
+ "sweet-lilac": "#975298",
+ "red-burgundy": "#ad5f7d",
+ // Gradient in PLANKA; collapsed to its dominant stop.
+ "pirate-gold": "#b47e11",
+};
+
+const FALLBACK_COLOR = "#6b7280";
+
+export function labelColorToHex(color: string | null | undefined): string {
+ if (!color) return FALLBACK_COLOR;
+ return LABEL_COLORS[color] ?? FALLBACK_COLOR;
+}
+
+export { FALLBACK_COLOR, LABEL_COLORS };
diff --git a/packages/planka-import/src/index.ts b/packages/planka-import/src/index.ts
new file mode 100644
index 000000000..fdbb8d123
--- /dev/null
+++ b/packages/planka-import/src/index.ts
@@ -0,0 +1,350 @@
+#!/usr/bin/env node
+import { writeFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import prompts from "prompts";
+import { HELP_TEXT, parseArgs } from "./args.js";
+import { KaneoClient } from "./kaneo.js";
+import { type BoardReport, type BoardTarget, migrate } from "./migrate.js";
+import { PlankaClient } from "./planka.js";
+
+const require = createRequire(import.meta.url);
+const { version } = require("../package.json") as { version: string };
+
+async function main(): Promise<number> {
+ const args = parseArgs(process.argv.slice(2));
+
+ if (args.help) {
+ process.stdout.write(HELP_TEXT);
+ return 0;
+ }
+
+ if (args.version) {
+ process.stdout.write(`${version}\n`);
+ return 0;
+ }
+
+ const interactive = process.stdin.isTTY === true;
+
+ const plankaUrl =
+ args.plankaUrl ??
+ (await ask(interactive, {
+ type: "text",
+ name: "value",
+ message: "PLANKA instance URL",
+ }));
+ if (!plankaUrl) throw new Error("--planka-url is required");
+
+ const planka = new PlankaClient({
+ baseUrl: plankaUrl,
+ ...(args.plankaToken ? { token: args.plankaToken } : {}),
+ });
+
+ if (!args.plankaToken) {
+ const user =
+ args.plankaUser ??
+ (await ask(interactive, {
+ type: "text",
+ name: "value",
+ message: "PLANKA email or username",
+ }));
+ if (!user) throw new Error("--planka-user is required");
+
+ const password =
+ args.plankaPassword ??
+ process.env.PLANKA_PASSWORD ??
+ (await ask(interactive, {
+ type: "password",
+ name: "value",
+ message: "PLANKA password",
+ }));
+ if (!password) throw new Error("--planka-password is required");
+
+ await planka.login(user, password);
+ log("Authenticated with PLANKA");
+ }
+
+ const bundle = await planka.listProjects();
+ const boards = bundle.included.boards ?? [];
+ const boardCounts = new Map<string, number>();
+ for (const board of boards) {
+ boardCounts.set(
+ board.projectId,
+ (boardCounts.get(board.projectId) ?? 0) + 1,
+ );
+ }
+
+ const allTargets: BoardTarget[] = [];
+ for (const project of bundle.items) {
+ for (const board of boards.filter((b) => b.projectId === project.id)) {
+ allTargets.push({
+ project,
+ board,
+ boardCountInProject: boardCounts.get(project.id) ?? 1,
+ });
+ }
+ }
+
+ if (allTargets.length === 0) {
+ log("No boards found in PLANKA for this account.");
+ return 0;
+ }
+
+ const targets = await selectTargets(allTargets, args, interactive);
+ if (targets.length === 0) {
+ log("Nothing selected.");
+ return 0;
+ }
+
+ const kaneoApiKey = args.kaneoApiKey ?? process.env.KANEO_API_KEY;
+ if (!kaneoApiKey && !args.dryRun) {
+ throw new Error(
+ "A Kaneo API key is required. Pass --kaneo-api-key or set KANEO_API_KEY.",
+ );
+ }
+
+ const kaneo = new KaneoClient({
+ baseUrl: args.kaneoUrl ?? "https://app.kaneo.app",
+ apiKey: kaneoApiKey ?? "",
+ });
+
+ let workspaceId = args.workspace ?? "";
+ if (!args.dryRun && !workspaceId) {
+ workspaceId = await selectWorkspace(kaneo, interactive);
+ }
+
+ // The dry run reads PLANKA only, so it can run before a Kaneo key exists and
+ // is the honest way to show what an import would do.
+ const preview = await migrate({
+ planka,
+ kaneo,
+ workspaceId,
+ targets,
+ dryRun: true,
+ skipComments: args.skipComments,
+ onProgress: () => {},
+ });
+
+ printPlan(preview);
+
+ if (args.dryRun) {
+ await writeReport(args.report, preview);
+ log("Dry run — nothing was written to Kaneo.");
+ return 0;
+ }
+
+ if (!args.yes) {
+ const confirmed = await confirm(
+ interactive,
+ `Import ${targets.length} board(s) into Kaneo workspace ${workspaceId}?`,
+ );
+ if (!confirmed) {
+ log("Aborted.");
+ return 1;
+ }
+ }
+
+ const reports = await migrate({
+ planka,
+ kaneo,
+ workspaceId,
+ targets,
+ dryRun: false,
+ skipComments: args.skipComments,
+ ...(args.icon ? { projectIcon: args.icon } : {}),
+ onProgress: progress,
+ });
+
+ clearProgress();
+ printResults(reports);
+ await writeReport(args.report, reports);
+
+ return reports.some((report) => report.failed) ? 1 : 0;
+}
+
+async function selectTargets(
+ allTargets: BoardTarget[],
+ args: ReturnType<typeof parseArgs>,
+ interactive: boolean,
+): Promise<BoardTarget[]> {
+ if (args.projects.length > 0) {
+ const wanted = args.projects.map((value) => value.toLowerCase());
+ const matched = allTargets.filter(
+ (target) =>
+ wanted.includes(target.project.name.toLowerCase()) ||
+ wanted.includes(target.project.id.toLowerCase()),
+ );
+
+ if (matched.length === 0) {
+ throw new Error(
+ `No PLANKA project matched: ${args.projects.join(", ")}. Available: ${[
+ ...new Set(allTargets.map((target) => target.project.name)),
+ ].join(", ")}`,
+ );
+ }
+ return matched;
+ }
+
+ if (args.all || !interactive) return allTargets;
+
+ const answer = await prompts({
+ type: "multiselect",
+ name: "value",
+ message: "Select boards to migrate",
+ instructions: false,
+ choices: allTargets.map((target) => ({
+ title: `${target.project.name} › ${target.board.name}`,
+ value: target,
+ selected: true,
+ })),
+ });
+
+ return (answer.value as BoardTarget[] | undefined) ?? [];
+}
+
+async function selectWorkspace(
+ kaneo: KaneoClient,
+ interactive: boolean,
+): Promise<string> {
+ const workspaces = await kaneo.listWorkspaces();
+
+ if (workspaces.length === 0) {
+ throw new Error("This Kaneo account has no workspaces.");
+ }
+
+ const first = workspaces[0];
+ if (workspaces.length === 1 && first) return first.id;
+
+ if (!interactive) {
+ throw new Error(
+ `Several workspaces are available; pass --workspace with one of: ${workspaces
+ .map((workspace) => `${workspace.name} (${workspace.id})`)
+ .join(", ")}`,
+ );
+ }
+
+ const answer = await prompts({
+ type: "select",
+ name: "value",
+ message: "Target Kaneo workspace",
+ choices: workspaces.map((workspace) => ({
+ title: workspace.name,
+ value: workspace.id,
+ })),
+ });
+
+ const chosen = answer.value as string | undefined;
+ if (!chosen) throw new Error("No workspace selected.");
+ return chosen;
+}
+
+function printPlan(reports: BoardReport[]): void {
+ log("");
+ log("Planned import:");
+ for (const report of reports) {
+ if (report.failed) {
+ log(` ✖ ${report.projectName}: ${report.error}`);
+ continue;
+ }
+ log(
+ ` • ${report.projectName} ${report.columns} columns ${report.tasks} tasks ${report.labels} labels ${report.comments} comments`,
+ );
+ for (const warning of report.warnings) log(` ! ${warning}`);
+ if (report.skippedLists.length > 0) {
+ log(
+ ` – skipping ${report.skippedLists.join(", ")} (archive/trash lists are not migrated)`,
+ );
+ }
+ if (report.skippedAttachments > 0) {
+ log(
+ ` – ${report.skippedAttachments} attachment(s) will not be migrated`,
+ );
+ }
+ }
+ log("");
+}
+
+function printResults(reports: BoardReport[]): void {
+ log("");
+ for (const report of reports) {
+ if (report.failed) {
+ log(`✖ ${report.projectName}: ${report.error}`);
+ continue;
+ }
+ log(
+ `✔ ${report.projectName} (${report.projectKey}) ${report.columns} columns ${report.tasks} tasks ${report.labels} labels ${report.comments} comments ${report.assignees} assignees`,
+ );
+ }
+
+ const failed = reports.filter((report) => report.failed).length;
+ log("");
+ log(
+ failed > 0
+ ? `Finished with ${failed} failed board(s).`
+ : "Finished. Everything imported.",
+ );
+}
+
+async function writeReport(
+ path: string | undefined,
+ reports: BoardReport[],
+): Promise<void> {
+ if (!path) return;
+ await writeFile(path, `${JSON.stringify(reports, null, 2)}\n`, "utf8");
+ log(`Report written to ${path}`);
+}
+
+let progressActive = false;
+
+function progress(message: string): void {
+ if (!process.stdout.isTTY) return;
+ process.stdout.write(`\r\u001B[2K${message}`);
+ progressActive = true;
+}
+
+function clearProgress(): void {
+ if (progressActive && process.stdout.isTTY) {
+ process.stdout.write("\r\u001B[2K");
+ progressActive = false;
+ }
+}
+
+function log(message: string): void {
+ clearProgress();
+ process.stdout.write(`${message}\n`);
+}
+
+async function ask(
+ interactive: boolean,
+ question: prompts.PromptObject,
+): Promise<string | undefined> {
+ if (!interactive) return undefined;
+ const answer = await prompts(question);
+ const value = answer.value as string | undefined;
+ return value?.trim() || undefined;
+}
+
+async function confirm(
+ interactive: boolean,
+ message: string,
+): Promise<boolean> {
+ if (!interactive) return true;
+ const answer = await prompts({
+ type: "confirm",
+ name: "value",
+ message,
+ initial: true,
+ });
+ return answer.value === true;
+}
+
+main()
+ .then((code) => {
+ process.exitCode = code;
+ })
+ .catch((error: unknown) => {
+ clearProgress();
+ process.stderr.write(
+ `${error instanceof Error ? error.message : String(error)}\n`,
+ );
+ process.exitCode = 1;
+ });
diff --git a/packages/planka-import/src/kaneo.ts b/packages/planka-import/src/kaneo.ts
new file mode 100644
index 000000000..19b89fcd0
--- /dev/null
+++ b/packages/planka-import/src/kaneo.ts
@@ -0,0 +1,177 @@
+export type KaneoWorkspace = { id: string; name: string; slug?: string };
+export type KaneoProject = { id: string; name: string; slug: string };
+export type KaneoColumn = { id: string; name: string; slug: string };
+export type KaneoTask = { id: string; title: string; number: number };
+export type KaneoLabel = { id: string; name: string; color: string };
+export type KaneoMember = { id: string; name: string; email: string };
+
+/** Kaneo API base URL without trailing slash and without `/api` suffix. */
+export function normalizeBaseUrl(raw: string): string {
+ const trimmed = raw.trim().replace(/\/+$/, "");
+ try {
+ const url = new URL(trimmed);
+ let path = url.pathname.replace(/\/+$/, "");
+ if (path === "/api" || path.endsWith("/api")) {
+ path = path.replace(/\/?api$/, "") || "/";
+ }
+ return `${url.protocol}//${url.host}${path === "/" ? "" : path}`;
+ } catch {
+ return trimmed.replace(/\/api\/?$/, "").replace(/\/+$/, "");
+ }
+}
+
+export class KaneoClient {
+ readonly baseUrl: string;
+ private readonly apiKey: string;
+
+ constructor(options: { baseUrl: string; apiKey: string }) {
+ this.baseUrl = normalizeBaseUrl(options.baseUrl);
+ this.apiKey = options.apiKey;
+ }
+
+ listWorkspaces(): Promise<KaneoWorkspace[]> {
+ return this.request<KaneoWorkspace[]>("/api/auth/organization/list");
+ }
+
+ listProjects(workspaceId: string): Promise<KaneoProject[]> {
+ return this.request<KaneoProject[]>(
+ `/api/project?workspaceId=${encodeURIComponent(workspaceId)}`,
+ );
+ }
+
+ listMembers(workspaceId: string): Promise<KaneoMember[]> {
+ return this.request<KaneoMember[]>(
+ `/api/workspace/${encodeURIComponent(workspaceId)}/members`,
+ );
+ }
+
+ createProject(input: {
+ name: string;
+ workspaceId: string;
+ icon: string;
+ slug: string;
+ }): Promise<KaneoProject> {
+ return this.request<KaneoProject>("/api/project", {
+ method: "POST",
+ body: JSON.stringify(input),
+ });
+ }
+
+ listColumns(projectId: string): Promise<KaneoColumn[]> {
+ return this.request<KaneoColumn[]>(
+ `/api/column/${encodeURIComponent(projectId)}`,
+ );
+ }
+
+ createColumn(
+ projectId: string,
+ input: { name: string; isFinal?: boolean },
+ ): Promise<KaneoColumn> {
+ return this.request<KaneoColumn>(
+ `/api/column/${encodeURIComponent(projectId)}`,
+ { method: "POST", body: JSON.stringify(input) },
+ );
+ }
+
+ deleteColumn(columnId: string): Promise<unknown> {
+ return this.request(`/api/column/${encodeURIComponent(columnId)}`, {
+ method: "DELETE",
+ });
+ }
+
+ createTask(
+ projectId: string,
+ input: {
+ title: string;
+ description: string;
+ status: string;
+ priority: string;
+ dueDate?: string;
+ userId?: string;
+ },
+ ): Promise<KaneoTask> {
+ return this.request<KaneoTask>(
+ `/api/task/${encodeURIComponent(projectId)}`,
+ { method: "POST", body: JSON.stringify(input) },
+ );
+ }
+
+ /**
+ * Idempotent in both scopes: without `taskId` it upserts the workspace-level
+ * label, with `taskId` it upserts the label on that task. We never use
+ * PUT /label/:id/task, which *moves* an existing label row and would detach
+ * it from whichever task already had it.
+ */
+ createLabel(input: {
+ name: string;
+ color: string;
+ workspaceId: string;
+ taskId?: string;
+ }): Promise<KaneoLabel> {
+ return this.request<KaneoLabel>("/api/label", {
+ method: "POST",
+ body: JSON.stringify(input),
+ });
+ }
+
+ createComment(taskId: string, content: string): Promise<unknown> {
+ return this.request(`/api/comment/${encodeURIComponent(taskId)}`, {
+ method: "POST",
+ body: JSON.stringify({ content }),
+ });
+ }
+
+ private async request<T>(path: string, init?: RequestInit): Promise<T> {
+ const headers = new Headers(init?.headers);
+ headers.set("Authorization", `Bearer ${this.apiKey}`);
+ headers.set("Accept", "application/json");
+ if (init?.body != null && !headers.has("Content-Type")) {
+ headers.set("Content-Type", "application/json");
+ }
+
+ let res: Response;
+ try {
+ res = await fetch(`${this.baseUrl}${path}`, {
+ ...init,
+ headers,
+ signal: AbortSignal.timeout(30_000),
+ });
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ throw new Error(`Kaneo ${path}: ${reason}`);
+ }
+
+ const text = await res.text();
+ let body: unknown = null;
+ if (text) {
+ try {
+ body = JSON.parse(text) as unknown;
+ } catch {
+ body = text;
+ }
+ }
+
+ if (!res.ok) {
+ throw new Error(`Kaneo ${path}: ${describeError(body, res.status)}`);
+ }
+
+ return body as T;
+ }
+}
+
+function describeError(body: unknown, status: number): string {
+ if (status === 401) {
+ return "unauthorized (HTTP 401) — check your Kaneo API key";
+ }
+ if (typeof body === "object" && body !== null) {
+ const record = body as Record<string, unknown>;
+ for (const key of ["message", "error"]) {
+ const value = record[key];
+ if (typeof value === "string" && value.length > 0) return value;
+ }
+ }
+ if (typeof body === "string" && body.length > 0) {
+ return body.length > 300 ? `${body.slice(0, 300)}…` : body;
+ }
+ return `HTTP ${status}`;
+}
diff --git a/packages/planka-import/src/keys.test.ts b/packages/planka-import/src/keys.test.ts
new file mode 100644
index 000000000..17d2fe9ec
--- /dev/null
+++ b/packages/planka-import/src/keys.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from "vitest";
+import { toColumnSlug, toProjectKey, uniqueKey } from "./keys.js";
+
+describe("toColumnSlug", () => {
+ it("lowercases and hyphenates", () => {
+ expect(toColumnSlug("In Progress")).toBe("in-progress");
+ expect(toColumnSlug("To Do")).toBe("to-do");
+ });
+
+ it("strips punctuation and edge hyphens", () => {
+ expect(toColumnSlug(" Ready?! for review ")).toBe("ready-for-review");
+ expect(toColumnSlug("--Done--")).toBe("done");
+ });
+
+ it("keeps non-latin letters", () => {
+ expect(toColumnSlug("Готово")).toBe("готово");
+ });
+
+ it("returns empty for names with no alphanumerics", () => {
+ expect(toColumnSlug("???")).toBe("");
+ expect(toColumnSlug(" ")).toBe("");
+ });
+});
+
+describe("toProjectKey", () => {
+ it("uses initials for multi-word names", () => {
+ expect(toProjectKey("Marketing Website Redesign")).toBe("MWR");
+ });
+
+ it("uses a prefix for single-word names", () => {
+ expect(toProjectKey("Engineering")).toBe("ENGINEER");
+ });
+
+ it("caps at 8 characters", () => {
+ expect(toProjectKey("a b c d e f g h i j k").length).toBeLessThanOrEqual(8);
+ });
+
+ it("falls back when the name has nothing usable", () => {
+ expect(toProjectKey("???")).toBe("PROJ");
+ expect(toProjectKey("")).toBe("PROJ");
+ });
+});
+
+describe("uniqueKey", () => {
+ it("returns the candidate when free", () => {
+ expect(uniqueKey("ENG", new Set())).toBe("ENG");
+ });
+
+ it("suffixes on collision", () => {
+ expect(uniqueKey("ENG", new Set(["ENG"]))).toBe("ENG-2");
+ expect(uniqueKey("ENG", new Set(["ENG", "ENG-2"]))).toBe("ENG-3");
+ });
+
+ it("stays within the length cap when suffixing", () => {
+ const result = uniqueKey("ENGINEER", new Set(["ENGINEER"]));
+ expect(result.length).toBeLessThanOrEqual(8);
+ expect(result).toBe("ENGINE-2");
+ });
+});
diff --git a/packages/planka-import/src/keys.ts b/packages/planka-import/src/keys.ts
new file mode 100644
index 000000000..4b9763aac
--- /dev/null
+++ b/packages/planka-import/src/keys.ts
@@ -0,0 +1,56 @@
+// Mirrors `toSlug` in apps/api/src/column/controllers/create-column.ts. Kaneo
+// derives a column's slug from its name server-side, and tasks reference the
+// column by that slug, so we have to predict it to place cards correctly.
+export function toColumnSlug(name: string): string {
+ const slug = name
+ .normalize("NFKC")
+ .toLowerCase()
+ .trim()
+ .replace(/[^\p{L}\p{M}\p{N}]+/gu, "-")
+ .replace(/^-+|-+$/g, "");
+
+ return /[\p{L}\p{N}]/u.test(slug) ? slug : "";
+}
+
+// Kaneo rejects these as column slugs: they are virtual task statuses.
+export const RESERVED_COLUMN_SLUGS = ["planned", "archived"];
+
+const PROJECT_KEY_MAX = 8;
+
+// Kaneo's project "key" is the short prefix on task references (ENG-14). PLANKA
+// has no equivalent, so we synthesise one: initials for multi-word names,
+// otherwise a prefix of the name.
+export function toProjectKey(name: string): string {
+ const words = name
+ .normalize("NFKC")
+ .replace(/[^\p{L}\p{N}\s]+/gu, " ")
+ .trim()
+ .split(/\s+/u)
+ .filter(Boolean);
+
+ if (words.length === 0) return "PROJ";
+
+ const key =
+ words.length > 1
+ ? words.map((word) => word[0]).join("")
+ : (words[0] as string);
+
+ const normalized = key.toUpperCase().slice(0, PROJECT_KEY_MAX);
+ return normalized.length > 0 ? normalized : "PROJ";
+}
+
+// Appends -2, -3, … until the candidate is free, respecting the field's cap.
+export function uniqueKey(
+ candidate: string,
+ taken: Set<string>,
+ maxLength = PROJECT_KEY_MAX,
+): string {
+ if (!taken.has(candidate)) return candidate;
+
+ for (let suffix = 2; ; suffix++) {
+ const tail = String(suffix);
+ const head = candidate.slice(0, Math.max(1, maxLength - tail.length - 1));
+ const next = `${head}-${tail}`;
+ if (!taken.has(next)) return next;
+ }
+}
diff --git a/packages/planka-import/src/mapping.test.ts b/packages/planka-import/src/mapping.test.ts
new file mode 100644
index 000000000..7579de55a
--- /dev/null
+++ b/packages/planka-import/src/mapping.test.ts
@@ -0,0 +1,197 @@
+import { describe, expect, it } from "vitest";
+import {
+ boardProjectName,
+ buildDescription,
+ formatComment,
+ planColumns,
+ sortCards,
+ toDueDate,
+} from "./mapping.js";
+import type { PlankaCard, PlankaList } from "./planka.js";
+
+function list(partial: Partial<PlankaList> & { id: string }): PlankaList {
+ return {
+ boardId: "b1",
+ name: "List",
+ type: "active",
+ position: 0,
+ color: null,
+ ...partial,
+ };
+}
+
+function card(partial: Partial<PlankaCard> & { id: string }): PlankaCard {
+ return {
+ boardId: "b1",
+ listId: "l1",
+ name: "Card",
+ description: null,
+ position: 0,
+ dueDate: null,
+ isDueCompleted: null,
+ isClosed: null,
+ commentsTotal: 0,
+ ...partial,
+ };
+}
+
+describe("planColumns", () => {
+ it("orders by position and marks closed lists as final", () => {
+ const planned = planColumns([
+ list({ id: "b", name: "Done", type: "closed", position: 2 }),
+ list({ id: "a", name: "To Do", position: 1 }),
+ ]);
+
+ expect(planned.map((column) => column.slug)).toEqual(["to-do", "done"]);
+ expect(planned.map((column) => column.isFinal)).toEqual([false, true]);
+ });
+
+ it("renames lists whose slug is a reserved virtual status", () => {
+ const [planned] = planColumns([list({ id: "a", name: "Planned" })]);
+
+ expect(planned?.slug).toBe("planned-list");
+ expect(planned?.renamedFrom).toBe("Planned");
+ });
+
+ it("disambiguates lists that would collide on slug", () => {
+ const planned = planColumns([
+ list({ id: "a", name: "In Review", position: 0 }),
+ list({ id: "b", name: "in review", position: 1 }),
+ list({ id: "c", name: "In Review", position: 2 }),
+ ]);
+
+ expect(new Set(planned.map((column) => column.slug)).size).toBe(3);
+ expect(planned[1]?.renamedFrom).toBe("in review");
+ });
+
+ it("falls back to a usable name when the list name has no alphanumerics", () => {
+ const [planned] = planColumns([list({ id: "a", name: "???" })]);
+
+ expect(planned?.slug).toBe("untitled");
+ });
+
+ it("handles a null list name", () => {
+ const [planned] = planColumns([list({ id: "a", name: null })]);
+
+ expect(planned?.slug).toBe("untitled");
+ });
+});
+
+describe("sortCards", () => {
+ it("sorts by position without mutating the input", () => {
+ const input = [
+ card({ id: "b", position: 2 }),
+ card({ id: "a", position: 1 }),
+ ];
+ const sorted = sortCards(input);
+
+ expect(sorted.map((c) => c.id)).toEqual(["a", "b"]);
+ expect(input.map((c) => c.id)).toEqual(["b", "a"]);
+ });
+});
+
+describe("buildDescription", () => {
+ it("returns the description alone when there are no checklists", () => {
+ const result = buildDescription(
+ card({ id: "a", description: "Ship it" }),
+ [],
+ [],
+ );
+
+ expect(result).toBe("Ship it");
+ });
+
+ it("appends checklists as markdown checkboxes in position order", () => {
+ const result = buildDescription(
+ card({ id: "a", description: "Ship it" }),
+ [{ id: "tl1", cardId: "a", name: "Steps" }],
+ [
+ {
+ id: "t2",
+ taskListId: "tl1",
+ name: "Second",
+ isCompleted: false,
+ position: 2,
+ },
+ {
+ id: "t1",
+ taskListId: "tl1",
+ name: "First",
+ isCompleted: true,
+ position: 1,
+ },
+ ],
+ );
+
+ expect(result).toBe("Ship it\n\n## Steps\n\n- [x] First\n- [ ] Second");
+ });
+
+ it("skips empty checklists and handles a card with no description", () => {
+ const result = buildDescription(
+ card({ id: "a", description: null }),
+ [{ id: "tl1", cardId: "a", name: "Empty" }],
+ [],
+ );
+
+ expect(result).toBe("");
+ });
+});
+
+describe("formatComment", () => {
+ it("preserves the original author and date", () => {
+ const result = formatComment(
+ {
+ id: "c1",
+ cardId: "a",
+ userId: "u1",
+ text: "Looks good",
+ createdAt: "2026-03-04T10:00:00.000Z",
+ },
+ { id: "u1", email: "[email protected]", name: "Sam", username: null },
+ );
+
+ expect(result).toBe(
+ "**Sam** on 2026-03-04 (imported from PLANKA)\n\nLooks good",
+ );
+ });
+
+ it("falls back when the author is unknown", () => {
+ const result = formatComment(
+ {
+ id: "c1",
+ cardId: "a",
+ userId: null,
+ text: "Orphaned",
+ createdAt: null,
+ },
+ undefined,
+ );
+
+ expect(result).toBe("**Unknown user** (imported from PLANKA)\n\nOrphaned");
+ });
+});
+
+describe("toDueDate", () => {
+ it("normalizes a valid due date", () => {
+ expect(
+ toDueDate(card({ id: "a", dueDate: "2026-03-04T10:00:00.000Z" })),
+ ).toBe("2026-03-04T10:00:00.000Z");
+ });
+
+ it("drops missing or unparseable dates", () => {
+ expect(toDueDate(card({ id: "a", dueDate: null }))).toBeUndefined();
+ expect(toDueDate(card({ id: "a", dueDate: "not-a-date" }))).toBeUndefined();
+ });
+});
+
+describe("boardProjectName", () => {
+ it("uses the project name when it has a single board", () => {
+ expect(boardProjectName("Marketing", "Main", 1)).toBe("Marketing");
+ });
+
+ it("qualifies with the board name when the project has several", () => {
+ expect(boardProjectName("Marketing", "Campaigns", 3)).toBe(
+ "Marketing – Campaigns",
+ );
+ });
+});
diff --git a/packages/planka-import/src/mapping.ts b/packages/planka-import/src/mapping.ts
new file mode 100644
index 000000000..1fb9b3e99
--- /dev/null
+++ b/packages/planka-import/src/mapping.ts
@@ -0,0 +1,143 @@
+import { RESERVED_COLUMN_SLUGS, toColumnSlug } from "./keys.js";
+import type {
+ PlankaCard,
+ PlankaComment,
+ PlankaList,
+ PlankaTask,
+ PlankaTaskList,
+ PlankaUser,
+} from "./planka.js";
+
+export type PlannedColumn = {
+ listId: string;
+ name: string;
+ slug: string;
+ isFinal: boolean;
+ renamedFrom?: string;
+};
+
+const UNTITLED_COLUMN = "Untitled";
+
+/**
+ * Turns PLANKA lists into the columns we will create, in board order.
+ *
+ * Kaneo derives a column's slug from its name and rejects duplicates and the
+ * reserved virtual statuses, so a name that would collide has to be adjusted
+ * here rather than fixed up after the fact.
+ */
+export function planColumns(lists: PlankaList[]): PlannedColumn[] {
+ const ordered = [...lists].sort(
+ (a, b) => (a.position ?? 0) - (b.position ?? 0),
+ );
+
+ const takenSlugs = new Set<string>();
+ const planned: PlannedColumn[] = [];
+
+ for (const list of ordered) {
+ const original = list.name?.trim() || UNTITLED_COLUMN;
+ let name = toColumnSlug(original) ? original : UNTITLED_COLUMN;
+
+ if (RESERVED_COLUMN_SLUGS.includes(toColumnSlug(name))) {
+ name = `${name} list`;
+ }
+
+ let slug = toColumnSlug(name);
+ for (let suffix = 2; takenSlugs.has(slug); suffix++) {
+ name = `${name.replace(/ \d+$/, "")} ${suffix}`;
+ slug = toColumnSlug(name);
+ }
+
+ takenSlugs.add(slug);
+ planned.push({
+ listId: list.id,
+ name,
+ slug,
+ isFinal: list.type === "closed",
+ ...(name !== original ? { renamedFrom: original } : {}),
+ });
+ }
+
+ return planned;
+}
+
+/** Cards in the order they appear on the board. */
+export function sortCards(cards: PlankaCard[]): PlankaCard[] {
+ return [...cards].sort((a, b) => (a.position ?? 0) - (b.position ?? 0));
+}
+
+/**
+ * Kaneo has no checklist primitive, so PLANKA's task lists are appended to the
+ * description as markdown checkboxes instead of being dropped.
+ */
+export function buildDescription(
+ card: PlankaCard,
+ taskLists: PlankaTaskList[],
+ tasks: PlankaTask[],
+): string {
+ const sections: string[] = [];
+ const description = card.description?.trim();
+ if (description) sections.push(description);
+
+ for (const taskList of taskLists) {
+ const items = tasks
+ .filter((task) => task.taskListId === taskList.id)
+ .sort((a, b) => a.position - b.position);
+
+ if (items.length === 0) continue;
+
+ const lines = items.map(
+ (item) => `- [${item.isCompleted ? "x" : " "}] ${item.name}`,
+ );
+ sections.push(`## ${taskList.name}\n\n${lines.join("\n")}`);
+ }
+
+ return sections.join("\n\n");
+}
+
+export function displayName(user: PlankaUser | undefined): string {
+ if (!user) return "Unknown user";
+ return (
+ user.name?.trim() || user.username?.trim() || user.email || "Unknown user"
+ );
+}
+
+/**
+ * Comments are re-created under the API key's owner, so the original author and
+ * date are preserved in the body rather than silently lost.
+ */
+export function formatComment(
+ comment: PlankaComment,
+ author: PlankaUser | undefined,
+): string {
+ const date = comment.createdAt
+ ? new Date(comment.createdAt).toISOString().slice(0, 10)
+ : null;
+ const attribution = date
+ ? `**${displayName(author)}** on ${date} (imported from PLANKA)`
+ : `**${displayName(author)}** (imported from PLANKA)`;
+
+ return `${attribution}\n\n${comment.text}`;
+}
+
+/** PLANKA has no priority field; Kaneo requires one on create. */
+export const DEFAULT_PRIORITY = "no-priority";
+
+export function toDueDate(card: PlankaCard): string | undefined {
+ if (!card.dueDate) return undefined;
+ const parsed = new Date(card.dueDate);
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString();
+}
+
+/**
+ * A Kaneo project maps to a PLANKA board, not a PLANKA project, because the
+ * board is what holds lists and cards. The project name is only worth
+ * prefixing when it would otherwise be ambiguous.
+ */
+export function boardProjectName(
+ projectName: string,
+ boardName: string,
+ boardCountInProject: number,
+): string {
+ if (boardCountInProject <= 1) return projectName;
+ return `${projectName} – ${boardName}`;
+}
diff --git a/packages/planka-import/src/migrate.test.ts b/packages/planka-import/src/migrate.test.ts
new file mode 100644
index 000000000..1751ee352
--- /dev/null
+++ b/packages/planka-import/src/migrate.test.ts
@@ -0,0 +1,371 @@
+import { describe, expect, it } from "vitest";
+import type { KaneoClient } from "./kaneo.js";
+import { migrate } from "./migrate.js";
+import type { BoardBundle, PlankaClient } from "./planka.js";
+
+type Call = { method: string; args: unknown[] };
+
+function fakeKaneo(calls: Call[]) {
+ let taskCounter = 0;
+ const record = (method: string, ...args: unknown[]) => {
+ calls.push({ method, args });
+ };
+
+ return {
+ async listProjects() {
+ record("listProjects");
+ return [{ id: "p_existing", name: "Existing", slug: "MWR" }];
+ },
+ async listMembers() {
+ record("listMembers");
+ return [{ id: "ku_1", name: "Sam", email: "[email protected]" }];
+ },
+ async createProject(input: unknown) {
+ record("createProject", input);
+ return { id: "p_new", name: "Board", slug: "B" };
+ },
+ async listColumns() {
+ record("listColumns");
+ return [
+ { id: "c_default_1", name: "To Do", slug: "to-do" },
+ { id: "c_default_2", name: "Done", slug: "done" },
+ ];
+ },
+ async deleteColumn(id: string) {
+ record("deleteColumn", id);
+ return {};
+ },
+ async createColumn(_projectId: string, input: unknown) {
+ record("createColumn", input);
+ return { id: "c_new", name: "x", slug: "x" };
+ },
+ async createTask(_projectId: string, input: unknown) {
+ record("createTask", input);
+ taskCounter++;
+ return { id: `t_${taskCounter}`, title: "t", number: taskCounter };
+ },
+ async createLabel(input: unknown) {
+ record("createLabel", input);
+ return { id: "l_1", name: "l", color: "#000000" };
+ },
+ async createComment(taskId: string, content: string) {
+ record("createComment", taskId, content);
+ return {};
+ },
+ } as unknown as KaneoClient;
+}
+
+function fakePlanka(bundle: BoardBundle, comments: unknown[] = []) {
+ return {
+ async getBoard() {
+ return bundle;
+ },
+ async listComments() {
+ return {
+ comments,
+ users: [],
+ };
+ },
+ } as unknown as PlankaClient;
+}
+
+const board = { id: "b1", projectId: "pr1", name: "Main", position: 0 };
+const project = { id: "pr1", name: "Marketing Website Redesign" };
+
+function bundleWith(overrides: Partial<BoardBundle["included"]>): BoardBundle {
+ return {
+ item: board,
+ included: {
+ lists: [
+ {
+ id: "l1",
+ boardId: "b1",
+ name: "Backlog",
+ type: "active",
+ position: 1,
+ color: null,
+ },
+ {
+ id: "l2",
+ boardId: "b1",
+ name: "Shipped",
+ type: "closed",
+ position: 2,
+ color: null,
+ },
+ {
+ id: "l3",
+ boardId: "b1",
+ name: "Archive",
+ type: "archive",
+ position: 3,
+ color: null,
+ },
+ ],
+ cards: [
+ {
+ id: "card1",
+ boardId: "b1",
+ listId: "l1",
+ name: "Write copy",
+ description: "Homepage",
+ position: 1,
+ dueDate: null,
+ isDueCompleted: null,
+ isClosed: null,
+ commentsTotal: 0,
+ },
+ ],
+ ...overrides,
+ },
+ };
+}
+
+const target = { project, board, boardCountInProject: 1 };
+
+describe("migrate (dry run)", () => {
+ it("reports counts without calling Kaneo", async () => {
+ const calls: Call[] = [];
+ const [report] = await migrate({
+ planka: fakePlanka(bundleWith({})),
+ kaneo: fakeKaneo(calls),
+ workspaceId: "ws_1",
+ targets: [target],
+ dryRun: true,
+ skipComments: false,
+ });
+
+ expect(calls).toEqual([]);
+ expect(report?.columns).toBe(2);
+ expect(report?.tasks).toBe(1);
+ expect(report?.skippedLists).toEqual(["Archive"]);
+ });
+
+ it("counts comments from the denormalized card total", async () => {
+ const bundle = bundleWith({});
+ const [firstCard] = bundle.included.cards ?? [];
+ if (firstCard) firstCard.commentsTotal = 4;
+
+ const [report] = await migrate({
+ planka: fakePlanka(bundle),
+ kaneo: fakeKaneo([]),
+ workspaceId: "ws_1",
+ targets: [target],
+ dryRun: true,
+ skipComments: false,
+ });
+
+ expect(report?.comments).toBe(4);
+ });
+});
+
+describe("migrate (write)", () => {
+ it("removes Kaneo's seeded columns before creating the PLANKA ones", async () => {
+ const calls: Call[] = [];
+ await migrate({
+ planka: fakePlanka(bundleWith({})),
+ kaneo: fakeKaneo(calls),
+ workspaceId: "ws_1",
+ targets: [target],
+ dryRun: false,
+ skipComments: false,
+ });
+
+ const sequence = calls.map((call) => call.method);
+ const lastDelete = sequence.lastIndexOf("deleteColumn");
+ const firstCreate = sequence.indexOf("createColumn");
+
+ expect(sequence.filter((m) => m === "deleteColumn")).toHaveLength(2);
+ expect(lastDelete).toBeLessThan(firstCreate);
+
+ const created = calls
+ .filter((call) => call.method === "createColumn")
+ .map((call) => call.args[0]);
+ expect(created).toEqual([
+ { name: "Backlog", isFinal: false },
+ { name: "Shipped", isFinal: true },
+ ]);
+ });
+
+ it("avoids a project key that is already taken in the workspace", async () => {
+ const calls: Call[] = [];
+ const [report] = await migrate({
+ planka: fakePlanka(bundleWith({})),
+ kaneo: fakeKaneo(calls),
+ workspaceId: "ws_1",
+ targets: [target],
+ dryRun: false,
+ skipComments: false,
+ });
+
+ // "Marketing Website Redesign" -> MWR, which the fake workspace already has.
+ expect(report?.projectKey).toBe("MWR-2");
+ });
+
+ it("attaches labels via createLabel so existing labels are never moved", async () => {
+ const calls: Call[] = [];
+ await migrate({
+ planka: fakePlanka(
+ bundleWith({
+ labels: [
+ {
+ id: "lab1",
+ boardId: "b1",
+ name: "Urgent",
+ color: "berry-red",
+ position: 1,
+ },
+ ],
+ cardLabels: [{ cardId: "card1", labelId: "lab1" }],
+ }),
+ ),
+ kaneo: fakeKaneo(calls),
+ workspaceId: "ws_1",
+ targets: [target],
+ dryRun: false,
+ skipComments: false,
+ });
+
+ const labelCalls = calls
+ .filter((call) => call.method === "createLabel")
+ .map((call) => call.args[0]);
+
+ expect(labelCalls).toEqual([
+ { name: "Urgent", color: "#e83855", workspaceId: "ws_1" },
+ { name: "Urgent", color: "#e83855", workspaceId: "ws_1", taskId: "t_1" },
+ ]);
+ });
+
+ it("resolves an assignee by email, case-insensitively", async () => {
+ const calls: Call[] = [];
+ const [report] = await migrate({
+ planka: fakePlanka(
+ bundleWith({
+ cardMemberships: [{ cardId: "card1", userId: "pu1" }],
+ users: [
+ {
+ id: "pu1",
+ email: "[email protected]",
+ name: "Sam",
+ username: null,
+ },
+ ],
+ }),
+ ),
+ kaneo: fakeKaneo(calls),
+ workspaceId: "ws_1",
+ targets: [target],
+ dryRun: false,
+ skipComments: false,
+ });
+
+ const task = calls.find((call) => call.method === "createTask")
+ ?.args[0] as { userId?: string };
+ expect(task.userId).toBe("ku_1");
+ expect(report?.assignees).toBe(1);
+ });
+
+ it("leaves the task unassigned when the member is not in the workspace", async () => {
+ const calls: Call[] = [];
+ await migrate({
+ planka: fakePlanka(
+ bundleWith({
+ cardMemberships: [{ cardId: "card1", userId: "pu9" }],
+ users: [
+ {
+ id: "pu9",
+ email: "[email protected]",
+ name: "Nobody",
+ username: null,
+ },
+ ],
+ }),
+ ),
+ kaneo: fakeKaneo(calls),
+ workspaceId: "ws_1",
+ targets: [target],
+ dryRun: false,
+ skipComments: false,
+ });
+
+ const task = calls.find((call) => call.method === "createTask")
+ ?.args[0] as { userId?: string };
+ expect(task.userId).toBeUndefined();
+ });
+
+ it("skips cards that live in archive or trash lists", async () => {
+ const calls: Call[] = [];
+ const bundle = bundleWith({});
+ bundle.included.cards?.push({
+ id: "card2",
+ boardId: "b1",
+ listId: "l3",
+ name: "Old card",
+ description: null,
+ position: 1,
+ dueDate: null,
+ isDueCompleted: null,
+ isClosed: null,
+ commentsTotal: 0,
+ });
+
+ await migrate({
+ planka: fakePlanka(bundle),
+ kaneo: fakeKaneo(calls),
+ workspaceId: "ws_1",
+ targets: [target],
+ dryRun: false,
+ skipComments: false,
+ });
+
+ const titles = calls
+ .filter((call) => call.method === "createTask")
+ .map((call) => (call.args[0] as { title: string }).title);
+ expect(titles).toEqual(["Write copy"]);
+ });
+
+ it("does not fetch comments when the card reports none", async () => {
+ const calls: Call[] = [];
+ await migrate({
+ planka: fakePlanka(bundleWith({}), [
+ {
+ id: "cm1",
+ cardId: "card1",
+ userId: null,
+ text: "hi",
+ createdAt: null,
+ },
+ ]),
+ kaneo: fakeKaneo(calls),
+ workspaceId: "ws_1",
+ targets: [target],
+ dryRun: false,
+ skipComments: false,
+ });
+
+ expect(calls.some((call) => call.method === "createComment")).toBe(false);
+ });
+
+ it("isolates a failing board instead of aborting the whole run", async () => {
+ const failing = {
+ async getBoard() {
+ throw new Error("boom");
+ },
+ async listComments() {
+ return { comments: [], users: [] };
+ },
+ } as unknown as PlankaClient;
+
+ const reports = await migrate({
+ planka: failing,
+ kaneo: fakeKaneo([]),
+ workspaceId: "ws_1",
+ targets: [target],
+ dryRun: false,
+ skipComments: false,
+ });
+
+ expect(reports[0]?.failed).toBe(true);
+ expect(reports[0]?.error).toBe("boom");
+ });
+});
diff --git a/packages/planka-import/src/migrate.ts b/packages/planka-import/src/migrate.ts
new file mode 100644
index 000000000..a1752dd59
--- /dev/null
+++ b/packages/planka-import/src/migrate.ts
@@ -0,0 +1,342 @@
+import { labelColorToHex } from "./colors.js";
+import type { KaneoClient } from "./kaneo.js";
+import { toProjectKey, uniqueKey } from "./keys.js";
+import {
+ boardProjectName,
+ buildDescription,
+ DEFAULT_PRIORITY,
+ formatComment,
+ planColumns,
+ sortCards,
+ toDueDate,
+} from "./mapping.js";
+import {
+ MIGRATABLE_LIST_TYPES,
+ type PlankaBoard,
+ type PlankaClient,
+ type PlankaProject,
+ type PlankaUser,
+} from "./planka.js";
+
+export type BoardTarget = {
+ project: PlankaProject;
+ board: PlankaBoard;
+ boardCountInProject: number;
+};
+
+export type BoardReport = {
+ board: string;
+ project: string;
+ projectName: string;
+ projectKey: string | null;
+ kaneoProjectId: string | null;
+ columns: number;
+ tasks: number;
+ labels: number;
+ comments: number;
+ assignees: number;
+ checklistItems: number;
+ skippedLists: string[];
+ skippedAttachments: number;
+ warnings: string[];
+ failed: boolean;
+ error?: string;
+};
+
+export type MigrateOptions = {
+ planka: PlankaClient;
+ kaneo: KaneoClient;
+ workspaceId: string;
+ targets: BoardTarget[];
+ dryRun: boolean;
+ skipComments: boolean;
+ projectIcon?: string;
+ onProgress?: (message: string) => void;
+};
+
+export async function migrate(options: MigrateOptions): Promise<BoardReport[]> {
+ const {
+ planka,
+ kaneo,
+ workspaceId,
+ targets,
+ dryRun,
+ skipComments,
+ projectIcon = "Layout",
+ onProgress = () => {},
+ } = options;
+
+ const takenKeys = new Set<string>();
+ const membersByEmail = new Map<string, string>();
+
+ if (!dryRun) {
+ for (const project of await kaneo.listProjects(workspaceId)) {
+ if (project.slug) takenKeys.add(project.slug);
+ }
+ for (const member of await kaneo.listMembers(workspaceId)) {
+ if (member.email)
+ membersByEmail.set(member.email.toLowerCase(), member.id);
+ }
+ }
+
+ const reports: BoardReport[] = [];
+
+ for (const target of targets) {
+ const projectName = boardProjectName(
+ target.project.name,
+ target.board.name,
+ target.boardCountInProject,
+ );
+
+ const report: BoardReport = {
+ board: target.board.name,
+ project: target.project.name,
+ projectName,
+ projectKey: null,
+ kaneoProjectId: null,
+ columns: 0,
+ tasks: 0,
+ labels: 0,
+ comments: 0,
+ assignees: 0,
+ checklistItems: 0,
+ skippedLists: [],
+ skippedAttachments: 0,
+ warnings: [],
+ failed: false,
+ };
+
+ try {
+ await migrateBoard({
+ planka,
+ kaneo,
+ workspaceId,
+ target,
+ projectName,
+ projectIcon,
+ dryRun,
+ skipComments,
+ takenKeys,
+ membersByEmail,
+ report,
+ onProgress,
+ });
+ } catch (error) {
+ report.failed = true;
+ report.error = error instanceof Error ? error.message : String(error);
+ }
+
+ reports.push(report);
+ }
+
+ return reports;
+}
+
+async function migrateBoard(context: {
+ planka: PlankaClient;
+ kaneo: KaneoClient;
+ workspaceId: string;
+ target: BoardTarget;
+ projectName: string;
+ projectIcon: string;
+ dryRun: boolean;
+ skipComments: boolean;
+ takenKeys: Set<string>;
+ membersByEmail: Map<string, string>;
+ report: BoardReport;
+ onProgress: (message: string) => void;
+}): Promise<void> {
+ const {
+ planka,
+ kaneo,
+ workspaceId,
+ target,
+ projectName,
+ projectIcon,
+ dryRun,
+ skipComments,
+ takenKeys,
+ membersByEmail,
+ report,
+ onProgress,
+ } = context;
+
+ onProgress(`Reading board "${target.board.name}" from PLANKA`);
+ const bundle = await planka.getBoard(target.board.id);
+ const included = bundle.included;
+
+ const allLists = included.lists ?? [];
+ const migratableLists = allLists.filter((list) =>
+ MIGRATABLE_LIST_TYPES.includes(list.type),
+ );
+ report.skippedLists = allLists
+ .filter((list) => !MIGRATABLE_LIST_TYPES.includes(list.type))
+ .map((list) => list.name?.trim() || list.type);
+
+ const columns = planColumns(migratableLists);
+ for (const column of columns) {
+ if (column.renamedFrom) {
+ report.warnings.push(
+ `List "${column.renamedFrom}" was imported as column "${column.name}" to avoid a naming conflict in Kaneo.`,
+ );
+ }
+ }
+
+ const slugByListId = new Map(
+ columns.map((column) => [column.listId, column.slug]),
+ );
+
+ const cards = sortCards(
+ (included.cards ?? []).filter((card) => slugByListId.has(card.listId)),
+ );
+
+ const taskLists = included.taskLists ?? [];
+ const checklistItems = included.tasks ?? [];
+ const cardLabels = included.cardLabels ?? [];
+ const cardMemberships = included.cardMemberships ?? [];
+ const boardLabels = included.labels ?? [];
+ const usersById = new Map<string, PlankaUser>(
+ (included.users ?? []).map((user) => [user.id, user]),
+ );
+
+ report.columns = columns.length;
+ report.tasks = cards.length;
+ report.checklistItems = checklistItems.length;
+ report.skippedAttachments = (included.attachments ?? []).length;
+
+ const usedLabelIds = new Set(
+ cardLabels
+ .filter((link) => cards.some((card) => card.id === link.cardId))
+ .map((link) => link.labelId),
+ );
+ report.labels = boardLabels.filter((label) =>
+ usedLabelIds.has(label.id),
+ ).length;
+
+ if (dryRun) {
+ // The comment count is the denormalized per-card total, so a dry run can
+ // report it without fetching every card's comment thread.
+ report.comments = skipComments
+ ? 0
+ : cards.reduce((total, card) => total + (card.commentsTotal ?? 0), 0);
+ report.projectKey = toProjectKey(projectName);
+ return;
+ }
+
+ const projectKey = uniqueKey(toProjectKey(projectName), takenKeys);
+ takenKeys.add(projectKey);
+ report.projectKey = projectKey;
+
+ onProgress(`Creating project "${projectName}" (${projectKey})`);
+ const project = await kaneo.createProject({
+ name: projectName,
+ workspaceId,
+ icon: projectIcon,
+ slug: projectKey,
+ });
+ report.kaneoProjectId = project.id;
+
+ // Kaneo seeds every new project with four default columns. They are empty at
+ // this point, so removing them before creating ours keeps the board a 1:1
+ // mirror of PLANKA instead of leaving unused columns behind.
+ for (const existing of await kaneo.listColumns(project.id)) {
+ await kaneo.deleteColumn(existing.id);
+ }
+
+ for (const column of columns) {
+ await kaneo.createColumn(project.id, {
+ name: column.name,
+ isFinal: column.isFinal,
+ });
+ }
+
+ const labelIdByPlankaId = new Map<string, { name: string; color: string }>();
+ for (const label of boardLabels) {
+ if (!usedLabelIds.has(label.id)) continue;
+
+ const name = label.name?.trim() || label.color;
+ const color = labelColorToHex(label.color);
+ // Register the label at workspace level first so it shows up in Kaneo's
+ // label picker, not only on the tasks that happen to carry it.
+ await kaneo.createLabel({ name, color, workspaceId });
+ labelIdByPlankaId.set(label.id, { name, color });
+ }
+
+ let taskIndex = 0;
+ for (const card of cards) {
+ taskIndex++;
+ onProgress(
+ `Importing task ${taskIndex}/${cards.length} into "${projectName}"`,
+ );
+
+ const status = slugByListId.get(card.listId);
+ if (!status) continue;
+
+ const cardChecklists = taskLists.filter((tl) => tl.cardId === card.id);
+ const description = buildDescription(card, cardChecklists, checklistItems);
+
+ const assigneeId = resolveAssignee(
+ card.id,
+ cardMemberships,
+ usersById,
+ membersByEmail,
+ );
+ if (assigneeId) report.assignees++;
+
+ const dueDate = toDueDate(card);
+
+ const task = await kaneo.createTask(project.id, {
+ title: card.name,
+ description,
+ status,
+ priority: DEFAULT_PRIORITY,
+ ...(dueDate ? { dueDate } : {}),
+ ...(assigneeId ? { userId: assigneeId } : {}),
+ });
+
+ for (const link of cardLabels) {
+ if (link.cardId !== card.id) continue;
+ const label = labelIdByPlankaId.get(link.labelId);
+ if (!label) continue;
+
+ await kaneo.createLabel({
+ name: label.name,
+ color: label.color,
+ workspaceId,
+ taskId: task.id,
+ });
+ }
+
+ if (skipComments || card.commentsTotal === 0) continue;
+
+ const { comments, users } = await planka.listComments(card.id);
+ for (const user of users) usersById.set(user.id, user);
+
+ for (const comment of comments) {
+ const author = comment.userId ? usersById.get(comment.userId) : undefined;
+ await kaneo.createComment(task.id, formatComment(comment, author));
+ report.comments++;
+ }
+ }
+}
+
+function resolveAssignee(
+ cardId: string,
+ memberships: { cardId: string; userId: string }[],
+ usersById: Map<string, PlankaUser>,
+ membersByEmail: Map<string, string>,
+): string | undefined {
+ // PLANKA allows several members per card; Kaneo has a single assignee, so we
+ // take the first member who also exists in the target workspace.
+ for (const membership of memberships) {
+ if (membership.cardId !== cardId) continue;
+
+ const email = usersById.get(membership.userId)?.email?.toLowerCase();
+ if (!email) continue;
+
+ const kaneoUserId = membersByEmail.get(email);
+ if (kaneoUserId) return kaneoUserId;
+ }
+
+ return undefined;
+}
diff --git a/packages/planka-import/src/planka.ts b/packages/planka-import/src/planka.ts
new file mode 100644
index 000000000..c05d6a3df
--- /dev/null
+++ b/packages/planka-import/src/planka.ts
@@ -0,0 +1,274 @@
+export type PlankaUser = {
+ id: string;
+ email: string;
+ name: string | null;
+ username: string | null;
+};
+
+export type PlankaProject = {
+ id: string;
+ name: string;
+};
+
+export type PlankaBoard = {
+ id: string;
+ projectId: string;
+ name: string;
+ position: number | null;
+};
+
+// active/closed are the kanban lists whose cards arrive in full from
+// GET /boards/:id. archive and trash are "endless" lists that paginate
+// separately, and we deliberately do not migrate them.
+export const MIGRATABLE_LIST_TYPES = ["active", "closed"];
+
+export type PlankaList = {
+ id: string;
+ boardId: string;
+ name: string | null;
+ type: string;
+ position: number | null;
+ color: string | null;
+};
+
+export type PlankaCard = {
+ id: string;
+ boardId: string;
+ listId: string;
+ name: string;
+ description: string | null;
+ position: number | null;
+ dueDate: string | null;
+ isDueCompleted: boolean | null;
+ isClosed: boolean | null;
+ commentsTotal: number | null;
+};
+
+export type PlankaLabel = {
+ id: string;
+ boardId: string;
+ name: string | null;
+ color: string;
+ position: number;
+};
+
+export type PlankaCardLabel = { cardId: string; labelId: string };
+export type PlankaCardMembership = { cardId: string; userId: string };
+export type PlankaTaskList = { id: string; cardId: string; name: string };
+export type PlankaTask = {
+ id: string;
+ taskListId: string;
+ name: string;
+ isCompleted: boolean | null;
+ position: number;
+};
+export type PlankaAttachment = { id: string; cardId: string };
+export type PlankaComment = {
+ id: string;
+ cardId: string;
+ userId: string | null;
+ text: string;
+ createdAt: string | null;
+};
+
+export type BoardBundle = {
+ item: PlankaBoard;
+ included: {
+ lists?: PlankaList[];
+ cards?: PlankaCard[];
+ labels?: PlankaLabel[];
+ cardLabels?: PlankaCardLabel[];
+ cardMemberships?: PlankaCardMembership[];
+ taskLists?: PlankaTaskList[];
+ tasks?: PlankaTask[];
+ attachments?: PlankaAttachment[];
+ users?: PlankaUser[];
+ };
+};
+
+export type ProjectsBundle = {
+ items: PlankaProject[];
+ included: { boards?: PlankaBoard[]; users?: PlankaUser[] };
+};
+
+export function normalizeBaseUrl(url: string): string {
+ const trimmed = url.trim().replace(/\/+$/, "");
+ if (!/^https?:\/\//i.test(trimmed)) {
+ return `https://${trimmed}`;
+ }
+ return trimmed;
+}
+
+export class PlankaClient {
+ readonly baseUrl: string;
+ private token: string | null;
+
+ constructor(options: { baseUrl: string; token?: string }) {
+ this.baseUrl = normalizeBaseUrl(options.baseUrl);
+ this.token = options.token ?? null;
+ }
+
+ async login(emailOrUsername: string, password: string): Promise<void> {
+ let body: { item?: string };
+ try {
+ body = await this.request<{ item?: string }>("/api/access-tokens", {
+ method: "POST",
+ body: JSON.stringify({ emailOrUsername, password }),
+ headers: { "Content-Type": "application/json" },
+ });
+ } catch (error) {
+ if (error instanceof PlankaHttpError) {
+ throw new Error(describeLoginFailure(error));
+ }
+ throw error;
+ }
+
+ if (typeof body.item !== "string" || body.item.length === 0) {
+ throw new Error(
+ "PLANKA did not return an access token. Pass --planka-token instead.",
+ );
+ }
+
+ this.token = body.item;
+ }
+
+ async listProjects(): Promise<ProjectsBundle> {
+ const bundle = await this.request<ProjectsBundle>("/api/projects");
+ return {
+ items: bundle.items ?? [],
+ included: bundle.included ?? {},
+ };
+ }
+
+ async getBoard(boardId: string): Promise<BoardBundle> {
+ const bundle = await this.request<BoardBundle>(
+ `/api/boards/${encodeURIComponent(boardId)}`,
+ );
+ return { item: bundle.item, included: bundle.included ?? {} };
+ }
+
+ async listComments(cardId: string): Promise<{
+ comments: PlankaComment[];
+ users: PlankaUser[];
+ }> {
+ const comments: PlankaComment[] = [];
+ const users = new Map<string, PlankaUser>();
+ let beforeId: string | undefined;
+
+ // The endpoint is cursor-paginated and has no "total" to check against, so
+ // we walk until a page comes back empty or repeats the cursor.
+ while (true) {
+ const query = beforeId ? `?beforeId=${encodeURIComponent(beforeId)}` : "";
+ const page = await this.request<{
+ items: PlankaComment[];
+ included?: { users?: PlankaUser[] };
+ }>(`/api/cards/${encodeURIComponent(cardId)}/comments${query}`);
+
+ const items = page.items ?? [];
+ if (items.length === 0) break;
+
+ comments.push(...items);
+ for (const user of page.included?.users ?? []) {
+ users.set(user.id, user);
+ }
+
+ const oldest = items[items.length - 1];
+ if (!oldest || oldest.id === beforeId) break;
+ beforeId = oldest.id;
+ }
+
+ // PLANKA returns newest first; replay them in the order they were written.
+ comments.reverse();
+ return { comments, users: [...users.values()] };
+ }
+
+ private async request<T>(path: string, init?: RequestInit): Promise<T> {
+ const headers = new Headers(init?.headers);
+ if (this.token) {
+ headers.set("Authorization", `Bearer ${this.token}`);
+ }
+ headers.set("Accept", "application/json");
+
+ let res: Response;
+ try {
+ res = await fetch(`${this.baseUrl}${path}`, {
+ ...init,
+ headers,
+ signal: AbortSignal.timeout(30_000),
+ });
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ throw new Error(`PLANKA ${path}: ${reason}`);
+ }
+
+ const text = await res.text();
+ let body: unknown = null;
+ if (text) {
+ try {
+ body = JSON.parse(text) as unknown;
+ } catch {
+ body = text;
+ }
+ }
+
+ if (!res.ok) {
+ throw new PlankaHttpError(
+ `PLANKA ${path}: ${describeError(body, res.status)}`,
+ res.status,
+ body,
+ );
+ }
+
+ return body as T;
+ }
+}
+
+export class PlankaHttpError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ readonly body: unknown,
+ ) {
+ super(message);
+ this.name = "PlankaHttpError";
+ }
+}
+
+/**
+ * PLANKA answers a password login with 403 and a `step` when the account still
+ * has something to clear (instance terms, or two-factor). Neither can be
+ * completed non-interactively, so say which one it is and how to get past it.
+ */
+function describeLoginFailure(error: PlankaHttpError): string {
+ const step =
+ typeof error.body === "object" && error.body !== null
+ ? (error.body as { step?: unknown }).step
+ : undefined;
+
+ if (step === "accept-terms") {
+ return "This PLANKA instance requires you to accept its terms before the API will issue a token. Sign in once through the PLANKA web UI, accept the terms, then run this again.";
+ }
+
+ if (step === "verify-totp") {
+ return "This PLANKA account has two-factor authentication enabled, which password login cannot complete. Copy an access token from your browser's dev tools and pass --planka-token instead.";
+ }
+
+ return error.message;
+}
+
+function describeError(body: unknown, status: number): string {
+ if (status === 401) {
+ return "unauthorized (HTTP 401) — check your PLANKA credentials or token";
+ }
+ if (typeof body === "object" && body !== null) {
+ const record = body as Record<string, unknown>;
+ for (const key of ["message", "problem", "error"]) {
+ const value = record[key];
+ if (typeof value === "string" && value.length > 0) return value;
+ }
+ }
+ if (typeof body === "string" && body.length > 0) {
+ return body.length > 300 ? `${body.slice(0, 300)}…` : body;
+ }
+ return `HTTP ${status}`;
+}
diff --git a/packages/planka-import/tsconfig.json b/packages/planka-import/tsconfig.json
new file mode 100644
index 000000000..561a22631
--- /dev/null
+++ b/packages/planka-import/tsconfig.json
@@ -0,0 +1,12 @@
+{
+ "extends": "../typescript-config/base.json",
+ "compilerOptions": {
+ "outDir": "dist",
+ "rootDir": "src",
+ "noEmit": false,
+ "declaration": true,
+ "declarationMap": false
+ },
+ "include": ["src/**/*.ts"],
+ "exclude": ["node_modules", "dist", "src/**/*.test.ts"]
+}
diff --git a/packages/planka-import/vitest.config.ts b/packages/planka-import/vitest.config.ts
new file mode 100644
index 000000000..2e456d688
--- /dev/null
+++ b/packages/planka-import/vitest.config.ts
@@ -0,0 +1,9 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ globals: false,
+ environment: "node",
+ include: ["src/**/*.test.ts"],
+ },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 784fd43ce..3923eb9a5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -693,6 +693,31 @@ importers:
specifier: ^4.1.10
+ packages/planka-import:
+ dependencies:
+ prompts:
+ specifier: ^2.4.2
+ version: 2.4.2
+ devDependencies:
+ '@kaneo/typescript-config':
+ specifier: workspace:*
+ version: link:../typescript-config
+ '@types/node':
+ specifier: ^26.1.2
+ version: 26.1.2
+ '@types/prompts':
+ specifier: ^2.4.9
+ version: 2.4.9
+ tsx:
+ specifier: ^4.23.9
+ version: 4.23.9
+ typescript:
+ specifier: ^7.0.2
+ version: 7.0.2
+ vitest:
+ specifier: ^4.1.10
+
packages/typescript-config: {}
packages: