⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat(api): run imports from other tools
Andrej9f20cbcbfdd1
diff --git a/.env.sample b/.env.sampleindex 593b379bb..d0a6c3ae7 100644--- a/.env.sample+++ b/.env.sample@@ -119,5 +119,9 @@ SMTP_REQUIRE_TLS=# DEVICE_AUTH_CLIENT_IDS=kaneo-cli,kaneo-mcp# KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS=false+# Imports (Optional). Trello Power-Up API key from https://trello.com/power-ups/admin,+# used to link workspace admins to Trello to authorize an import.+# TRELLO_API_KEY=+# Required when saving personal notification tokens or signing secrets. Keep stable.# NOTIFICATION_SECRET_ENCRYPTION_KEY=diff --git a/Dockerfile.kaneo b/Dockerfile.kaneoindex 78b6b89e9..b07bc7b60 100644--- a/Dockerfile.kaneo+++ b/Dockerfile.kaneo@@ -11,6 +11,7 @@ COPY packages/typescript-config/package.json ./packages/typescript-config/COPY packages/email/package.json ./packages/email/COPY packages/libs/package.json ./packages/libs/COPY packages/permissions/package.json ./packages/permissions/+COPY packages/importers/package.json ./packages/importers/COPY packages/mcp/package.json ./packages/mcp/COPY apps/api/package.json ./apps/api/@@ -20,6 +21,7 @@ COPY packages/typescript-config ./packages/typescript-configCOPY packages/email ./packages/emailCOPY packages/libs ./packages/libsCOPY packages/permissions ./packages/permissions+COPY packages/importers ./packages/importersCOPY packages/mcp ./packages/mcpCOPY i18n ./i18nCOPY apps/api ./apps/api@@ -30,6 +32,9 @@ RUN pnpm run buildWORKDIR /app/packages/permissionsRUN pnpm run build+WORKDIR /app/packages/importers+RUN pnpm run build+WORKDIR /app/apps/apiRUN pnpm run build@@ -46,6 +51,7 @@ COPY --from=api-builder /app/packages/typescript-config/package.json ./packages/COPY --from=api-builder /app/packages/libs/package.json ./packages/libs/COPY --from=api-builder /app/packages/email/package.json ./packages/email/COPY --from=api-builder /app/packages/permissions/package.json ./packages/permissions/+COPY --from=api-builder /app/packages/importers/package.json ./packages/importers/COPY --from=api-builder /app/packages/mcp/package.json ./packages/mcp/RUN sed -i 's/"prepare": "husky"/"prepare": ""/g' package.json && \@@ -57,6 +63,7 @@ COPY --from=api-builder /app/apps/api/dist ./apps/api/distCOPY --from=api-builder /app/apps/api/drizzle ./apps/api/drizzleCOPY --from=api-builder /app/packages/email ./packages/emailCOPY --from=api-builder /app/packages/permissions ./packages/permissions+COPY --from=api-builder /app/packages/importers/dist ./packages/importers/distCOPY --from=api-builder /app/packages/mcp/dist ./packages/mcp/distFROM --platform=$BUILDPLATFORM node:24.19.0-alpine AS web-builder@@ -101,7 +108,7 @@ WORKDIR /appCOPY --from=api-runtime --chown=appuser:appuser /app /app# Fail the build early if the runtime dependency layout is broken on the target architecture-RUN cd /app/apps/api && node -e "const fs=require('fs');for(const m of ['bcryptjs','hono','pg','drizzle-orm','better-auth','ioredis','valibot','octokit','@modelcontextprotocol/sdk']){fs.accessSync('node_modules/'+m+'/package.json')}for(const m of ['email','permissions']){fs.accessSync('node_modules/@kaneo/'+m+'/dist/index.js')}" && \+RUN cd /app/apps/api && node -e "const fs=require('fs');for(const m of ['bcryptjs','hono','pg','drizzle-orm','better-auth','ioredis','valibot','octokit','@modelcontextprotocol/sdk']){fs.accessSync('node_modules/'+m+'/package.json')}for(const m of ['email','permissions','importers']){fs.accessSync('node_modules/@kaneo/'+m+'/dist/index.js')}" && \node --input-type=module -e "import { registerTools } from '@kaneo/mcp/tools'; if (typeof registerTools !== 'function') process.exit(1)"COPY --from=web-builder --chown=appuser:appuser /app/apps/web/dist /usr/share/nginx/htmldiff --git a/ENVIRONMENT_SETUP.md b/ENVIRONMENT_SETUP.mdindex a15a482d2..1d600e378 100644--- a/ENVIRONMENT_SETUP.md+++ b/ENVIRONMENT_SETUP.md@@ -61,7 +61,8 @@ Use the [environment reference](https://kaneo.app/docs/core/installation/environ- **Email:** configure SMTP. Email verification codes become the default sign-in method; `DISABLE_EMAIL_OTP_SIGN_IN=true` keeps password sign-in. Invitations and password resets still use SMTP.- **Sign-in providers:** configure OAuth credentials on the API and register the local callback URL with the provider.- **MCP:** the built-in endpoint uses `KANEO_INTERNAL_API_URL`, defaulting to `http://127.0.0.1:1337`, for internal tool requests. Device authorization allows `kaneo-cli` and `kaneo-mcp` by default.-- **Private-network connections:** `KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS=true` permits internal ntfy, Gotify, webhook, Gitea, and GitLab destinations. Only enable it on a trusted deployment.+- **Private-network connections:** `KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS=true` permits internal ntfy, Gotify, webhook, Gitea, GitLab, and import source (PLANKA, Plane, Kaneo) destinations. Only enable it on a trusted deployment.+- **Trello imports:** `TRELLO_API_KEY` is the API key of a Trello Power-Up. Workspace admins starting a Trello import get a link to Trello's authorize page built from it; without it, they paste their own API key next to the token.- **Redis:** only needed to relay live updates between multiple API instances. Leave it unset for one local API process.- **CAPTCHA:** set `TURNSTILE_SECRET_KEY` in the root `.env` and the matching `VITE_TURNSTILE_SITE_KEY` in `apps/web/.env.local`. The secret enables verification independently of cloud mode. Configure a widget that accepts your development hostname.- **Sentry:** `SENTRY_DSN` enables API reporting. A browser build reads `VITE_SENTRY_DSN`; the current container renderer does not substitute `KANEO_SENTRY_DSN` at runtime. Leave reporting unset if you do not need it.diff --git a/apps/api/Dockerfile b/apps/api/Dockerfileindex e98f7ba62..afdcf3b33 100644--- a/apps/api/Dockerfile+++ b/apps/api/Dockerfile@@ -14,6 +14,7 @@ COPY packages/typescript-config/package.json ./packages/typescript-config/COPY packages/email/package.json ./packages/email/COPY packages/libs/package.json ./packages/libs/COPY packages/permissions/package.json ./packages/permissions/+COPY packages/importers/package.json ./packages/importers/COPY packages/mcp/package.json ./packages/mcp/COPY apps/api/package.json ./apps/api/@@ -25,6 +26,7 @@ COPY packages/typescript-config ./packages/typescript-configCOPY packages/email ./packages/emailCOPY packages/libs ./packages/libsCOPY packages/permissions ./packages/permissions+COPY packages/importers ./packages/importersCOPY packages/mcp ./packages/mcpCOPY i18n ./i18nCOPY apps/api ./apps/api@@ -37,6 +39,10 @@ RUN pnpm run buildWORKDIR /app/packages/permissionsRUN pnpm run build+# Build importers package+WORKDIR /app/packages/importers+RUN pnpm run build+# Fix TypeScript config and build APIWORKDIR /app/apps/apiRUN sed -i 's/"extends": "@kaneo\/typescript-config\/base.json"/"extends": "..\/..\/packages\/typescript-config\/base.json"/g' /app/apps/api/tsconfig.json && \@@ -56,6 +62,7 @@ COPY packages/typescript-config/package.json ./packages/typescript-config/COPY packages/libs/package.json ./packages/libs/COPY packages/email/package.json ./packages/email/COPY packages/permissions/package.json ./packages/permissions/+COPY packages/importers/package.json ./packages/importers/COPY packages/mcp/package.json ./packages/mcp/COPY apps/api/package.json ./apps/api/@@ -82,10 +89,11 @@ COPY --from=builder --chown=appuser:appuser /app/apps/api/dist ./apps/api/distCOPY --from=builder --chown=appuser:appuser /app/apps/api/drizzle ./apps/api/drizzleCOPY --from=builder --chown=appuser:appuser /app/packages/email ./packages/emailCOPY --from=builder --chown=appuser:appuser /app/packages/permissions ./packages/permissions+COPY --from=builder --chown=appuser:appuser /app/packages/importers/dist ./packages/importers/distCOPY --from=builder --chown=appuser:appuser /app/packages/mcp/dist ./packages/mcp/dist# Fail the build early if the runtime dependency layout is broken on the target architecture-RUN cd /app/apps/api && node -e "const fs=require('fs');for(const m of ['bcryptjs','hono','pg','drizzle-orm','better-auth','ioredis','valibot','octokit','@modelcontextprotocol/sdk']){fs.accessSync('node_modules/'+m+'/package.json')}for(const m of ['email','permissions']){fs.accessSync('node_modules/@kaneo/'+m+'/dist/index.js')}" && \+RUN cd /app/apps/api && node -e "const fs=require('fs');for(const m of ['bcryptjs','hono','pg','drizzle-orm','better-auth','ioredis','valibot','octokit','@modelcontextprotocol/sdk']){fs.accessSync('node_modules/'+m+'/package.json')}for(const m of ['email','permissions','importers']){fs.accessSync('node_modules/@kaneo/'+m+'/dist/index.js')}" && \node --input-type=module -e "import { registerTools } from '@kaneo/mcp/tools'; if (typeof registerTools !== 'function') process.exit(1)"# Switch to non-root userdiff --git a/apps/api/drizzle/0063_import_runs.sql b/apps/api/drizzle/0063_import_runs.sqlnew file mode 100644index 000000000..e52e14152--- /dev/null+++ b/apps/api/drizzle/0063_import_runs.sql@@ -0,0 +1,18 @@+CREATE TABLE "import_run" (+ "id" text PRIMARY KEY NOT NULL,+ "workspace_id" text NOT NULL,+ "user_id" text,+ "source" text NOT NULL,+ "status" text DEFAULT 'running' NOT NULL,+ "include_comments" boolean DEFAULT true NOT NULL,+ "message" text,+ "projects" jsonb NOT NULL,+ "error" text,+ "heartbeat_at" timestamp DEFAULT (now() AT TIME ZONE 'utc') NOT NULL,+ "created_at" timestamp DEFAULT (now() AT TIME ZONE 'utc') NOT NULL,+ "finished_at" timestamp+);+--> statement-breakpoint+ALTER TABLE "import_run" ADD CONSTRAINT "import_run_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint+ALTER TABLE "import_run" ADD CONSTRAINT "import_run_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE cascade;--> statement-breakpoint+CREATE INDEX "import_run_workspace_created_idx" ON "import_run" USING btree ("workspace_id","created_at");\ No newline at end of filediff --git a/apps/api/drizzle/meta/0063_snapshot.json b/apps/api/drizzle/meta/0063_snapshot.jsonnew file mode 100644index 000000000..52ef02363--- /dev/null+++ b/apps/api/drizzle/meta/0063_snapshot.json@@ -0,0 +1,5391 @@+{+ "id": "f569b31a-0316-4069-acb6-0443dcf0a86f",+ "prevId": "0466239b-b8ab-4220-a847-dde109ec6508",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.activity": {+ "name": "activity",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_name": {+ "name": "external_user_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_avatar": {+ "name": "external_user_avatar",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_source": {+ "name": "external_source",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_url": {+ "name": "external_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "activity_task_id_idx": {+ "name": "activity_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "activity_userId_idx": {+ "name": "activity_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "activity_createdAt_idx": {+ "name": "activity_createdAt_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "activity_task_id_task_id_fk": {+ "name": "activity_task_id_task_id_fk",+ "tableFrom": "activity",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "activity_user_id_user_id_fk": {+ "name": "activity_user_id_user_id_fk",+ "tableFrom": "activity",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "activity_task_external_source_external_url_unique": {+ "name": "activity_task_external_source_external_url_unique",+ "nullsNotDistinct": false,+ "columns": [+ "task_id",+ "external_source",+ "external_url"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 86400000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 10+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_userId_idx": {+ "name": "apikey_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "apikey_reference_id_user_id_fk": {+ "name": "apikey_reference_id_user_id_fk",+ "tableFrom": "apikey",+ "tableTo": "user",+ "columnsFrom": [+ "reference_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "apikey_user_id_user_id_fk": {+ "name": "apikey_user_id_user_id_fk",+ "tableFrom": "apikey",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.asset": {+ "name": "asset",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activity_id": {+ "name": "activity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "object_key": {+ "name": "object_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'image'"+ },+ "surface": {+ "name": "surface",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'description'"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "asset_workspaceId_idx": {+ "name": "asset_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_projectId_idx": {+ "name": "asset_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_taskId_idx": {+ "name": "asset_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_activityId_idx": {+ "name": "asset_activityId_idx",+ "columns": [+ {+ "expression": "activity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_createdBy_idx": {+ "name": "asset_createdBy_idx",+ "columns": [+ {+ "expression": "created_by",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_draft_expiry_idx": {+ "name": "asset_draft_expiry_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"asset\".\"task_id\" is null and \"asset\".\"surface\" in ('draft', 'draft-pending')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "asset_workspace_id_workspace_id_fk": {+ "name": "asset_workspace_id_workspace_id_fk",+ "tableFrom": "asset",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_project_id_project_id_fk": {+ "name": "asset_project_id_project_id_fk",+ "tableFrom": "asset",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_task_id_task_id_fk": {+ "name": "asset_task_id_task_id_fk",+ "tableFrom": "asset",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_activity_id_activity_id_fk": {+ "name": "asset_activity_id_activity_id_fk",+ "tableFrom": "asset",+ "tableTo": "activity",+ "columnsFrom": [+ "activity_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_created_by_user_id_fk": {+ "name": "asset_created_by_user_id_fk",+ "tableFrom": "asset",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "asset_object_key_unique": {+ "name": "asset_object_key_unique",+ "nullsNotDistinct": false,+ "columns": [+ "object_key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_event": {+ "name": "billing_event",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "processed_at": {+ "name": "processed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_reminder_sent": {+ "name": "billing_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "billing_reminder_sent_workspaceId_idx": {+ "name": "billing_reminder_sent_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "billing_reminder_sent_userId_idx": {+ "name": "billing_reminder_sent_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "billing_reminder_sent_user_id_user_id_fk": {+ "name": "billing_reminder_sent_user_id_user_id_fk",+ "tableFrom": "billing_reminder_sent",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "billing_reminder_sent_workspace_id_workspace_id_fk": {+ "name": "billing_reminder_sent_workspace_id_workspace_id_fk",+ "tableFrom": "billing_reminder_sent",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "billing_reminder_sent_user_type_unique": {+ "name": "billing_reminder_sent_user_type_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id",+ "reminder_type"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.calendar_feed": {+ "name": "calendar_feed",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "label_ids": {+ "name": "label_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "time_zone": {+ "name": "time_zone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'UTC'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "calendar_feed_project_id_idx": {+ "name": "calendar_feed_project_id_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "calendar_feed_project_id_project_id_fk": {+ "name": "calendar_feed_project_id_project_id_fk",+ "tableFrom": "calendar_feed",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "calendar_feed_token_unique": {+ "name": "calendar_feed_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.column": {+ "name": "column",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_final": {+ "name": "is_final",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "column_projectId_idx": {+ "name": "column_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "column_project_id_project_id_fk": {+ "name": "column_project_id_project_id_fk",+ "tableFrom": "column",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.comment": {+ "name": "comment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "comment_task_idx": {+ "name": "comment_task_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "comment_user_idx": {+ "name": "comment_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "comment_task_id_task_id_fk": {+ "name": "comment_task_id_task_id_fk",+ "tableFrom": "comment",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "comment_user_id_user_id_fk": {+ "name": "comment_user_id_user_id_fk",+ "tableFrom": "comment",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_definition": {+ "name": "custom_field_definition",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "required": {+ "name": "required",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "default_value": {+ "name": "default_value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "options": {+ "name": "options",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "custom_field_def_projectId_idx": {+ "name": "custom_field_def_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "custom_field_definition_project_id_project_id_fk": {+ "name": "custom_field_definition_project_id_project_id_fk",+ "tableFrom": "custom_field_definition",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_value": {+ "name": "custom_field_value",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "custom_field_value_taskId_idx": {+ "name": "custom_field_value_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "custom_field_value_fieldId_idx": {+ "name": "custom_field_value_fieldId_idx",+ "columns": [+ {+ "expression": "field_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "custom_field_value_task_id_task_id_fk": {+ "name": "custom_field_value_task_id_task_id_fk",+ "tableFrom": "custom_field_value",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "custom_field_value_field_id_custom_field_definition_id_fk": {+ "name": "custom_field_value_field_id_custom_field_definition_id_fk",+ "tableFrom": "custom_field_value",+ "tableTo": "custom_field_definition",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "custom_field_value_task_field_unique": {+ "name": "custom_field_value_task_field_unique",+ "nullsNotDistinct": false,+ "columns": [+ "task_id",+ "field_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.data_migration": {+ "name": "data_migration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.device_code": {+ "name": "device_code",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "device_code": {+ "name": "device_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_code": {+ "name": "user_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "last_polled_at": {+ "name": "last_polled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "polling_interval": {+ "name": "polling_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "device_code_device_code_uidx": {+ "name": "device_code_device_code_uidx",+ "columns": [+ {+ "expression": "device_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "device_code_user_code_uidx": {+ "name": "device_code_user_code_uidx",+ "columns": [+ {+ "expression": "user_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "device_code_user_id_idx": {+ "name": "device_code_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "device_code_user_id_user_id_fk": {+ "name": "device_code_user_id_user_id_fk",+ "tableFrom": "device_code",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.external_link": {+ "name": "external_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_id": {+ "name": "integration_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "external_link_taskId_idx": {+ "name": "external_link_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_integrationId_idx": {+ "name": "external_link_integrationId_idx",+ "columns": [+ {+ "expression": "integration_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_externalId_idx": {+ "name": "external_link_externalId_idx",+ "columns": [+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_resourceType_idx": {+ "name": "external_link_resourceType_idx",+ "columns": [+ {+ "expression": "resource_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_deferred_issue_idx": {+ "name": "external_link_deferred_issue_idx",+ "columns": [+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"external_link\".\"resource_type\" = 'issue' AND \"external_link\".\"metadata\" LIKE '%\"deferredIssueEdit\":%'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "external_link_task_id_task_id_fk": {+ "name": "external_link_task_id_task_id_fk",+ "tableFrom": "external_link",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "external_link_integration_id_integration_id_fk": {+ "name": "external_link_integration_id_integration_id_fk",+ "tableFrom": "external_link",+ "tableTo": "integration",+ "columnsFrom": [+ "integration_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.github_import": {+ "name": "github_import",+ "schema": "",+ "columns": {+ "integration_id": {+ "name": "integration_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "github_import_integration_id_integration_id_fk": {+ "name": "github_import_integration_id_integration_id_fk",+ "tableFrom": "github_import",+ "tableTo": "integration",+ "columnsFrom": [+ "integration_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.github_integration": {+ "name": "github_integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_owner": {+ "name": "repository_owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_name": {+ "name": "repository_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "installation_id": {+ "name": "installation_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "github_integration_project_id_project_id_fk": {+ "name": "github_integration_project_id_project_id_fk",+ "tableFrom": "github_integration",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "github_integration_project_id_unique": {+ "name": "github_integration_project_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.import_run": {+ "name": "import_run",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'running'"+ },+ "include_comments": {+ "name": "include_comments",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "projects": {+ "name": "projects",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "heartbeat_at": {+ "name": "heartbeat_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "import_run_workspace_created_idx": {+ "name": "import_run_workspace_created_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "import_run_workspace_id_workspace_id_fk": {+ "name": "import_run_workspace_id_workspace_id_fk",+ "tableFrom": "import_run",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "import_run_user_id_user_id_fk": {+ "name": "import_run_user_id_user_id_fk",+ "tableFrom": "import_run",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.integration": {+ "name": "integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "integration_projectId_idx": {+ "name": "integration_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "integration_type_idx": {+ "name": "integration_type_idx",+ "columns": [+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "integration_project_id_project_id_fk": {+ "name": "integration_project_id_project_id_fk",+ "tableFrom": "integration",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "integration_project_type_unique": {+ "name": "integration_project_type_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "type"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_access": {+ "name": "project_access",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'all'"+ },+ "project_ids": {+ "name": "project_ids",+ "type": "text[]",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::text[]"+ }+ },+ "indexes": {+ "invitation_workspaceId_idx": {+ "name": "invitation_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_inviterId_idx": {+ "name": "invitation_inviterId_idx",+ "columns": [+ {+ "expression": "inviter_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "invitation_workspace_id_workspace_id_fk": {+ "name": "invitation_workspace_id_workspace_id_fk",+ "tableFrom": "invitation",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": [+ "inviter_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.job_lease": {+ "name": "job_lease",+ "schema": "",+ "columns": {+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.label": {+ "name": "label",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "deletion_started_at": {+ "name": "deletion_started_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "label_task_id_idx": {+ "name": "label_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_id_idx": {+ "name": "label_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_cascade_idx": {+ "name": "label_workspace_cascade_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"label\".\"task_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_name_unique": {+ "name": "label_workspace_name_unique",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"label\".\"task_id\" is null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "label_task_id_task_id_fk": {+ "name": "label_task_id_task_id_fk",+ "tableFrom": "label",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "label_workspace_id_workspace_id_fk": {+ "name": "label_workspace_id_workspace_id_fk",+ "tableFrom": "label",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_task_name_unique": {+ "name": "label_task_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "task_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_state": {+ "name": "mcp_oauth_state",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "mcp_oauth_state_kind_key_uidx": {+ "name": "mcp_oauth_state_kind_key_uidx",+ "columns": [+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_oauth_state_expiresAt_idx": {+ "name": "mcp_oauth_state_expiresAt_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.notification": {+ "name": "notification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'info'"+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "is_read": {+ "name": "is_read",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "resource_id": {+ "name": "resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_userId_idx": {+ "name": "notification_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "notification_user_id_user_id_fk": {+ "name": "notification_user_id_user_id_fk",+ "tableFrom": "notification",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_role": {+ "name": "workspace_role",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "permission": {+ "name": "permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "workspace_role_workspaceId_idx": {+ "name": "workspace_role_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_role_role_idx": {+ "name": "workspace_role_role_idx",+ "columns": [+ {+ "expression": "role",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_role_workspace_id_workspace_id_fk": {+ "name": "workspace_role_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_role",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project": {+ "name": "project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'Layout'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "is_public": {+ "name": "is_public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "last_task_number": {+ "name": "last_task_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "background_object_key": {+ "name": "background_object_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "background_mime_type": {+ "name": "background_mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "background_version": {+ "name": "background_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "project_background_object_key_idx": {+ "name": "project_background_object_key_idx",+ "columns": [+ {+ "expression": "background_object_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"project\".\"background_object_key\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_workspaceId_position_idx": {+ "name": "project_workspaceId_position_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_workspace_id_workspace_id_fk": {+ "name": "project_workspace_id_workspace_id_fk",+ "tableFrom": "project",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_workspace_id_id_unique": {+ "name": "project_workspace_id_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id",+ "id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "active_team_id": {+ "name": "active_team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "impersonated_by": {+ "name": "impersonated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.storage_cleanup": {+ "name": "storage_cleanup",+ "schema": "",+ "columns": {+ "object_key": {+ "name": "object_key",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "last_attempt_at": {+ "name": "last_attempt_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_relation": {+ "name": "task_relation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "source_task_id": {+ "name": "source_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_task_id": {+ "name": "target_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "relation_type": {+ "name": "relation_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "task_relation_source_idx": {+ "name": "task_relation_source_idx",+ "columns": [+ {+ "expression": "source_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_relation_target_idx": {+ "name": "task_relation_target_idx",+ "columns": [+ {+ "expression": "target_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_relation_source_task_id_task_id_fk": {+ "name": "task_relation_source_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "tableTo": "task",+ "columnsFrom": [+ "source_task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "task_relation_target_task_id_task_id_fk": {+ "name": "task_relation_target_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "tableTo": "task",+ "columnsFrom": [+ "target_task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_reminder_sent": {+ "name": "task_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "task_reminder_sent_taskId_idx": {+ "name": "task_reminder_sent_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_reminder_sent_task_id_task_id_fk": {+ "name": "task_reminder_sent_task_id_task_id_fk",+ "tableFrom": "task_reminder_sent",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_reminder_sent_task_type_unique": {+ "name": "task_reminder_sent_task_type_unique",+ "nullsNotDistinct": false,+ "columns": [+ "task_id",+ "reminder_type"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task": {+ "name": "task",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "number": {+ "name": "number",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1+ },+ "assignee_id": {+ "name": "assignee_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'to-do'"+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'low'"+ },+ "start_date": {+ "name": "start_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "due_date": {+ "name": "due_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "task_projectId_idx": {+ "name": "task_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_project_scheduled_id_idx": {+ "name": "task_project_scheduled_id_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"task\".\"start_date\" is not null or \"task\".\"due_date\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_dueDate_idx": {+ "name": "task_dueDate_idx",+ "columns": [+ {+ "expression": "due_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_assigneeId_idx": {+ "name": "task_assigneeId_idx",+ "columns": [+ {+ "expression": "assignee_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_columnId_idx": {+ "name": "task_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_project_id_project_id_fk": {+ "name": "task_project_id_project_id_fk",+ "tableFrom": "task",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "task_assignee_id_user_id_fk": {+ "name": "task_assignee_id_user_id_fk",+ "tableFrom": "task",+ "tableTo": "user",+ "columnsFrom": [+ "assignee_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ },+ "task_column_id_column_id_fk": {+ "name": "task_column_id_column_id_fk",+ "tableFrom": "task",+ "tableTo": "column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_project_number_unique": {+ "name": "task_project_number_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "number"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "team_workspaceId_idx": {+ "name": "team_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_workspace_id_workspace_id_fk": {+ "name": "team_workspace_id_workspace_id_fk",+ "tableFrom": "team",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_member": {+ "name": "team_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "teamMember_teamId_idx": {+ "name": "teamMember_teamId_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "teamMember_userId_idx": {+ "name": "teamMember_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_member_team_id_team_id_fk": {+ "name": "team_member_team_id_team_id_fk",+ "tableFrom": "team_member",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_member_user_id_user_id_fk": {+ "name": "team_member_user_id_user_id_fk",+ "tableFrom": "team_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.time_entry": {+ "name": "time_entry",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "end_time": {+ "name": "end_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "duration": {+ "name": "duration",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "time_entry_taskId_idx": {+ "name": "time_entry_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "time_entry_userId_idx": {+ "name": "time_entry_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "time_entry_task_id_task_id_fk": {+ "name": "time_entry_task_id_task_id_fk",+ "tableFrom": "time_entry",+ "tableTo": "task",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "time_entry_user_id_user_id_fk": {+ "name": "time_entry_user_id_user_id_fk",+ "tableFrom": "time_entry",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.trial_grant": {+ "name": "trial_grant",+ "schema": "",+ "columns": {+ "email_hash": {+ "name": "email_hash",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "locale": {+ "name": "locale",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "is_anonymous": {+ "name": "is_anonymous",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banned": {+ "name": "banned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "ban_reason": {+ "name": "ban_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ban_expires": {+ "name": "ban_expires",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": [+ "email"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_avatar": {+ "name": "user_avatar",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "data": {+ "name": "data",+ "type": "bytea",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "user_avatar_userId_idx": {+ "name": "user_avatar_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_avatar_user_id_user_id_fk": {+ "name": "user_avatar_user_id_user_id_fk",+ "tableFrom": "user_avatar",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_avatar_user_id_unique": {+ "name": "user_avatar_user_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_preference": {+ "name": "user_notification_preference",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_server_url": {+ "name": "ntfy_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_topic": {+ "name": "ntfy_topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_token": {+ "name": "ntfy_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_server_url": {+ "name": "gotify_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_token": {+ "name": "gotify_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_url": {+ "name": "webhook_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_secret": {+ "name": "webhook_secret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "task_assignment_enabled": {+ "name": "task_assignment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_comment_enabled": {+ "name": "task_comment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_status_change_enabled": {+ "name": "task_status_change_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_enabled": {+ "name": "due_date_reminder_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_lead_time_minutes": {+ "name": "due_date_reminder_lead_time_minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1440+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_notification_preference_user_id_user_id_fk": {+ "name": "user_notification_preference_user_id_user_id_fk",+ "tableFrom": "user_notification_preference",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_preference_user_id_unique": {+ "name": "user_notification_preference_user_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_project": {+ "name": "user_notification_workspace_project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_rule_id": {+ "name": "workspace_rule_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "user_notification_workspace_project_ruleId_idx": {+ "name": "user_notification_workspace_project_ruleId_idx",+ "columns": [+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_project_projectId_idx": {+ "name": "user_notification_workspace_project_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_project_workspaceId_projectId_idx": {+ "name": "user_notification_workspace_project_workspaceId_projectId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "unwp_workspaceId_workspaceRuleId_idx": {+ "name": "unwp_workspaceId_workspaceRuleId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_notification_workspace_project_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "user_notification_workspace_rule",+ "columnsFrom": [+ "workspace_id",+ "workspace_rule_id"+ ],+ "columnsTo": [+ "workspace_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "project",+ "columnsFrom": [+ "workspace_id",+ "project_id"+ ],+ "columnsTo": [+ "workspace_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_project_rule_project_unique": {+ "name": "user_notification_workspace_project_rule_project_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_rule_id",+ "project_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_rule": {+ "name": "user_notification_workspace_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "project_mode": {+ "name": "project_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'all'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "user_notification_workspace_rule_userId_idx": {+ "name": "user_notification_workspace_rule_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_rule_workspaceId_idx": {+ "name": "user_notification_workspace_rule_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_notification_workspace_rule_user_id_user_id_fk": {+ "name": "user_notification_workspace_rule_user_id_user_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_rule_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_rule_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_rule_user_workspace_unique": {+ "name": "user_notification_workspace_rule_user_workspace_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id",+ "workspace_id"+ ]+ },+ "user_notification_workspace_rule_workspace_id_id_unique": {+ "name": "user_notification_workspace_rule_workspace_id_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id",+ "id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workflow_rule": {+ "name": "workflow_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_type": {+ "name": "integration_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "workflow_rule_projectId_idx": {+ "name": "workflow_rule_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workflow_rule_columnId_idx": {+ "name": "workflow_rule_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workflow_rule_project_id_project_id_fk": {+ "name": "workflow_rule_project_id_project_id_fk",+ "tableFrom": "workflow_rule",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "workflow_rule_column_id_column_id_fk": {+ "name": "workflow_rule_column_id_column_id_fk",+ "tableFrom": "workflow_rule",+ "tableTo": "column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace": {+ "name": "workspace",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "nullsNotDistinct": false,+ "columns": [+ "slug"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_billing": {+ "name": "workspace_billing",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "founding_free": {+ "name": "founding_free",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "creem_customer_id": {+ "name": "creem_customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_subscription_id": {+ "name": "creem_subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_product_id": {+ "name": "creem_product_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "plan": {+ "name": "plan",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "billing_interval": {+ "name": "billing_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "seats": {+ "name": "seats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "current_period_end": {+ "name": "current_period_end",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "canceled_at": {+ "name": "canceled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "workspace_billing_workspaceId_idx": {+ "name": "workspace_billing_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_billing_workspace_id_workspace_id_fk": {+ "name": "workspace_billing_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_billing",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_billing_workspace_id_unique": {+ "name": "workspace_billing_workspace_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id"+ ]+ },+ "workspace_billing_creem_subscription_id_unique": {+ "name": "workspace_billing_creem_subscription_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "creem_subscription_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_member_access": {+ "name": "workspace_member_access",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_access": {+ "name": "project_access",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'all'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "workspace_member_access_userId_idx": {+ "name": "workspace_member_access_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_member_access_workspace_id_workspace_id_fk": {+ "name": "workspace_member_access_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_member_access",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "workspace_member_access_user_id_user_id_fk": {+ "name": "workspace_member_access_user_id_user_id_fk",+ "tableFrom": "workspace_member_access",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_member_access_workspace_user_unique": {+ "name": "workspace_member_access_workspace_user_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id",+ "user_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_member_project": {+ "name": "workspace_member_project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "(now() AT TIME ZONE 'utc')"+ }+ },+ "indexes": {+ "workspace_member_project_projectId_idx": {+ "name": "workspace_member_project_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_member_project_user_id_user_id_fk": {+ "name": "workspace_member_project_user_id_user_id_fk",+ "tableFrom": "workspace_member_project",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "workspace_member_project_workspace_id_project_id_project_workspace_id_id_fk": {+ "name": "workspace_member_project_workspace_id_project_id_project_workspace_id_id_fk",+ "tableFrom": "workspace_member_project",+ "tableTo": "project",+ "columnsFrom": [+ "workspace_id",+ "project_id"+ ],+ "columnsTo": [+ "workspace_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_member_project_workspace_user_project_unique": {+ "name": "workspace_member_project_workspace_user_project_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id",+ "user_id",+ "project_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_member": {+ "name": "workspace_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "joined_at": {+ "name": "joined_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "workspace_member_workspaceId_idx": {+ "name": "workspace_member_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_member_userId_idx": {+ "name": "workspace_member_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_member_workspace_id_workspace_id_fk": {+ "name": "workspace_member_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_member",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "workspace_member_user_id_user_id_fk": {+ "name": "workspace_member_user_id_user_id_fk",+ "tableFrom": "workspace_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/apps/api/drizzle/meta/_journal.json b/apps/api/drizzle/meta/_journal.jsonindex a15494165..b20531503 100644--- a/apps/api/drizzle/meta/_journal.json+++ b/apps/api/drizzle/meta/_journal.json@@ -442,6 +442,13 @@"when": 1791580417885,"tag": "0062_motionless_sister_grimm","breakpoints": true+ },+ {+ "idx": 63,+ "version": "7",+ "when": 1791727180448,+ "tag": "0063_import_runs",+ "breakpoints": true}]}\ No newline at end of filediff --git a/apps/api/src/activity/response.ts b/apps/api/src/activity/response.tsindex c6cf88d16..60ad7894d 100644--- a/apps/api/src/activity/response.ts+++ b/apps/api/src/activity/response.ts@@ -21,7 +21,8 @@ export const activitySchema = z}),externalUserAvatar: z.string().nullable(),externalSource: z.string().nullable().openapi({- description: "The tool it was imported from, e.g. planka, trello, jira.",+ description:+ "The tool it was imported from: planka, trello, jira, plane, linear, kaneo, or a connected forge such as github.",}),externalUrl: z.string().nullable(),})diff --git a/apps/api/src/comment/schema.ts b/apps/api/src/comment/schema.tsindex c05f4971e..6bc5d235b 100644--- a/apps/api/src/comment/schema.ts+++ b/apps/api/src/comment/schema.ts@@ -12,10 +12,13 @@ export const createCommentBody = z.object({description:"Attribution for an imported comment. Requires workspace:manage_settings and externalSource; otherwise ignored.",}),- externalSource: z.enum(["planka", "trello", "jira"]).optional().openapi({- description:- "The tool the comment was imported from. Supplying external attribution requires workspace:manage_settings.",- }),+ externalSource: z+ .enum(["planka", "trello", "jira", "plane", "linear", "kaneo"])+ .optional()+ .openapi({+ description:+ "The tool the comment was imported from. Supplying external attribution requires workspace:manage_settings.",+ }),});export const updateCommentBody = z.object({diff --git a/apps/api/src/database/index.ts b/apps/api/src/database/index.tsindex 43bb94b51..09f91bc04 100644--- a/apps/api/src/database/index.ts+++ b/apps/api/src/database/index.ts@@ -53,6 +53,7 @@ import {externalLinkTable,githubImportTable,githubIntegrationTable,+ importRunTable,integrationTable,invitationTable,jobLeaseTable,@@ -102,6 +103,7 @@ export const schema = {externalLinkTable,githubIntegrationTable,githubImportTable,+ importRunTable,integrationTable,invitationTable,jobLeaseTable,diff --git a/apps/api/src/database/schema.ts b/apps/api/src/database/schema.tsindex 30fd02bc7..d905f0951 100644--- a/apps/api/src/database/schema.ts+++ b/apps/api/src/database/schema.ts@@ -14,6 +14,7 @@ import {uniqueIndex,} from "drizzle-orm/pg-core";import type { GitHubImportState } from "../github-integration/import-state";+import type { ImportRunProject } from "../import/import-run-project";// Timestamp columns without a time zone hold UTC (Drizzle reads and writes// them as UTC). A bare now() default would be cast through the session time@@ -1072,6 +1073,44 @@ export const githubImportTable = pgTable("github_import", {.$onUpdate(() => new Date()),});+export const importRunTable = pgTable(+ "import_run",+ {+ id: text("id")+ .$defaultFn(() => createId())+ .primaryKey(),+ workspaceId: text("workspace_id")+ .notNull()+ .references(() => workspaceTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),+ userId: text("user_id").references(() => userTable.id, {+ onDelete: "set null",+ onUpdate: "cascade",+ }),+ source: text("source").notNull(),+ status: text("status").notNull().default("running"),+ includeComments: boolean("include_comments").notNull().default(true),+ message: text("message"),+ projects: jsonb("projects").$type<ImportRunProject[]>().notNull(),+ error: text("error"),+ heartbeatAt: timestamp("heartbeat_at", { mode: "date" })+ .default(utcNow)+ .notNull(),+ createdAt: timestamp("created_at", { mode: "date" })+ .default(utcNow)+ .notNull(),+ finishedAt: timestamp("finished_at", { mode: "date" }),+ },+ (table) => [+ index("import_run_workspace_created_idx").on(+ table.workspaceId,+ table.createdAt,+ ),+ ],+);+export const externalLinkTable = pgTable("external_link",{diff --git a/apps/api/src/import/active-imports.ts b/apps/api/src/import/active-imports.tsnew file mode 100644index 000000000..204993e45--- /dev/null+++ b/apps/api/src/import/active-imports.ts@@ -0,0 +1,47 @@+import type { ImportRunProject } from "./import-run-project";++export const MAX_ACTIVE_IMPORTS = 2;++export type ImportSlot = {+ controller: AbortController;+ runId: string | null;+ job: Promise<void> | null;+ projects: () => ImportRunProject[];+};++const slots = new Set<ImportSlot>();++export function reserveImportSlot(): ImportSlot | null {+ if (slots.size >= MAX_ACTIVE_IMPORTS) return null;+ const slot: ImportSlot = {+ controller: new AbortController(),+ runId: null,+ job: null,+ projects: () => [],+ };+ slots.add(slot);+ return slot;+}++export function releaseImportSlot(slot: ImportSlot) {+ slots.delete(slot);+}++export function trackImportJob(+ slot: ImportSlot,+ runId: string,+ job: Promise<void>,+ projects: () => ImportRunProject[],+) {+ slot.runId = runId;+ slot.projects = projects;+ slot.job = job.finally(() => releaseImportSlot(slot));+}++export function activeImportSlots(): ImportSlot[] {+ return [...slots];+}++export async function waitForActiveImports() {+ await Promise.allSettled(activeImportSlots().map((slot) => slot.job));+}diff --git a/apps/api/src/import/controllers/get-import-run.ts b/apps/api/src/import/controllers/get-import-run.tsnew file mode 100644index 000000000..1ab33e806--- /dev/null+++ b/apps/api/src/import/controllers/get-import-run.ts@@ -0,0 +1,26 @@+import { and, eq } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../../database";+import { importRunTable } from "../../database/schema";+import { toImportRunResponse } from "../runs/to-import-run-response";++async function getImportRun(workspaceId: string, runId: string) {+ const [row] = await db+ .select()+ .from(importRunTable)+ .where(+ and(+ eq(importRunTable.id, runId),+ eq(importRunTable.workspaceId, workspaceId),+ ),+ )+ .limit(1);++ if (!row) {+ throw new HTTPException(404, { message: "Import not found" });+ }++ return { run: toImportRunResponse(row) };+}++export default getImportRun;diff --git a/apps/api/src/import/controllers/get-trello-authorize-url.ts b/apps/api/src/import/controllers/get-trello-authorize-url.tsnew file mode 100644index 000000000..e73efb79f--- /dev/null+++ b/apps/api/src/import/controllers/get-trello-authorize-url.ts@@ -0,0 +1,9 @@+import { trelloAuthorizeUrl } from "@kaneo/importers";+import { trelloApiKeyFromEnv } from "../source/trello-api-key";++function getTrelloAuthorizeUrl() {+ const apiKey = trelloApiKeyFromEnv();+ return { authorizeUrl: apiKey ? trelloAuthorizeUrl(apiKey) : null };+}++export default getTrelloAuthorizeUrl;diff --git a/apps/api/src/import/controllers/list-import-runs.ts b/apps/api/src/import/controllers/list-import-runs.tsnew file mode 100644index 000000000..b9231a3a2--- /dev/null+++ b/apps/api/src/import/controllers/list-import-runs.ts@@ -0,0 +1,23 @@+import { desc, eq } from "drizzle-orm";+import db from "../../database";+import { importRunTable } from "../../database/schema";+import { markStaleRuns } from "../runs/mark-stale-runs";+import { toImportRunResponse } from "../runs/to-import-run-response";++const LISTED_RUNS = 20;++async function listImportRuns(workspaceId: string) {+ const rows = await db+ .select()+ .from(importRunTable)+ .where(eq(importRunTable.workspaceId, workspaceId))+ .orderBy(desc(importRunTable.createdAt), desc(importRunTable.id))+ .limit(LISTED_RUNS);++ const now = new Date();+ await markStaleRuns(rows, now);++ return { runs: rows.map((row) => toImportRunResponse(row, now)) };+}++export default listImportRuns;diff --git a/apps/api/src/import/controllers/list-source-projects.ts b/apps/api/src/import/controllers/list-source-projects.tsnew file mode 100644index 000000000..586014ac8--- /dev/null+++ b/apps/api/src/import/controllers/list-source-projects.ts@@ -0,0 +1,29 @@+import type { ImportConnectionInput } from "../schema";+import {+ importHttpError,+ openImportSource,+} from "../source/open-import-source";++const LIST_TIMEOUT_MS = 90_000;++async function listSourceProjects(connection: ImportConnectionInput) {+ const opened = await openImportSource(+ connection,+ AbortSignal.timeout(LIST_TIMEOUT_MS),+ );++ try {+ const projects = await opened.source.listProjects();+ return {+ projects: projects.map(({ id, name, detail }) => ({+ id,+ name,+ ...(detail ? { detail } : {}),+ })),+ };+ } catch (error) {+ throw importHttpError(opened.describe(error));+ }+}++export default listSourceProjects;diff --git a/apps/api/src/import/controllers/start-import-run.ts b/apps/api/src/import/controllers/start-import-run.tsnew file mode 100644index 000000000..ea2a4e0a8--- /dev/null+++ b/apps/api/src/import/controllers/start-import-run.ts@@ -0,0 +1,113 @@+import type { SourceProject } from "@kaneo/importers";+import { HTTPException } from "hono/http-exception";+import { eventContext } from "../../events";+import {+ type ImportSlot,+ MAX_ACTIVE_IMPORTS,+ releaseImportSlot,+ reserveImportSlot,+ trackImportJob,+} from "../active-imports";+import { logImportError } from "../log-import-error";+import { type ImportJobState, runImportJob } from "../run-import-job";+import { assertNoRunningImport } from "../runs/assert-no-running-import";+import { createImportRun } from "../runs/create-import-run";+import { toImportRunResponse } from "../runs/to-import-run-response";+import type { ImportConnectionInput } from "../schema";+import {+ importHttpError,+ type OpenedImportSource,+ openImportSource,+} from "../source/open-import-source";+import { selectSourceProjects } from "../source/select-source-projects";++const CONNECT_TIMEOUT_MS = 90_000;++type StartImportRunInput = {+ workspaceId: string;+ userId: string;+ connection: ImportConnectionInput;+ projectIds: string[];+ includeComments: boolean;+};++async function connectAndList(+ slot: ImportSlot,+ connection: ImportConnectionInput,+): Promise<{ opened: OpenedImportSource; available: SourceProject[] }> {+ const timer = setTimeout(() => {+ slot.controller.abort(+ new DOMException("The source took too long to answer.", "TimeoutError"),+ );+ }, CONNECT_TIMEOUT_MS);++ try {+ const opened = await openImportSource(connection, slot.controller.signal);+ try {+ return { opened, available: await opened.source.listProjects() };+ } catch (error) {+ throw importHttpError(opened.describe(error));+ }+ } finally {+ clearTimeout(timer);+ }+}++async function startImportRun({+ workspaceId,+ userId,+ connection,+ projectIds,+ includeComments,+}: StartImportRunInput) {+ const slot = reserveImportSlot();+ if (!slot) {+ throw new HTTPException(429, {+ message: `This Kaneo server is already running ${MAX_ACTIVE_IMPORTS} imports. Try again when one of them finishes.`,+ });+ }++ try {+ await assertNoRunningImport(workspaceId);+ const { opened, available } = await connectAndList(slot, connection);+ const projects = selectSourceProjects(+ projectIds,+ available,+ opened.sourceName,+ );++ const run = await createImportRun({+ workspaceId,+ userId,+ source: opened.sourceId,+ includeComments,+ projects,+ });++ const state: ImportJobState = { projects: run.projects };+ const job = eventContext.exit(() =>+ runImportJob({+ runId: run.id,+ workspaceId,+ userId,+ includeComments,+ opened,+ state,+ signal: slot.controller.signal,+ }),+ );+ trackImportJob(+ slot,+ run.id,+ job.catch((error) => logImportError("Import job crashed", run.id, error)),+ () => state.projects,+ );++ return toImportRunResponse(run);+ } catch (error) {+ releaseImportSlot(slot);+ throw error;+ }+}++export default startImportRun;diff --git a/apps/api/src/import/guarded-fetch.test.ts b/apps/api/src/import/guarded-fetch.test.tsnew file mode 100644index 000000000..4fa48292d--- /dev/null+++ b/apps/api/src/import/guarded-fetch.test.ts@@ -0,0 +1,157 @@+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import { createGuardedFetch, MAX_IMPORT_REDIRECTS } from "./guarded-fetch";++const PUBLIC = "http://93.184.216.34";+const OTHER_PUBLIC = "http://93.184.216.35";++function redirect(location: string, status = 302) {+ return new Response(null, { status, headers: { location } });+}++describe("createGuardedFetch", () => {+ beforeEach(() => {+ vi.stubEnv("KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS", "");+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it("sends public requests without following redirects automatically", async () => {+ const baseFetch = vi.fn(async () => new Response("ok"));+ const guard = createGuardedFetch("PLANKA", { baseFetch });++ const response = await guard.fetch(`${PUBLIC}/api/projects`, {+ headers: { Authorization: "Bearer secret" },+ });++ expect(await response.text()).toBe("ok");+ expect(baseFetch).toHaveBeenCalledWith(+ `${PUBLIC}/api/projects`,+ expect.objectContaining({ redirect: "manual" }),+ );+ expect(guard.failure()).toBeNull();+ expect(guard.lastHost()).toBe("93.184.216.34");+ });++ it("refuses private destinations before sending anything", async () => {+ const baseFetch = vi.fn(async () => new Response("ok"));+ const guard = createGuardedFetch("PLANKA", { baseFetch });++ await expect(guard.fetch("http://10.0.0.5/api")).rejects.toThrow(+ "PLANKA destination resolves to a non-routable address",+ );+ expect(baseFetch).not.toHaveBeenCalled();+ expect(guard.failure()).toEqual({+ kind: "destination",+ message: "PLANKA destination resolves to a non-routable address",+ });+ });++ it("allows private destinations when the instance opts in", async () => {+ vi.stubEnv("KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS", "true");+ const baseFetch = vi.fn(async () => new Response("ok"));+ const guard = createGuardedFetch("PLANKA", { baseFetch });++ await expect(guard.fetch("http://10.0.0.5/api")).resolves.toBeInstanceOf(+ Response,+ );+ });++ it("checks every redirect hop", async () => {+ const baseFetch = vi.fn(async () => redirect("http://127.0.0.1/admin"));+ const guard = createGuardedFetch("Kaneo", { baseFetch });++ await expect(guard.fetch(`${PUBLIC}/api`)).rejects.toThrow("non-routable");+ expect(baseFetch).toHaveBeenCalledTimes(1);+ });++ it("keeps credentials on the same origin and drops them across sites", async () => {+ const baseFetch = vi+ .fn<(input: string, init?: RequestInit) => Promise<Response>>()+ .mockResolvedValueOnce(redirect(`${PUBLIC}/v2/api`, 307))+ .mockResolvedValueOnce(redirect(`${OTHER_PUBLIC}/api`, 307))+ .mockResolvedValueOnce(new Response("done"));+ const guard = createGuardedFetch("Plane", { baseFetch });++ await guard.fetch(`${PUBLIC}/api`, {+ method: "POST",+ body: "{}",+ headers: {+ "X-API-Key": "secret",+ Accept: "application/json",+ "Content-Type": "application/json",+ },+ });++ const headersOf = (call: number) =>+ new Headers(baseFetch.mock.calls[call]?.[1]?.headers);+ expect(headersOf(1).get("x-api-key")).toBe("secret");+ expect(headersOf(2).get("x-api-key")).toBeNull();+ expect(headersOf(2).get("accept")).toBe("application/json");+ expect(baseFetch.mock.calls[2]?.[1]?.method).toBe("POST");+ expect(baseFetch.mock.calls[2]?.[0]).toBe(`${OTHER_PUBLIC}/api`);+ });++ it("turns a 303 into a GET without a body", async () => {+ const baseFetch = vi+ .fn<(input: string, init?: RequestInit) => Promise<Response>>()+ .mockResolvedValueOnce(redirect(`${PUBLIC}/done`, 303))+ .mockResolvedValueOnce(new Response("done"));+ const guard = createGuardedFetch("Kaneo", { baseFetch });++ await guard.fetch(`${PUBLIC}/api`, { method: "POST", body: "{}" });++ expect(baseFetch.mock.calls[1]?.[1]?.method).toBe("GET");+ expect(baseFetch.mock.calls[1]?.[1]?.body).toBeUndefined();+ });++ it("gives up after a few redirects", async () => {+ const baseFetch = vi.fn(async () => redirect(`${PUBLIC}/loop`));+ const guard = createGuardedFetch("PLANKA", { baseFetch });++ await expect(guard.fetch(`${PUBLIC}/api`)).rejects.toThrow(+ "PLANKA redirected too many times. Check the URL.",+ );+ expect(baseFetch).toHaveBeenCalledTimes(MAX_IMPORT_REDIRECTS + 1);+ });++ it("records network failures unless the import was cancelled", async () => {+ const baseFetch = vi.fn(async () => {+ throw new TypeError("fetch failed");+ });+ const guard = createGuardedFetch("PLANKA", { baseFetch });++ await expect(guard.fetch(`${PUBLIC}/api`)).rejects.toThrow("fetch failed");+ expect(guard.failure()).toEqual({+ kind: "unreachable",+ host: "93.184.216.34",+ });++ const controller = new AbortController();+ controller.abort();+ const cancelled = createGuardedFetch("PLANKA", {+ baseFetch,+ cancelSignal: controller.signal,+ });+ await expect(cancelled.fetch(`${PUBLIC}/api`)).rejects.toThrow();+ expect(cancelled.failure()).toBeNull();+ });++ it("rejects malformed URLs as a destination problem", async () => {+ const guard = createGuardedFetch("PLANKA", {+ baseFetch: vi.fn(async () => new Response("ok")),+ });++ await expect(guard.fetch("https://exa mple.com/api")).rejects.toThrow(+ "Enter a valid PLANKA URL.",+ );+ });+});diff --git a/apps/api/src/import/guarded-fetch.ts b/apps/api/src/import/guarded-fetch.tsnew file mode 100644index 000000000..10d4b790c--- /dev/null+++ b/apps/api/src/import/guarded-fetch.ts@@ -0,0 +1,170 @@+import type { FetchLike } from "@kaneo/importers";+import { assertPublicDestination } from "../utils/assert-public-destination";+import { withoutOutboundTelemetry } from "../utils/sensitive-outbound";++export const MAX_IMPORT_REDIRECTS = 3;++const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);++const HEADERS_KEPT_ACROSS_SITES = new Set([+ "accept",+ "accept-language",+ "content-type",+ "user-agent",+]);++export type GuardFailure =+ | { kind: "destination"; message: string }+ | { kind: "unreachable"; host: string };++export type GuardedFetch = {+ fetch: FetchLike;+ failure(): GuardFailure | null;+ lastHost(): string | null;+ reset(): void;+};++type GuardOptions = {+ cancelSignal?: AbortSignal;+ baseFetch?: FetchLike;+};++class GuardError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "ImportDestinationError";+ }+}++function errorCode(error: unknown) {+ const code = (error as { code?: unknown } | null)?.code;+ return typeof code === "string" ? code : null;+}++function keepsCredentials(from: URL, to: URL) {+ return (+ from.origin === to.origin ||+ (from.protocol === "http:" &&+ to.protocol === "https:" &&+ from.hostname === to.hostname)+ );+}++function redirectInit(+ init: RequestInit,+ status: number,+ sameSite: boolean,+): RequestInit {+ const method = (init.method ?? "GET").toUpperCase();+ const becomesGet =+ (status === 303 && method !== "HEAD") ||+ ((status === 301 || status === 302) && method === "POST");++ const headers = new Headers(init.headers);+ if (!sameSite) {+ for (const name of [...headers.keys()]) {+ if (!HEADERS_KEPT_ACROSS_SITES.has(name)) headers.delete(name);+ }+ }+ if (becomesGet) headers.delete("content-type");++ return {+ ...init,+ headers,+ ...(becomesGet ? { method: "GET", body: undefined } : {}),+ };+}++export function createGuardedFetch(+ label: string,+ {+ cancelSignal,+ baseFetch = (input, init) => fetch(input, init),+ }: GuardOptions = {},+): GuardedFetch {+ let failure: GuardFailure | null = null;+ let lastHost: string | null = null;++ function fail(next: GuardFailure, message: string): never {+ failure = next;+ throw new GuardError(message);+ }++ async function checkDestination(url: URL) {+ lastHost = url.host;+ try {+ await assertPublicDestination(url.href, label);+ } catch (error) {+ if (errorCode(error)) {+ fail(+ { kind: "unreachable", host: url.host },+ `${label} at ${url.host} could not be resolved`,+ );+ }+ const message =+ error instanceof Error ? error.message : `${label} URL is not allowed`;+ fail({ kind: "destination", message }, message);+ }+ }++ function parse(input: string, base?: URL) {+ try {+ return new URL(input, base);+ } catch {+ const message = `Enter a valid ${label} URL.`;+ return fail({ kind: "destination", message }, message);+ }+ }++ const guarded: FetchLike = async (input, init = {}) => {+ let url = parse(input);+ let request = init;++ for (let redirects = 0; ; redirects++) {+ await checkDestination(url);++ let response: Response;+ try {+ response = await withoutOutboundTelemetry(() =>+ baseFetch(url.href, { ...request, redirect: "manual" }),+ );+ } catch (error) {+ if (!cancelSignal?.aborted) {+ failure = { kind: "unreachable", host: url.host };+ }+ throw error;+ }++ const location = REDIRECT_STATUSES.has(response.status)+ ? response.headers.get("location")+ : null;+ if (!location) {+ failure = null;+ return response;+ }++ await response.body?.cancel().catch(() => {});+ if (redirects >= MAX_IMPORT_REDIRECTS) {+ const message = `${label} redirected too many times. Check the URL.`;+ fail({ kind: "destination", message }, message);+ }++ const next = parse(location, url);+ request = redirectInit(+ request,+ response.status,+ keepsCredentials(url, next),+ );+ url = next;+ }+ };++ return {+ fetch: guarded,+ failure: () => failure,+ lastHost: () => lastHost,+ reset: () => {+ failure = null;+ },+ };+}diff --git a/apps/api/src/import/import-run-project.ts b/apps/api/src/import/import-run-project.tsnew file mode 100644index 000000000..8e662a16c--- /dev/null+++ b/apps/api/src/import/import-run-project.ts@@ -0,0 +1,69 @@+export const IMPORT_RUN_STATUSES = ["running", "completed", "failed"] as const;++export type ImportRunStatus = (typeof IMPORT_RUN_STATUSES)[number];++export const IMPORT_RUN_PROJECT_STATUSES = [+ "pending",+ "running",+ "completed",+ "failed",+] as const;++export type ImportRunProjectStatus =+ (typeof IMPORT_RUN_PROJECT_STATUSES)[number];++export type ImportCounts = {+ columns: number;+ tasks: number;+ labels: number;+ comments: number;+ assignees: number;+ relations: number;+};++export type ImportRunProject = {+ sourceId: string;+ name: string;+ status: ImportRunProjectStatus;+ projectId: string | null;+ projectSlug: string | null;+ counts: ImportCounts;+ warnings: string[];+ error: string | null;+};++export const EMPTY_IMPORT_COUNTS: ImportCounts = {+ columns: 0,+ tasks: 0,+ labels: 0,+ comments: 0,+ assignees: 0,+ relations: 0,+};++export function pendingRunProject(+ sourceId: string,+ name: string,+): ImportRunProject {+ return {+ sourceId,+ name,+ status: "pending",+ projectId: null,+ projectSlug: null,+ counts: { ...EMPTY_IMPORT_COUNTS },+ warnings: [],+ error: null,+ };+}++export function failUnfinishedProjects(+ projects: ImportRunProject[],+ error: string,+): ImportRunProject[] {+ return projects.map((project) =>+ project.status === "pending" || project.status === "running"+ ? { ...project, status: "failed", error }+ : project,+ );+}diff --git a/apps/api/src/import/index.ts b/apps/api/src/import/index.tsnew file mode 100644index 000000000..a202d3ca7--- /dev/null+++ b/apps/api/src/import/index.ts@@ -0,0 +1,200 @@+import { requireEntitlement } from "../billing/require-entitlement-middleware";+import {+ apiRouter,+ type BaseVariables,+ createRoute,+ errorResponse,+ jsonResponse,+} from "../openapi";+import { requireWorkspacePermission } from "../utils/require-workspace-permission";+import { workspaceAccess } from "../utils/workspace-access-middleware";+import getImportRun from "./controllers/get-import-run";+import listImportRuns from "./controllers/list-import-runs";+import listSourceProjects from "./controllers/list-source-projects";+import getTrelloAuthorizeUrl from "./controllers/get-trello-authorize-url";+import startImportRun from "./controllers/start-import-run";+import {+ importRunEnvelopeSchema,+ importRunListSchema,+ importSourceProjectListSchema,+ trelloAuthorizeUrlSchema,+} from "./response";+import {+ importRunParam,+ listImportSourceProjectsBody,+ startImportRunBody,+ workspaceIdParam,+} from "./schema";++const importPermission = requireWorkspacePermission({+ workspace: ["manage_settings"],+ project: ["create"],+});++const forbidden = errorResponse(+ "Missing workspace:manage_settings or project:create permission",+);++const listImportSourceProjectsRoute = createRoute({+ method: "post",+ operationId: "listImportSourceProjects",+ path: "/projects",+ tags: ["Import"],+ summary: "List projects in an import source",+ description:+ "Sign in to PLANKA, Plane, Linear, Trello or another Kaneo instance and list the projects that can be imported. The credentials are used only for this request; they are never stored, logged, or returned.",+ middleware: [+ workspaceAccess.fromBody(),+ importPermission,+ requireEntitlement,+ ] as const,+ request: {+ body: {+ required: true,+ content: {+ "application/json": { schema: listImportSourceProjectsBody },+ },+ },+ },+ responses: {+ 200: jsonResponse(+ "Projects available in the source",+ importSourceProjectListSchema,+ ),+ 400: errorResponse(+ "Invalid body, credentials the source rejected, or a destination this server may not reach",+ ),+ 402: errorResponse("Workspace plan has expired"),+ 403: forbidden,+ 404: errorResponse("Workspace not found"),+ 502: errorResponse(+ "The source could not be reached or answered with an error",+ ),+ },+});++const startImportRunRoute = createRoute({+ method: "post",+ operationId: "startImportRun",+ path: "/runs",+ tags: ["Import"],+ summary: "Start an import",+ description:+ "Import the selected source projects into the workspace as new Kaneo projects. The import runs in the background; poll getImportRun for progress. The credentials are held in memory only while the import runs; they are never stored, logged, or returned. Imported tasks do not send notifications or trigger integrations.",+ middleware: [+ workspaceAccess.fromBody(),+ importPermission,+ requireEntitlement,+ ] as const,+ request: {+ body: {+ required: true,+ content: { "application/json": { schema: startImportRunBody } },+ },+ },+ responses: {+ 202: jsonResponse("The import started", importRunEnvelopeSchema),+ 400: errorResponse(+ "Invalid body, credentials the source rejected, a destination this server may not reach, or a selected project the source no longer lists",+ ),+ 402: errorResponse("Workspace plan has expired"),+ 403: forbidden,+ 404: errorResponse("Workspace not found"),+ 409: errorResponse("Another import is already running in this workspace"),+ 429: errorResponse(+ "This server is already running its maximum number of imports, or the API key exceeded its rate limit",+ ),+ 502: errorResponse(+ "The source could not be reached or answered with an error",+ ),+ },+});++const listImportRunsRoute = createRoute({+ method: "get",+ operationId: "listImportRuns",+ path: "/runs/{workspaceId}",+ tags: ["Import"],+ summary: "List imports",+ description:+ "The workspace's 20 most recent imports, newest first. A run whose server stopped reporting progress is returned as failed.",+ middleware: [+ workspaceAccess.fromParam("workspaceId"),+ importPermission,+ ] as const,+ request: { params: workspaceIdParam },+ responses: {+ 200: jsonResponse("Recent imports", importRunListSchema),+ 403: forbidden,+ 404: errorResponse("Workspace not found"),+ },+});++const getImportRunRoute = createRoute({+ method: "get",+ operationId: "getImportRun",+ path: "/runs/{workspaceId}/{runId}",+ tags: ["Import"],+ summary: "Get an import",+ description:+ "Progress and outcome of one import, including each project's status, counts and warnings.",+ middleware: [+ workspaceAccess.fromParam("workspaceId"),+ importPermission,+ ] as const,+ request: { params: importRunParam },+ responses: {+ 200: jsonResponse("The import", importRunEnvelopeSchema),+ 403: forbidden,+ 404: errorResponse("Workspace or import not found"),+ },+});++const getTrelloAuthorizeUrlRoute = createRoute({+ method: "get",+ operationId: "getTrelloAuthorizeUrl",+ path: "/trello/authorize-url/{workspaceId}",+ tags: ["Import"],+ summary: "Get the Trello authorize link",+ description:+ "Link to Trello's authorize page for this server's Trello app, where the user approves read access and copies a token for startImportRun. null when the server has no TRELLO_API_KEY.",+ middleware: [+ workspaceAccess.fromParam("workspaceId"),+ importPermission,+ ] as const,+ request: { params: workspaceIdParam },+ responses: {+ 200: jsonResponse("The Trello authorize link", trelloAuthorizeUrlSchema),+ 403: forbidden,+ 404: errorResponse("Workspace not found"),+ },+});++const importRoutes = apiRouter<BaseVariables & { workspaceId: string }>()+ .openapi(listImportSourceProjectsRoute, async (c) => {+ const { connection } = c.req.valid("json");+ return c.json(await listSourceProjects(connection), 200);+ })+ .openapi(startImportRunRoute, async (c) => {+ const { connection, projectIds, includeComments } = c.req.valid("json");+ const run = await startImportRun({+ workspaceId: c.get("workspaceId"),+ userId: c.get("userId"),+ connection,+ projectIds,+ includeComments,+ });+ return c.json({ run }, 202);+ })+ .openapi(listImportRunsRoute, async (c) =>+ c.json(await listImportRuns(c.get("workspaceId")), 200),+ )+ .openapi(getTrelloAuthorizeUrlRoute, async (c) =>+ c.json(getTrelloAuthorizeUrl(), 200),+ )+ .openapi(getImportRunRoute, async (c) => {+ const { runId } = c.req.valid("param");+ return c.json(await getImportRun(c.get("workspaceId"), runId), 200);+ });++export default importRoutes;diff --git a/apps/api/src/import/log-import-error.ts b/apps/api/src/import/log-import-error.tsnew file mode 100644index 000000000..8c9a59dce--- /dev/null+++ b/apps/api/src/import/log-import-error.ts@@ -0,0 +1,14 @@+function field(value: unknown, key: string) {+ const found = (value as Record<string, unknown> | null | undefined)?.[key];+ return typeof found === "string" ? found : undefined;+}++export function logImportError(context: string, runId: string, error: unknown) {+ const cause = (error as { cause?: unknown } | null)?.cause ?? error;+ console.error(context, {+ runId,+ error: error instanceof Error ? error.name : typeof error,+ code: field(cause, "code"),+ constraint: field(cause, "constraint"),+ });+}diff --git a/apps/api/src/import/response.ts b/apps/api/src/import/response.tsnew file mode 100644index 000000000..07887cd6c--- /dev/null+++ b/apps/api/src/import/response.ts@@ -0,0 +1,88 @@+import { IMPORT_SOURCE_IDS } from "@kaneo/importers";+import { nullableResponseTimestamp, responseTimestamp, z } from "../openapi";+import {+ IMPORT_RUN_PROJECT_STATUSES,+ IMPORT_RUN_STATUSES,+} from "./import-run-project";++export const importSourceProjectSchema = z+ .object({+ id: z.string(),+ name: z.string(),+ detail: z.string().optional().openapi({+ description:+ "Extra context shown next to the name, such as the source workspace or team.",+ }),+ })+ .openapi("ImportSourceProject");++export const importSourceProjectListSchema = z+ .object({ projects: z.array(importSourceProjectSchema) })+ .openapi("ImportSourceProjectList");++const importCountsSchema = z+ .object({+ columns: z.number().int(),+ tasks: z.number().int(),+ labels: z.number().int(),+ comments: z.number().int(),+ assignees: z.number().int().openapi({+ description: "Tasks that were assigned to a workspace member.",+ }),+ relations: z.number().int(),+ })+ .openapi("ImportCounts");++export const importRunProjectSchema = z+ .object({+ sourceId: z.string(),+ name: z.string(),+ status: z.enum(IMPORT_RUN_PROJECT_STATUSES),+ projectId: z.string().nullable().openapi({+ description: "The Kaneo project created by the import, once completed.",+ }),+ projectSlug: z.string().nullable(),+ counts: importCountsSchema,+ warnings: z.array(z.string()),+ error: z.string().nullable(),+ })+ .openapi("ImportRunProject");++export const importRunSchema = z+ .object({+ id: z.string(),+ workspaceId: z.string(),+ source: z.enum(IMPORT_SOURCE_IDS),+ status: z.enum(IMPORT_RUN_STATUSES).openapi({+ description:+ "completed once every selected project was attempted, even if some failed; check each project's status. failed means the run itself stopped.",+ }),+ includeComments: z.boolean(),+ message: z.string().nullable().openapi({+ description: "Latest progress line while the run is running.",+ }),+ error: z.string().nullable(),+ projects: z.array(importRunProjectSchema),+ createdAt: responseTimestamp,+ finishedAt: nullableResponseTimestamp,+ })+ .openapi("ImportRun");++export const importRunEnvelopeSchema = z+ .object({ run: importRunSchema })+ .openapi("ImportRunEnvelope");++export const importRunListSchema = z+ .object({ runs: z.array(importRunSchema) })+ .openapi("ImportRunList");++export const trelloAuthorizeUrlSchema = z+ .object({+ authorizeUrl: z.string().nullable().openapi({+ description:+ "Trello page where the user approves read access for Kaneo and copies a token. null when the server has no TRELLO_API_KEY; the user then sends their own Trello API key with the token.",+ }),+ })+ .openapi("TrelloAuthorizeUrl");++export type ImportRunResponse = z.infer<typeof importRunSchema>;diff --git a/apps/api/src/import/run-import-job.ts b/apps/api/src/import/run-import-job.tsnew file mode 100644index 000000000..7a4fdc31a--- /dev/null+++ b/apps/api/src/import/run-import-job.ts@@ -0,0 +1,156 @@+import type { ImportedProject } from "@kaneo/importers";+import { HTTPException } from "hono/http-exception";+import {+ failUnfinishedProjects,+ type ImportRunProject,+} from "./import-run-project";+import { logImportError } from "./log-import-error";+import {+ createImportRunStore,+ type ImportRunStore,+} from "./runs/import-run-store";+import { createProgressThrottle } from "./runs/progress-throttle";+import type { OpenedImportSource } from "./source/open-import-source";+import { writeImportedProject } from "./write-imported-project";++export type ImportJobState = { projects: ImportRunProject[] };++export type ImportJob = {+ runId: string;+ workspaceId: string;+ userId: string;+ includeComments: boolean;+ opened: OpenedImportSource;+ state: ImportJobState;+ signal: AbortSignal;+};++const HEARTBEAT_MS = 20_000;+const STOPPED = "The import was stopped.";+const UNEXPECTED = "The import stopped because of an unexpected error.";+const SAVE_FAILED = "Kaneo could not save this project.";++function stopReason(signal: AbortSignal) {+ return signal.reason instanceof Error ? signal.reason.message : STOPPED;+}++function updateProject(+ job: ImportJob,+ index: number,+ changes: Partial<ImportRunProject>,+) {+ job.state.projects = job.state.projects.map((project, position) =>+ position === index ? { ...project, ...changes } : project,+ );+ return job.state.projects;+}++async function readSourceProject(+ job: ImportJob,+ store: ImportRunStore,+ sourceId: string,+): Promise<ImportedProject> {+ const progress = createProgressThrottle((message) => {+ void store.save({ message });+ });+ job.opened.resetFailure();+ try {+ return await job.opened.source.readProject(sourceId, {+ includeComments: job.includeComments,+ onProgress: progress.report,+ signal: job.signal,+ });+ } finally {+ progress.cancel();+ }+}++async function importProject(+ job: ImportJob,+ store: ImportRunStore,+ index: number,+) {+ const entry = job.state.projects[index];+ if (!entry) return;++ await store.save({+ message: `Reading ${entry.name}`,+ projects: updateProject(job, index, { status: "running" }),+ });++ let project: ImportedProject;+ try {+ project = await readSourceProject(job, store, entry.sourceId);+ } catch (error) {+ if (job.signal.aborted) return;+ await store.save({+ projects: updateProject(job, index, {+ status: "failed",+ error: job.opened.describe(error).message,+ }),+ });+ return;+ }++ await store.save({ message: `Saving ${entry.name}` });++ try {+ const written = await writeImportedProject({+ workspaceId: job.workspaceId,+ userId: job.userId,+ source: job.opened.sourceId,+ project,+ includeComments: job.includeComments,+ });+ await store.save({+ projects: updateProject(job, index, {+ status: "completed",+ error: null,+ ...written,+ }),+ });+ } catch (error) {+ if (!(error instanceof HTTPException)) {+ logImportError("Failed to save an imported project", job.runId, error);+ }+ await store.save({+ projects: updateProject(job, index, {+ status: "failed",+ error: error instanceof HTTPException ? error.message : SAVE_FAILED,+ }),+ });+ }+}++export async function runImportJob(job: ImportJob): Promise<void> {+ const store = createImportRunStore(job.runId);+ const heartbeat = setInterval(() => {+ void store.save({});+ }, HEARTBEAT_MS);+ heartbeat.unref?.();++ let error: string | null = null;+ try {+ for (let index = 0; index < job.state.projects.length; index++) {+ if (job.signal.aborted || store.isDetached()) break;+ await importProject(job, store, index);+ }+ if (job.signal.aborted) error = stopReason(job.signal);+ } catch (unexpected) {+ logImportError("Import run failed", job.runId, unexpected);+ error = UNEXPECTED;+ } finally {+ clearInterval(heartbeat);+ }++ if (error) {+ job.state.projects = failUnfinishedProjects(job.state.projects, error);+ }+ await store.save({+ status: error ? "failed" : "completed",+ error,+ message: null,+ projects: job.state.projects,+ finishedAt: new Date(),+ });+}diff --git a/apps/api/src/import/runs/assert-no-running-import.ts b/apps/api/src/import/runs/assert-no-running-import.tsnew file mode 100644index 000000000..aa3eab797--- /dev/null+++ b/apps/api/src/import/runs/assert-no-running-import.ts@@ -0,0 +1,29 @@+import { and, eq, gt } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../../database";+import { importRunTable } from "../../database/schema";+import { STALE_RUN_MS } from "./to-import-run-response";++export async function assertNoRunningImport(+ workspaceId: string,+ database: Pick<typeof db, "select"> = db,+) {+ const [running] = await database+ .select({ id: importRunTable.id })+ .from(importRunTable)+ .where(+ and(+ eq(importRunTable.workspaceId, workspaceId),+ eq(importRunTable.status, "running"),+ gt(importRunTable.heartbeatAt, new Date(Date.now() - STALE_RUN_MS)),+ ),+ )+ .limit(1);++ if (running) {+ throw new HTTPException(409, {+ message:+ "An import is already running in this workspace. Wait for it to finish, then try again.",+ });+ }+}diff --git a/apps/api/src/import/runs/create-import-run.ts b/apps/api/src/import/runs/create-import-run.tsnew file mode 100644index 000000000..aa5f35c68--- /dev/null+++ b/apps/api/src/import/runs/create-import-run.ts@@ -0,0 +1,41 @@+import type { ImportSourceId } from "@kaneo/importers";+import { sql } from "drizzle-orm";+import db from "../../database";+import { importRunTable } from "../../database/schema";+import type { ImportRunProject } from "../import-run-project";+import { assertNoRunningImport } from "./assert-no-running-import";++export async function createImportRun({+ workspaceId,+ userId,+ source,+ includeComments,+ projects,+}: {+ workspaceId: string;+ userId: string;+ source: ImportSourceId;+ includeComments: boolean;+ projects: ImportRunProject[];+}) {+ return db.transaction(async (tx) => {+ await tx.execute(+ sql`SELECT pg_advisory_xact_lock(hashtext('import-run'), hashtext(${workspaceId}))`,+ );+ await assertNoRunningImport(workspaceId, tx);++ const [run] = await tx+ .insert(importRunTable)+ .values({+ workspaceId,+ userId,+ source,+ includeComments,+ projects,+ message: "Starting the import",+ })+ .returning();+ if (!run) throw new Error("Failed to create the import run");+ return run;+ });+}diff --git a/apps/api/src/import/runs/import-run-store.ts b/apps/api/src/import/runs/import-run-store.tsnew file mode 100644index 000000000..19a636349--- /dev/null+++ b/apps/api/src/import/runs/import-run-store.ts@@ -0,0 +1,50 @@+import { and, eq } from "drizzle-orm";+import db from "../../database";+import { importRunTable } from "../../database/schema";+import { logImportError } from "../log-import-error";++type RunChanges = Partial<+ Pick<+ typeof importRunTable.$inferInsert,+ "status" | "message" | "projects" | "error" | "finishedAt"+ >+>;++export type ImportRunStore = {+ save(changes: RunChanges): Promise<void>;+ isDetached(): boolean;+ flush(): Promise<void>;+};++export function createImportRunStore(runId: string): ImportRunStore {+ let chain = Promise.resolve();+ let detached = false;++ async function write(changes: RunChanges) {+ if (detached) return;+ try {+ const updated = await db+ .update(importRunTable)+ .set({ ...changes, heartbeatAt: new Date() })+ .where(+ and(+ eq(importRunTable.id, runId),+ eq(importRunTable.status, "running"),+ ),+ )+ .returning({ id: importRunTable.id });+ if (updated.length === 0) detached = true;+ } catch (error) {+ logImportError("Failed to save import progress", runId, error);+ }+ }++ return {+ save(changes) {+ chain = chain.then(() => write(changes));+ return chain;+ },+ isDetached: () => detached,+ flush: () => chain,+ };+}diff --git a/apps/api/src/import/runs/mark-stale-runs.ts b/apps/api/src/import/runs/mark-stale-runs.tsnew file mode 100644index 000000000..2ba8cca30--- /dev/null+++ b/apps/api/src/import/runs/mark-stale-runs.ts@@ -0,0 +1,29 @@+import { and, eq, lt } from "drizzle-orm";+import db from "../../database";+import { importRunTable } from "../../database/schema";+import {+ type ImportRunRow,+ interruptedRun,+ isStaleRun,+ STALE_RUN_MS,+} from "./to-import-run-response";++export async function markStaleRuns(rows: readonly ImportRunRow[], now: Date) {+ const cutoff = new Date(now.getTime() - STALE_RUN_MS);+ await Promise.all(+ rows+ .filter((row) => isStaleRun(row, now))+ .map((row) =>+ db+ .update(importRunTable)+ .set(interruptedRun(row))+ .where(+ and(+ eq(importRunTable.id, row.id),+ eq(importRunTable.status, "running"),+ lt(importRunTable.heartbeatAt, cutoff),+ ),+ ),+ ),+ );+}diff --git a/apps/api/src/import/runs/progress-throttle.test.ts b/apps/api/src/import/runs/progress-throttle.test.tsnew file mode 100644index 000000000..b68d38bed--- /dev/null+++ b/apps/api/src/import/runs/progress-throttle.test.ts@@ -0,0 +1,48 @@+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import { createProgressThrottle } from "./progress-throttle";++describe("createProgressThrottle", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("writes the first message at once and then at most once per interval", () => {+ const write = vi.fn();+ const throttle = createProgressThrottle(write, 1000);++ throttle.report("Reading cards (1 of 9)");+ throttle.report("Reading cards (2 of 9)");+ throttle.report("Reading cards (3 of 9)");+ expect(write.mock.calls).toEqual([["Reading cards (1 of 9)"]]);++ vi.advanceTimersByTime(999);+ expect(write).toHaveBeenCalledTimes(1);++ vi.advanceTimersByTime(1);+ expect(write.mock.calls.at(-1)).toEqual(["Reading cards (3 of 9)"]);+ expect(write).toHaveBeenCalledTimes(2);+ });++ it("drops a pending message when cancelled", () => {+ const write = vi.fn();+ const throttle = createProgressThrottle(write, 1000);++ throttle.report("first");+ throttle.report("second");+ throttle.cancel();+ vi.advanceTimersByTime(5000);++ expect(write.mock.calls).toEqual([["first"]]);+ });+});diff --git a/apps/api/src/import/runs/progress-throttle.ts b/apps/api/src/import/runs/progress-throttle.tsnew file mode 100644index 000000000..7e69b3540--- /dev/null+++ b/apps/api/src/import/runs/progress-throttle.ts@@ -0,0 +1,42 @@+export type ProgressThrottle = {+ report(message: string): void;+ cancel(): void;+};++export function createProgressThrottle(+ write: (message: string) => void,+ intervalMs = 1000,+ now: () => number = Date.now,+): ProgressThrottle {+ let lastWrite = Number.NEGATIVE_INFINITY;+ let pending: string | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;++ function flush() {+ timer = null;+ if (pending === null) return;+ const message = pending;+ pending = null;+ lastWrite = now();+ write(message);+ }++ return {+ report(message) {+ pending = message;+ if (timer) return;+ const wait = lastWrite + intervalMs - now();+ if (wait <= 0) {+ flush();+ return;+ }+ timer = setTimeout(flush, wait);+ timer.unref?.();+ },+ cancel() {+ if (timer) clearTimeout(timer);+ timer = null;+ pending = null;+ },+ };+}diff --git a/apps/api/src/import/runs/stop-active-imports.ts b/apps/api/src/import/runs/stop-active-imports.tsnew file mode 100644index 000000000..284bcd70a--- /dev/null+++ b/apps/api/src/import/runs/stop-active-imports.ts@@ -0,0 +1,54 @@+import { and, eq } from "drizzle-orm";+import db from "../../database";+import { importRunTable } from "../../database/schema";+import { activeImportSlots } from "../active-imports";+import {+ failUnfinishedProjects,+ type ImportRunProject,+} from "../import-run-project";+import { logImportError } from "../log-import-error";++export const RESTART_ERROR = "Kaneo restarted during the import.";++const SHUTDOWN_GRACE_MS = 5_000;++async function markStopped(runId: string, projects: ImportRunProject[]) {+ try {+ await db+ .update(importRunTable)+ .set({+ status: "failed",+ error: RESTART_ERROR,+ message: null,+ projects: failUnfinishedProjects(projects, RESTART_ERROR),+ finishedAt: new Date(),+ })+ .where(+ and(eq(importRunTable.id, runId), eq(importRunTable.status, "running")),+ );+ } catch (error) {+ logImportError("Failed to mark an import as stopped", runId, error);+ }+}++export async function stopActiveImports(graceMs = SHUTDOWN_GRACE_MS) {+ const slots = activeImportSlots();+ if (slots.length === 0) return;++ for (const slot of slots) slot.controller.abort(new Error(RESTART_ERROR));++ let timer: ReturnType<typeof setTimeout> | undefined;+ await Promise.race([+ Promise.allSettled(slots.map((slot) => slot.job)),+ new Promise((resolve) => {+ timer = setTimeout(resolve, graceMs);+ }),+ ]);+ clearTimeout(timer);++ await Promise.all(+ activeImportSlots().flatMap((slot) =>+ slot.runId ? [markStopped(slot.runId, slot.projects())] : [],+ ),+ );+}diff --git a/apps/api/src/import/runs/to-import-run-response.test.ts b/apps/api/src/import/runs/to-import-run-response.test.tsnew file mode 100644index 000000000..ac91d0738--- /dev/null+++ b/apps/api/src/import/runs/to-import-run-response.test.ts@@ -0,0 +1,106 @@+import { describe, expect, it } from "vite-plus/test";+import { pendingRunProject } from "../import-run-project";+import {+ INTERRUPTED_RUN_ERROR,+ type ImportRunRow,+ isStaleRun,+ toImportRunResponse,+} from "./to-import-run-response";++const createdAt = new Date("2026-10-01T10:00:00.000Z");++function row(overrides: Partial<ImportRunRow> = {}): ImportRunRow {+ return {+ id: "run-1",+ workspaceId: "workspace-1",+ userId: "user-1",+ source: "planka",+ status: "running",+ includeComments: true,+ message: "Reading cards (20 of 80)",+ projects: [+ { ...pendingRunProject("a", "Alpha"), status: "completed" },+ { ...pendingRunProject("b", "Beta"), status: "running" },+ pendingRunProject("c", "Gamma"),+ ],+ error: null,+ heartbeatAt: new Date("2026-10-01T10:05:00.000Z"),+ createdAt,+ finishedAt: null,+ ...overrides,+ };+}++describe("toImportRunResponse", () => {+ it("returns a fresh running run as it is, without the user", () => {+ const now = new Date("2026-10-01T10:06:00.000Z");+ const response = toImportRunResponse(row(), now);++ expect(response).toEqual({+ id: "run-1",+ workspaceId: "workspace-1",+ source: "planka",+ status: "running",+ includeComments: true,+ message: "Reading cards (20 of 80)",+ error: null,+ projects: row().projects,+ createdAt,+ finishedAt: null,+ });+ expect(response).not.toHaveProperty("userId");+ });++ it("reports a running run with a stale heartbeat as interrupted", () => {+ const now = new Date("2026-10-01T10:07:01.000Z");+ const response = toImportRunResponse(row(), now);++ expect(response.status).toBe("failed");+ expect(response.error).toBe(INTERRUPTED_RUN_ERROR);+ expect(response.message).toBeNull();+ expect(response.finishedAt).toEqual(row().heartbeatAt);+ expect(response.projects.map((project) => project.status)).toEqual([+ "completed",+ "failed",+ "failed",+ ]);+ expect(response.projects[1]?.error).toBe(INTERRUPTED_RUN_ERROR);+ expect(response.projects[0]?.error).toBeNull();+ });++ it("leaves finished runs alone however old their heartbeat is", () => {+ const finishedAt = new Date("2026-10-01T10:05:00.000Z");+ const response = toImportRunResponse(+ row({ status: "completed", message: null, finishedAt }),+ new Date("2026-10-09T00:00:00.000Z"),+ );++ expect(response.status).toBe("completed");+ expect(response.error).toBeNull();+ expect(response.finishedAt).toEqual(finishedAt);+ });++ it("treats an unknown stored status as failed", () => {+ expect(toImportRunResponse(row({ status: "paused" })).status).toBe(+ "failed",+ );+ });+});++describe("isStaleRun", () => {+ it("allows two minutes of silence", () => {+ const heartbeatAt = new Date("2026-10-01T10:00:00.000Z");+ expect(+ isStaleRun(+ { status: "running", heartbeatAt },+ new Date("2026-10-01T10:02:00.000Z"),+ ),+ ).toBe(false);+ expect(+ isStaleRun(+ { status: "running", heartbeatAt },+ new Date("2026-10-01T10:02:00.001Z"),+ ),+ ).toBe(true);+ });+});diff --git a/apps/api/src/import/runs/to-import-run-response.ts b/apps/api/src/import/runs/to-import-run-response.tsnew file mode 100644index 000000000..e8044b285--- /dev/null+++ b/apps/api/src/import/runs/to-import-run-response.ts@@ -0,0 +1,63 @@+import type { ImportSourceId } from "@kaneo/importers";+import type { importRunTable } from "../../database/schema";+import {+ failUnfinishedProjects,+ IMPORT_RUN_STATUSES,+ type ImportRunStatus,+} from "../import-run-project";+import type { ImportRunResponse } from "../response";++export type ImportRunRow = typeof importRunTable.$inferSelect;++export const STALE_RUN_MS = 2 * 60_000;++export const INTERRUPTED_RUN_ERROR =+ "The import was interrupted before it finished.";++export function isStaleRun(+ row: Pick<ImportRunRow, "status" | "heartbeatAt">,+ now: Date,+) {+ return (+ row.status === "running" &&+ now.getTime() - row.heartbeatAt.getTime() > STALE_RUN_MS+ );+}++function runStatus(status: string): ImportRunStatus {+ return (IMPORT_RUN_STATUSES as readonly string[]).includes(status)+ ? (status as ImportRunStatus)+ : "failed";+}++export function interruptedRun(row: ImportRunRow) {+ return {+ status: "failed" as const,+ message: null,+ error: INTERRUPTED_RUN_ERROR,+ projects: failUnfinishedProjects(row.projects, INTERRUPTED_RUN_ERROR),+ finishedAt: row.heartbeatAt,+ };+}++export function toImportRunResponse(+ row: ImportRunRow,+ now = new Date(),+): ImportRunResponse {+ const current = isStaleRun(row, now)+ ? { ...row, ...interruptedRun(row) }+ : row;++ return {+ id: current.id,+ workspaceId: current.workspaceId,+ source: current.source as ImportSourceId,+ status: runStatus(current.status),+ includeComments: current.includeComments,+ message: current.message,+ error: current.error,+ projects: current.projects,+ createdAt: current.createdAt,+ finishedAt: current.finishedAt,+ };+}diff --git a/apps/api/src/import/schema.ts b/apps/api/src/import/schema.tsnew file mode 100644index 000000000..105b12653--- /dev/null+++ b/apps/api/src/import/schema.ts@@ -0,0 +1,137 @@+import { z } from "../openapi";++const NEVER_STORED = "Used only for this import and never stored or logged.";++function sourceUrl(description: string) {+ return z+ .string()+ .trim()+ .min(1)+ .max(2048)+ .openapi({ description, example: "https://planka.example.com" });+}++function secret(description: string) {+ return z+ .string()+ .trim()+ .min(1)+ .max(4096)+ .openapi({ description: `${description} ${NEVER_STORED}` });+}++const plankaConnection = z+ .object({+ source: z.literal("planka"),+ url: sourceUrl("Address of the PLANKA instance."),+ apiKey: secret(+ "A PLANKA API key. Send it, or username and password.",+ ).optional(),+ username: z.string().trim().min(1).max(256).optional().openapi({+ description:+ "Username or email of a PLANKA account, used with password when no API key is sent.",+ }),+ password: z+ .string()+ .min(1)+ .max(4096)+ .optional()+ .openapi({+ description: `Password of that PLANKA account. ${NEVER_STORED}`,+ }),+ })+ .refine(+ (connection) =>+ Boolean(connection.apiKey) ||+ Boolean(connection.username && connection.password),+ {+ message: "Enter a PLANKA API key, or a username and password",+ path: ["apiKey"],+ },+ )+ .openapi("PlankaImportConnection");++const planeConnection = z+ .object({+ source: z.literal("plane"),+ url: sourceUrl(+ "Address of the Plane instance, e.g. https://app.plane.so for Plane Cloud.",+ ),+ apiKey: secret("A Plane personal access token."),+ workspaceSlug: z.string().trim().min(1).max(256).optional().openapi({+ description:+ "Slug of the Plane workspace to read. Optional when the URL already names it.",+ }),+ })+ .openapi("PlaneImportConnection");++const linearConnection = z+ .object({+ source: z.literal("linear"),+ apiKey: secret("A Linear personal API key."),+ })+ .openapi("LinearImportConnection");++const trelloConnection = z+ .object({+ source: z.literal("trello"),+ token: secret("A Trello token authorized for this Kaneo instance."),+ apiKey: z.string().trim().min(1).max(256).optional().openapi({+ description:+ "Trello API key, a public app identifier. Defaults to the server's TRELLO_API_KEY.",+ }),+ })+ .openapi("TrelloImportConnection");++const kaneoConnection = z+ .object({+ source: z.literal("kaneo"),+ url: sourceUrl("Address of the Kaneo instance to import from."),+ apiKey: secret("An API key from that Kaneo instance."),+ })+ .openapi("KaneoImportConnection");++export const importConnectionSchema = z+ .discriminatedUnion("source", [+ plankaConnection,+ planeConnection,+ linearConnection,+ trelloConnection,+ kaneoConnection,+ ])+ .openapi("ImportConnection", {+ description: `Where to import from and how to sign in. Credentials are used only for this request and the import it starts; they are never stored, logged, or returned.`,+ });++export type ImportConnectionInput = z.infer<typeof importConnectionSchema>;++export const listImportSourceProjectsBody = z.object({+ workspaceId: z.string().min(1),+ connection: importConnectionSchema,+});++export const startImportRunBody = z.object({+ workspaceId: z.string().min(1),+ connection: importConnectionSchema,+ projectIds: z+ .array(z.string().trim().min(1).max(512))+ .min(1)+ .max(50)+ .refine((ids) => new Set(ids).size === ids.length, {+ message: "Project IDs must be unique",+ })+ .openapi({+ description:+ "Source project IDs from listImportSourceProjects, imported in this order.",+ }),+ includeComments: z.boolean().default(true).openapi({+ description: "Import task comments too. Defaults to true.",+ }),+});++export const workspaceIdParam = z.object({ workspaceId: z.string() });++export const importRunParam = z.object({+ workspaceId: z.string(),+ runId: z.string(),+});diff --git a/apps/api/src/import/source/describe-import-error.test.ts b/apps/api/src/import/source/describe-import-error.test.tsnew file mode 100644index 000000000..0bced8c91--- /dev/null+++ b/apps/api/src/import/source/describe-import-error.test.ts@@ -0,0 +1,138 @@+import { describe, expect, it } from "vite-plus/test";+import {+ describeImportError,+ type ImportErrorContext,+ sanitizeImportMessage,+} from "./describe-import-error";++class SourceHttpError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ this.name = "SourceHttpError";+ }+}++const context: ImportErrorContext = {+ sourceName: "PLANKA",+ credentialHint: "Check the API key.",+ failure: null,+ lastHost: "planka.example.com",+ secrets: ["super-secret-key"],+};++describe("describeImportError", () => {+ it("explains rejected credentials without the adapter's request path", () => {+ expect(+ describeImportError(+ new SourceHttpError("PLANKA /api/users/me: unauthorized", 401),+ context,+ ),+ ).toEqual({+ status: 400,+ message: "Could not sign in to PLANKA. Check the API key.",+ });+ expect(+ describeImportError(new SourceHttpError("forbidden", 403), {+ ...context,+ credentialHint: "Check the username and password.",+ }).message,+ ).toBe("Could not sign in to PLANKA. Check the username and password.");+ });++ it("reports unreachable hosts as a bad gateway", () => {+ expect(+ describeImportError(new Error("PLANKA /api: fetch failed"), {+ ...context,+ failure: { kind: "unreachable", host: "planka.lan:3000" },+ }),+ ).toEqual({+ status: 502,+ message: "Could not reach PLANKA at planka.lan:3000.",+ });+ });++ it("passes the destination check message through", () => {+ expect(+ describeImportError(new Error("wrapped"), {+ ...context,+ failure: {+ kind: "destination",+ message: "PLANKA destination resolves to a non-routable address",+ },+ }),+ ).toEqual({+ status: 400,+ message: "PLANKA destination resolves to a non-routable address",+ });+ });++ it("explains timeouts", () => {+ expect(+ describeImportError(+ new DOMException("The operation timed out.", "TimeoutError"),+ context,+ ),+ ).toEqual({+ status: 502,+ message: "PLANKA at planka.example.com took too long to answer.",+ });+ });++ it("maps upstream failures by status", () => {+ expect(describeImportError(new SourceHttpError("x", 503), context)).toEqual(+ {+ status: 502,+ message: "PLANKA returned an error (HTTP 503). Try again later.",+ },+ );+ expect(+ describeImportError(new SourceHttpError("x", 404), context).status,+ ).toBe(400);+ expect(+ describeImportError(new SourceHttpError("x", 429), context).status,+ ).toBe(502);+ });++ it("shows an adapter's own message without secrets or query strings", () => {+ expect(+ describeImportError(+ new Error(+ "Board not found at https://api.trello.com/1/boards/1?key=abc&token=super-secret-key for super-secret-key",+ ),+ context,+ ),+ ).toEqual({+ status: 400,+ message:+ "Board not found at https://api.trello.com/1/boards/1 for [redacted]",+ });+ });++ it("hides programming errors behind a generic message", () => {+ expect(+ describeImportError(+ new TypeError("Cannot read properties of undefined (reading 'id')"),+ context,+ ),+ ).toEqual({+ status: 502,+ message: "PLANKA sent a response Kaneo could not read.",+ });+ expect(describeImportError("boom", context).status).toBe(502);+ });+});++describe("sanitizeImportMessage", () => {+ it("refuses to show a message containing a short secret", () => {+ expect(sanitizeImportMessage("wrong pin 1234", ["1234"])).toBeNull();+ });++ it("caps long messages", () => {+ const message = sanitizeImportMessage("x".repeat(900), []);+ expect(message?.length).toBe(500);+ expect(message?.endsWith("...")).toBe(true);+ });+});diff --git a/apps/api/src/import/source/describe-import-error.ts b/apps/api/src/import/source/describe-import-error.tsnew file mode 100644index 000000000..b7506513b--- /dev/null+++ b/apps/api/src/import/source/describe-import-error.ts@@ -0,0 +1,125 @@+import type { GuardFailure } from "../guarded-fetch";++export type ImportErrorContext = {+ sourceName: string;+ credentialHint: string;+ failure: GuardFailure | null;+ lastHost: string | null;+ secrets: readonly string[];+};++export type DescribedImportError = { status: 400 | 502; message: string };++const MAX_MESSAGE_LENGTH = 500;+const MIN_REDACTABLE_SECRET_LENGTH = 6;+const PROGRAMMING_ERRORS = new Set([+ "TypeError",+ "SyntaxError",+ "RangeError",+ "ReferenceError",+]);++function errorName(error: unknown) {+ return error instanceof Error || error instanceof DOMException+ ? error.name+ : null;+}++function sourceHttpStatus(error: unknown) {+ if (!(error instanceof Error) || error.name !== "SourceHttpError") {+ return null;+ }+ const status = (error as { status?: unknown }).status;+ return typeof status === "number" ? status : null;+}++function describeHttpStatus(+ status: number,+ { sourceName, credentialHint }: ImportErrorContext,+): DescribedImportError {+ if (status === 401 || status === 403) {+ return {+ status: 400,+ message: `Could not sign in to ${sourceName}. ${credentialHint}`,+ };+ }+ if (status === 404) {+ return {+ status: 400,+ message: `${sourceName} could not find what Kaneo asked for (HTTP 404). Check the URL.`,+ };+ }+ if (status === 429) {+ return {+ status: 502,+ message: `${sourceName} is limiting requests. Try again in a few minutes.`,+ };+ }+ if (status >= 500) {+ return {+ status: 502,+ message: `${sourceName} returned an error (HTTP ${status}). Try again later.`,+ };+ }+ return {+ status: 400,+ message: `${sourceName} refused the request (HTTP ${status}).`,+ };+}++export function sanitizeImportMessage(+ message: string,+ secrets: readonly string[],+): string | null {+ let clean = message.replace(/(https?:\/\/[^\s?#]+)[?#]\S*/gi, "$1");+ for (const secret of secrets) {+ if (!secret || !clean.includes(secret)) continue;+ if (secret.length < MIN_REDACTABLE_SECRET_LENGTH) return null;+ clean = clean.split(secret).join("[redacted]");+ }+ clean = clean.trim();+ if (!clean) return null;+ return clean.length > MAX_MESSAGE_LENGTH+ ? `${clean.slice(0, MAX_MESSAGE_LENGTH - 3)}...`+ : clean;+}++export function describeImportError(+ error: unknown,+ context: ImportErrorContext,+): DescribedImportError {+ const { sourceName, failure, lastHost } = context;++ if (failure?.kind === "destination") {+ return { status: 400, message: failure.message };+ }+ if (failure?.kind === "unreachable") {+ return {+ status: 502,+ message: `Could not reach ${sourceName} at ${failure.host}.`,+ };+ }++ const name = errorName(error);+ if (name === "TimeoutError" || name === "AbortError") {+ return {+ status: 502,+ message: lastHost+ ? `${sourceName} at ${lastHost} took too long to answer.`+ : `${sourceName} took too long to answer.`,+ };+ }++ const httpStatus = sourceHttpStatus(error);+ if (httpStatus !== null) return describeHttpStatus(httpStatus, context);++ if (error instanceof Error && !PROGRAMMING_ERRORS.has(error.name)) {+ const message = sanitizeImportMessage(error.message, context.secrets);+ if (message) return { status: 400, message };+ }++ return {+ status: 502,+ message: `${sourceName} sent a response Kaneo could not read.`,+ };+}diff --git a/apps/api/src/import/source/open-import-source.ts b/apps/api/src/import/source/open-import-source.tsnew file mode 100644index 000000000..bb8295311--- /dev/null+++ b/apps/api/src/import/source/open-import-source.ts@@ -0,0 +1,59 @@+import {+ connectSource,+ type ImportSource,+ type ImportSourceId,+} from "@kaneo/importers";+import { HTTPException } from "hono/http-exception";+import { createGuardedFetch } from "../guarded-fetch";+import type { ImportConnectionInput } from "../schema";+import {+ type DescribedImportError,+ describeImportError,+} from "./describe-import-error";+import { resolveImportConnection } from "./resolve-import-connection";+import { IMPORT_SOURCE_NAMES } from "./source-names";++export type OpenedImportSource = {+ sourceId: ImportSourceId;+ sourceName: string;+ source: ImportSource;+ describe(error: unknown): DescribedImportError;+ resetFailure(): void;+};++export function importHttpError({ status, message }: DescribedImportError) {+ return new HTTPException(status, { message });+}++export async function openImportSource(+ input: ImportConnectionInput,+ signal: AbortSignal,+): Promise<OpenedImportSource> {+ const resolved = resolveImportConnection(input);+ const sourceName = IMPORT_SOURCE_NAMES[input.source];+ const guard = createGuardedFetch(sourceName, { cancelSignal: signal });+ const describe = (error: unknown) =>+ describeImportError(error, {+ sourceName,+ credentialHint: resolved.credentialHint,+ failure: guard.failure(),+ lastHost: guard.lastHost(),+ secrets: resolved.secrets,+ });++ try {+ const source = await connectSource(resolved.connection, {+ fetch: guard.fetch,+ signal,+ });+ return {+ sourceId: input.source,+ sourceName,+ source,+ describe,+ resetFailure: guard.reset,+ };+ } catch (error) {+ throw importHttpError(describe(error));+ }+}diff --git a/apps/api/src/import/source/resolve-import-connection.test.ts b/apps/api/src/import/source/resolve-import-connection.test.tsnew file mode 100644index 000000000..81a0ac340--- /dev/null+++ b/apps/api/src/import/source/resolve-import-connection.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vite-plus/test";+import { resolveImportConnection } from "./resolve-import-connection";++describe("resolveImportConnection", () => {+ it("sends PLANKA an API key when one is given", () => {+ expect(+ resolveImportConnection(+ {+ source: "planka",+ url: "https://planka.example.com",+ apiKey: "key-123456",+ username: "ana",+ password: "hunter22",+ },+ {},+ ),+ ).toEqual({+ connection: {+ source: "planka",+ url: "https://planka.example.com",+ apiKey: "key-123456",+ },+ secrets: ["key-123456", "hunter22"],+ credentialHint: "Check the API key.",+ });+ });++ it("signs in to PLANKA with a password otherwise", () => {+ const resolved = resolveImportConnection(+ {+ source: "planka",+ url: "https://planka.example.com",+ username: "ana",+ password: "hunter22",+ },+ {},+ );++ expect(resolved.connection).toEqual({+ source: "planka",+ url: "https://planka.example.com",+ username: "ana",+ password: "hunter22",+ });+ expect(resolved.credentialHint).toBe("Check the username and password.");+ });++ it("falls back to the server's Trello API key", () => {+ expect(+ resolveImportConnection(+ { source: "trello", token: "token-123456" },+ { TRELLO_API_KEY: " app-key " },+ ).connection,+ ).toEqual({ source: "trello", apiKey: "app-key", token: "token-123456" });++ expect(+ resolveImportConnection(+ { source: "trello", token: "token-123456", apiKey: "own-key" },+ { TRELLO_API_KEY: "app-key" },+ ).connection,+ ).toEqual({ source: "trello", apiKey: "own-key", token: "token-123456" });+ });++ it("asks for a Trello API key when there is none", () => {+ expect(() =>+ resolveImportConnection({ source: "trello", token: "token-123456" }, {}),+ ).toThrow("Add a Trello API key.");+ });+});diff --git a/apps/api/src/import/source/resolve-import-connection.ts b/apps/api/src/import/source/resolve-import-connection.tsnew file mode 100644index 000000000..1b9b7afd1--- /dev/null+++ b/apps/api/src/import/source/resolve-import-connection.ts@@ -0,0 +1,66 @@+import type { ImportConnection } from "@kaneo/importers";+import { HTTPException } from "hono/http-exception";+import type { ImportConnectionInput } from "../schema";+import { trelloApiKeyFromEnv } from "./trello-api-key";++export type ResolvedImportConnection = {+ connection: ImportConnection;+ secrets: string[];+ credentialHint: string;+};++export function resolveImportConnection(+ input: ImportConnectionInput,+ env: NodeJS.ProcessEnv = process.env,+): ResolvedImportConnection {+ switch (input.source) {+ case "planka": {+ const { source, url, apiKey, username, password } = input;+ const usesPassword = !apiKey;+ return {+ connection: {+ source,+ url,+ ...(apiKey ? { apiKey } : { username, password }),+ },+ secrets: [apiKey, password].filter(isPresent),+ credentialHint: usesPassword+ ? "Check the username and password."+ : "Check the API key.",+ };+ }+ case "trello": {+ const apiKey = input.apiKey ?? trelloApiKeyFromEnv(env);+ if (!apiKey) {+ throw new HTTPException(400, { message: "Add a Trello API key." });+ }+ return {+ connection: { source: "trello", apiKey, token: input.token },+ secrets: [input.token, apiKey],+ credentialHint: "Check the API key and token.",+ };+ }+ case "plane":+ return {+ connection: input,+ secrets: [input.apiKey],+ credentialHint: "Check the API key.",+ };+ case "linear":+ return {+ connection: input,+ secrets: [input.apiKey],+ credentialHint: "Check the API key.",+ };+ case "kaneo":+ return {+ connection: input,+ secrets: [input.apiKey],+ credentialHint: "Check the API key.",+ };+ }+}++function isPresent(value: string | undefined): value is string {+ return Boolean(value);+}diff --git a/apps/api/src/import/source/select-source-projects.test.ts b/apps/api/src/import/source/select-source-projects.test.tsnew file mode 100644index 000000000..e7e25e7e4--- /dev/null+++ b/apps/api/src/import/source/select-source-projects.test.ts@@ -0,0 +1,32 @@+import { HTTPException } from "hono/http-exception";+import { describe, expect, it } from "vite-plus/test";+import { selectSourceProjects } from "./select-source-projects";++const available = [+ { id: "1", name: "Website" },+ { id: "2", name: " Mobile ", detail: "Team A" },+ { id: "3", name: " " },+];++describe("selectSourceProjects", () => {+ it("keeps the requested order and takes names from the source", () => {+ expect(+ selectSourceProjects(["3", "2", "1"], available, "PLANKA").map(+ ({ sourceId, name, status }) => ({ sourceId, name, status }),+ ),+ ).toEqual([+ { sourceId: "3", name: "Untitled project", status: "pending" },+ { sourceId: "2", name: "Mobile", status: "pending" },+ { sourceId: "1", name: "Website", status: "pending" },+ ]);+ });++ it("refuses projects the source no longer lists", () => {+ expect(() => selectSourceProjects(["1", "9"], available, "Linear")).toThrow(+ HTTPException,+ );+ expect(() => selectSourceProjects(["8", "9"], available, "Linear")).toThrow(+ "2 selected projects are no longer available in Linear. Refresh the list and try again.",+ );+ });+});diff --git a/apps/api/src/import/source/select-source-projects.ts b/apps/api/src/import/source/select-source-projects.tsnew file mode 100644index 000000000..df5c6f9aa--- /dev/null+++ b/apps/api/src/import/source/select-source-projects.ts@@ -0,0 +1,29 @@+import type { SourceProject } from "@kaneo/importers";+import { HTTPException } from "hono/http-exception";+import {+ type ImportRunProject,+ pendingRunProject,+} from "../import-run-project";++export function selectSourceProjects(+ projectIds: readonly string[],+ available: readonly SourceProject[],+ sourceName: string,+): ImportRunProject[] {+ const byId = new Map(available.map((project) => [project.id, project]));+ const missing = projectIds.filter((id) => !byId.has(id));++ if (missing.length > 0) {+ const subject =+ missing.length === 1+ ? "A selected project is"+ : `${missing.length} selected projects are`;+ throw new HTTPException(400, {+ message: `${subject} no longer available in ${sourceName}. Refresh the list and try again.`,+ });+ }++ return projectIds.map((id) =>+ pendingRunProject(id, byId.get(id)?.name.trim() || "Untitled project"),+ );+}diff --git a/apps/api/src/import/source/source-names.ts b/apps/api/src/import/source/source-names.tsnew file mode 100644index 000000000..96ea05ca6--- /dev/null+++ b/apps/api/src/import/source/source-names.ts@@ -0,0 +1,9 @@+import type { ImportSourceId } from "@kaneo/importers";++export const IMPORT_SOURCE_NAMES: Record<ImportSourceId, string> = {+ planka: "PLANKA",+ plane: "Plane",+ linear: "Linear",+ trello: "Trello",+ kaneo: "Kaneo",+};diff --git a/apps/api/src/import/source/trello-api-key.ts b/apps/api/src/import/source/trello-api-key.tsnew file mode 100644index 000000000..9d154a64b--- /dev/null+++ b/apps/api/src/import/source/trello-api-key.ts@@ -0,0 +1,3 @@+export function trelloApiKeyFromEnv(env: NodeJS.ProcessEnv = process.env) {+ return env.TRELLO_API_KEY?.trim() || null;+}diff --git a/apps/api/src/import/write-imported-project.ts b/apps/api/src/import/write-imported-project.tsnew file mode 100644index 000000000..c53f5b849--- /dev/null+++ b/apps/api/src/import/write-imported-project.ts@@ -0,0 +1,71 @@+import type { ImportedProject, ImportSourceId } from "@kaneo/importers";+import { eq } from "drizzle-orm";+import db from "../database";+import { projectTable } from "../database/schema";+import { publishEvent } from "../events";+import type { ImportCounts } from "./import-run-project";+import { createImportProject } from "./writer/create-import-project";+import { writeProjectContent } from "./writer/write-project-content";++export type WriteImportedProjectInput = {+ workspaceId: string;+ userId: string;+ source: ImportSourceId;+ project: ImportedProject;+ includeComments: boolean;+};++export type WrittenImportProject = {+ projectId: string;+ projectSlug: string;+ counts: ImportCounts;+ warnings: string[];+};++export async function writeImportedProject({+ workspaceId,+ userId,+ source,+ project,+ includeComments,+}: WriteImportedProjectInput): Promise<WrittenImportProject> {+ const name = project.name.trim() || "Untitled project";+ const created = await createImportProject(+ workspaceId,+ name,+ userId,+ project.key,+ );++ let content: Awaited<ReturnType<typeof writeProjectContent>>;+ try {+ content = await db.transaction((tx) =>+ writeProjectContent(tx, {+ projectId: created.id,+ workspaceId,+ userId,+ source,+ project,+ includeComments,+ }),+ );+ } catch (error) {+ await db+ .delete(projectTable)+ .where(eq(projectTable.id, created.id))+ .catch(() => {+ console.error("Failed to remove a partially imported project", {+ projectId: created.id,+ });+ });+ throw error;+ }++ await publishEvent("project.updated", { projectId: created.id });++ return {+ projectId: created.id,+ projectSlug: created.slug,+ ...content,+ };+}diff --git a/apps/api/src/import/writer/assign-import-task-numbers.test.ts b/apps/api/src/import/writer/assign-import-task-numbers.test.tsnew file mode 100644index 000000000..843fda002--- /dev/null+++ b/apps/api/src/import/writer/assign-import-task-numbers.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from "vite-plus/test";+import { assignImportTaskNumbers } from "./assign-import-task-numbers";++const numbered = (...numbers: (number | undefined)[]) =>+ numbers.map((number) => (number === undefined ? {} : { number }));++describe("assignImportTaskNumbers", () => {+ it("keeps source numbers that are all present and unique", () => {+ expect(assignImportTaskNumbers(numbered(12, 3, 7))).toEqual({+ numbers: [12, 3, 7],+ lastNumber: 12,+ });+ });++ it("numbers tasks without a source number after the highest one", () => {+ expect(+ assignImportTaskNumbers(numbered(undefined, 3, undefined, 7)),+ ).toEqual({+ numbers: [8, 3, 9, 7],+ lastNumber: 9,+ });+ });++ it("numbers every task in order when none has a source number", () => {+ expect(assignImportTaskNumbers(numbered(undefined, undefined))).toEqual({+ numbers: [1, 2],+ lastNumber: 2,+ });+ });++ it("keeps the first of duplicate numbers and moves the rest to the end", () => {+ expect(assignImportTaskNumbers(numbered(5, 2, 5, 2, 9))).toEqual({+ numbers: [5, 2, 10, 11, 9],+ lastNumber: 11,+ });+ });++ it("never reuses a kept number for a task numbered later", () => {+ expect(assignImportTaskNumbers(numbered(undefined, 1, 2))).toEqual({+ numbers: [3, 1, 2],+ lastNumber: 3,+ });+ });++ it("replaces zero, negative, fractional and unsafe numbers", () => {+ expect(+ assignImportTaskNumbers(+ numbered(0, -4, 2.5, Number.NaN, Number.MAX_SAFE_INTEGER + 1, 4),+ ),+ ).toEqual({+ numbers: [5, 6, 7, 8, 9, 4],+ lastNumber: 9,+ });+ });++ it("replaces numbers too large to store with room for the rest", () => {+ expect(assignImportTaskNumbers(numbered(2_147_483_647, 1))).toEqual({+ numbers: [2, 1],+ lastNumber: 2,+ });+ });++ it("returns nothing for an empty list", () => {+ expect(assignImportTaskNumbers([])).toEqual({ numbers: [], lastNumber: 0 });+ });+});diff --git a/apps/api/src/import/writer/assign-import-task-numbers.ts b/apps/api/src/import/writer/assign-import-task-numbers.tsnew file mode 100644index 000000000..8aa18c2c6--- /dev/null+++ b/apps/api/src/import/writer/assign-import-task-numbers.ts@@ -0,0 +1,34 @@+const MAX_TASK_NUMBER = 2_147_483_647;++export type ImportTaskNumbers = {+ numbers: number[];+ lastNumber: number;+};++export function assignImportTaskNumbers(+ tasks: readonly { number?: number }[],+): ImportTaskNumbers {+ const limit = MAX_TASK_NUMBER - tasks.length;+ const kept = new Set<number>();+ const keeps = tasks.map(({ number }) => {+ if (+ number === undefined ||+ !Number.isSafeInteger(number) ||+ number < 1 ||+ number > limit ||+ kept.has(number)+ ) {+ return false;+ }+ kept.add(number);+ return true;+ });++ let last = 0;+ for (const number of kept) last = Math.max(last, number);++ const numbers = tasks.map(({ number }, index) =>+ keeps[index] && number !== undefined ? number : ++last,+ );+ return { numbers, lastNumber: last };+}diff --git a/apps/api/src/import/writer/chunk.ts b/apps/api/src/import/writer/chunk.tsnew file mode 100644index 000000000..7fb6494a4--- /dev/null+++ b/apps/api/src/import/writer/chunk.ts@@ -0,0 +1,9 @@+export const IMPORT_CHUNK_SIZE = 500;++export function chunk<T>(items: readonly T[], size = IMPORT_CHUNK_SIZE): T[][] {+ const chunks: T[][] = [];+ for (let start = 0; start < items.length; start += size) {+ chunks.push(items.slice(start, start + size));+ }+ return chunks;+}diff --git a/apps/api/src/import/writer/create-import-project.ts b/apps/api/src/import/writer/create-import-project.tsnew file mode 100644index 000000000..e299e14ae--- /dev/null+++ b/apps/api/src/import/writer/create-import-project.ts@@ -0,0 +1,26 @@+import { eq } from "drizzle-orm";+import db from "../../database";+import { projectTable } from "../../database/schema";+import createProject from "../../project/controllers/create-project";+import { createWithUniqueKey } from "./create-with-unique-key";++export async function createImportProject(+ workspaceId: string,+ name: string,+ userId: string,+ preferredKey?: string,+) {+ const existing = await db+ .select({ slug: projectTable.slug })+ .from(projectTable)+ .where(eq(projectTable.workspaceId, workspaceId));++ const project = await createWithUniqueKey(+ name,+ existing.map((row) => row.slug),+ (key) => createProject(workspaceId, name, "Layout", key, userId),+ { preferredKey },+ );+ if (!project) throw new Error("Failed to create the imported project");+ return project;+}diff --git a/apps/api/src/import/writer/create-with-unique-key.test.ts b/apps/api/src/import/writer/create-with-unique-key.test.tsnew file mode 100644index 000000000..9f143a61e--- /dev/null+++ b/apps/api/src/import/writer/create-with-unique-key.test.ts@@ -0,0 +1,108 @@+import { HTTPException } from "hono/http-exception";+import { describe, expect, it, vi } from "vite-plus/test";+import { createWithUniqueKey } from "./create-with-unique-key";++describe("createWithUniqueKey", () => {+ it("derives a key from the name and avoids existing keys in any case", async () => {+ const create = vi.fn(async (key: string) => key);++ await expect(+ createWithUniqueKey("Marketing Website Redesign", ["mwr"], create),+ ).resolves.toBe("MWR-2");+ expect(create).toHaveBeenCalledTimes(1);+ });++ it("retries with the next key when another request took it first", async () => {+ const create = vi.fn(async (key: string) => {+ if (key !== "ENGINE-3") {+ throw new HTTPException(409, { message: "taken" });+ }+ return key;+ });++ await expect(createWithUniqueKey("Engineering", [], create)).resolves.toBe(+ "ENGINE-3",+ );+ expect(create.mock.calls.map(([key]) => key)).toEqual([+ "ENGINEER",+ "ENGINE-2",+ "ENGINE-3",+ ]);+ });++ it("gives up after a few conflicts", async () => {+ const create = vi.fn<(key: string) => Promise<string>>(async () => {+ throw new HTTPException(409, { message: "taken" });+ });++ await expect(+ createWithUniqueKey("Ops", [], create, { attempts: 3 }),+ ).rejects.toThrow("taken");+ expect(create.mock.calls.map(([key]) => key)).toEqual([+ "OPS",+ "OPS-2",+ "OPS-3",+ ]);+ });++ it("uses the source key when it is free", async () => {+ const create = vi.fn(async (key: string) => key);++ await expect(+ createWithUniqueKey("Website", ["ENG"], create, { preferredKey: "web" }),+ ).resolves.toBe("WEB");+ });++ it("suffixes the source key when the workspace already uses it", async () => {+ const create = vi.fn(async (key: string) => key);++ await expect(+ createWithUniqueKey("Website", ["web", "WEB-2"], create, {+ preferredKey: "WEB",+ }),+ ).resolves.toBe("WEB-3");+ });++ it("keeps a long source key whole when suffixing it", async () => {+ const create = vi.fn(async (key: string) => key);++ await expect(+ createWithUniqueKey("Marketing", ["MARKETING"], create, {+ preferredKey: "MARKETING",+ }),+ ).resolves.toBe("MARKETING-2");+ });++ it("retries the source key on conflicts like a derived one", async () => {+ const create = vi.fn(async (key: string) => {+ if (key === "ENG") throw new HTTPException(409, { message: "taken" });+ return key;+ });++ await expect(+ createWithUniqueKey("Engineering", [], create, { preferredKey: "ENG" }),+ ).resolves.toBe("ENG-2");+ expect(create.mock.calls.map(([key]) => key)).toEqual(["ENG", "ENG-2"]);+ });++ it("falls back to the name when the source key has nothing usable", async () => {+ const create = vi.fn(async (key: string) => key);++ await expect(+ createWithUniqueKey("Marketing Website Redesign", [], create, {+ preferredKey: " -_ ",+ }),+ ).resolves.toBe("MWR");+ });++ it("does not retry other failures", async () => {+ const create = vi.fn(async () => {+ throw new Error("database down");+ });++ await expect(createWithUniqueKey("Ops", [], create)).rejects.toThrow(+ "database down",+ );+ expect(create).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/api/src/import/writer/create-with-unique-key.ts b/apps/api/src/import/writer/create-with-unique-key.tsnew file mode 100644index 000000000..99aa1de46--- /dev/null+++ b/apps/api/src/import/writer/create-with-unique-key.ts@@ -0,0 +1,44 @@+import {+ SOURCE_PROJECT_KEY_MAX,+ sanitizeProjectKey,+ toProjectKey,+ uniqueKey,+} from "@kaneo/importers";+import { HTTPException } from "hono/http-exception";++export const MAX_PROJECT_KEY_ATTEMPTS = 5;++export type CreateWithUniqueKeyOptions = {+ preferredKey?: string;+ attempts?: number;+};++function normalizeKey(key: string) {+ return key.normalize("NFKC").toUpperCase();+}++export async function createWithUniqueKey<T>(+ name: string,+ existingKeys: Iterable<string>,+ create: (key: string) => Promise<T>,+ {+ preferredKey,+ attempts = MAX_PROJECT_KEY_ATTEMPTS,+ }: CreateWithUniqueKeyOptions = {},+): Promise<T> {+ const taken = new Set([...existingKeys].map(normalizeKey));+ const sourceKey = sanitizeProjectKey(preferredKey);+ const candidate = sourceKey ?? toProjectKey(name);+ const maxLength = sourceKey ? SOURCE_PROJECT_KEY_MAX : undefined;++ for (let attempt = 1; ; attempt++) {+ const key = uniqueKey(candidate, taken, maxLength);+ try {+ return await create(key);+ } catch (error) {+ const conflict = error instanceof HTTPException && error.status === 409;+ if (!conflict || attempt >= attempts) throw error;+ taken.add(normalizeKey(key));+ }+ }+}diff --git a/apps/api/src/import/writer/load-assignable-members.ts b/apps/api/src/import/writer/load-assignable-members.tsnew file mode 100644index 000000000..172535f82--- /dev/null+++ b/apps/api/src/import/writer/load-assignable-members.ts@@ -0,0 +1,26 @@+import { eq } from "drizzle-orm";+import type db from "../../database";+import { userTable, workspaceUserTable } from "../../database/schema";+import { filterUsersWithProjectAccess } from "../../project-access/filter-users-with-project-access";+import type { AssignableMember } from "./match-assignees";++type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];++export async function loadAssignableMembers(+ tx: Transaction,+ workspaceId: string,+ projectId: string,+): Promise<AssignableMember[]> {+ const members = await tx+ .select({ id: userTable.id, name: userTable.name, email: userTable.email })+ .from(workspaceUserTable)+ .innerJoin(userTable, eq(workspaceUserTable.userId, userTable.id))+ .where(eq(workspaceUserTable.workspaceId, workspaceId));++ const withAccess = await filterUsersWithProjectAccess(+ members.map((member) => member.id),+ projectId,+ tx,+ );+ return members.filter((member) => withAccess.has(member.id));+}diff --git a/apps/api/src/import/writer/match-assignees.test.ts b/apps/api/src/import/writer/match-assignees.test.tsnew file mode 100644index 000000000..0c76328ff--- /dev/null+++ b/apps/api/src/import/writer/match-assignees.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from "vite-plus/test";+import {+ createAssigneeMatcher,+ unmatchedAssigneeWarning,+} from "./match-assignees";++const members = [+ { id: "u-ana", name: "Ana Lima", email: "[email protected]" },+ { id: "u-bo", name: "Bo", email: "[email protected]" },+ { id: "u-sam-1", name: "Sam", email: "[email protected]" },+ { id: "u-sam-2", name: "sam", email: "[email protected]" },+];++describe("createAssigneeMatcher", () => {+ it("matches emails case-insensitively", () => {+ const matcher = createAssigneeMatcher(members);+ expect(matcher.match({ email: " [email protected] ", name: "A" })).toBe(+ "u-ana",+ );+ expect(matcher.warning()).toBeNull();+ });++ it("trusts a given email over the name", () => {+ const matcher = createAssigneeMatcher(members);+ expect(+ matcher.match({ email: "[email protected]", name: "Ana Lima" }),+ ).toBe(null);+ });++ it("falls back to a unique, exact name when the source hides emails", () => {+ const matcher = createAssigneeMatcher(members);+ expect(matcher.match({ name: " ana lima " })).toBe("u-ana");+ expect(matcher.match({ name: "Ana" })).toBeNull();+ expect(matcher.match({ name: "Sam" })).toBeNull();+ });++ it("ignores tasks without an assignee", () => {+ const matcher = createAssigneeMatcher(members);+ expect(matcher.match(undefined)).toBeNull();+ expect(matcher.match({ name: " " })).toBeNull();+ expect(matcher.warning()).toBeNull();+ });++ it("summarises the people it could not match", () => {+ const matcher = createAssigneeMatcher(members);+ matcher.match({ name: "Cy", email: "[email protected]" });+ matcher.match({ name: "Cy", email: "[email protected]" });+ matcher.match({ email: "[email protected]" });++ expect(matcher.warning()).toBe(+ "3 tasks were assigned to people who are not members of this workspace (Cy, [email protected]). Invite them, then assign the tasks.",+ );+ });+});++describe("unmatchedAssigneeWarning", () => {+ it("uses the singular for one task", () => {+ expect(unmatchedAssigneeWarning(1, ["Ana"])).toBe(+ "1 task was assigned to someone who is not a member of this workspace (Ana). Invite them, then assign the task.",+ );+ });++ it("lists at most five names", () => {+ expect(+ unmatchedAssigneeWarning(7, ["A", "B", "C", "D", "E", "F", "G"]),+ ).toBe(+ "7 tasks were assigned to people who are not members of this workspace (A, B, C, D, E, and 2 more). Invite them, then assign the tasks.",+ );+ });+});diff --git a/apps/api/src/import/writer/match-assignees.ts b/apps/api/src/import/writer/match-assignees.tsnew file mode 100644index 000000000..0a17ce37d--- /dev/null+++ b/apps/api/src/import/writer/match-assignees.ts@@ -0,0 +1,78 @@+import type { ImportedPerson } from "@kaneo/importers";++export type AssignableMember = { id: string; name: string; email: string };++export type AssigneeMatcher = {+ match(person: ImportedPerson | undefined): string | null;+ warning(): string | null;+};++const LISTED_NAMES = 5;++function normalize(value: string | null | undefined) {+ return value?.normalize("NFKC").trim().toLowerCase() ?? "";+}++function displayName(person: ImportedPerson) {+ return person.name?.trim() || person.email?.trim() || "someone";+}++function listNames(names: string[]) {+ const listed = names.slice(0, LISTED_NAMES).join(", ");+ const rest = names.length - LISTED_NAMES;+ return rest > 0 ? `${listed}, and ${rest} more` : listed;+}++export function unmatchedAssigneeWarning(+ taskCount: number,+ names: string[],+): string | null {+ if (taskCount === 0) return null;+ const tasks = taskCount === 1 ? "1 task was" : `${taskCount} tasks were`;+ const people =+ names.length === 1+ ? "someone who is not a member"+ : "people who are not members";+ const assign = taskCount === 1 ? "the task" : "the tasks";+ return `${tasks} assigned to ${people} of this workspace (${listNames(names)}). Invite them, then assign ${assign}.`;+}++export function createAssigneeMatcher(+ members: readonly AssignableMember[],+): AssigneeMatcher {+ const byEmail = new Map<string, string>();+ const byName = new Map<string, string | null>();+ for (const member of members) {+ const email = normalize(member.email);+ if (email) byEmail.set(email, member.id);+ const name = normalize(member.name);+ if (name) byName.set(name, byName.has(name) ? null : member.id);+ }++ let unmatchedTasks = 0;+ const unmatchedNames = new Map<string, string>();++ function find(person: ImportedPerson) {+ const email = normalize(person.email);+ if (email) return byEmail.get(email) ?? null;+ const name = normalize(person.name);+ return name ? (byName.get(name) ?? null) : null;+ }++ return {+ match(person) {+ if (!person || (!normalize(person.email) && !normalize(person.name))) {+ return null;+ }+ const userId = find(person);+ if (!userId) {+ unmatchedTasks++;+ const name = displayName(person);+ unmatchedNames.set(name.toLowerCase(), name);+ }+ return userId;+ },+ warning: () =>+ unmatchedAssigneeWarning(unmatchedTasks, [...unmatchedNames.values()]),+ };+}diff --git a/apps/api/src/import/writer/plan-import-columns.test.ts b/apps/api/src/import/writer/plan-import-columns.test.tsnew file mode 100644index 000000000..675fcd86e--- /dev/null+++ b/apps/api/src/import/writer/plan-import-columns.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from "vite-plus/test";+import { planImportColumns } from "./plan-import-columns";++function column(key: string, name: string, isFinal = false) {+ return { key, name, isFinal };+}++describe("planImportColumns", () => {+ it("keeps names, order and the final flag", () => {+ expect(+ planImportColumns([+ column("a", "Backlog"),+ column("b", " In Progress "),+ column("c", "Shipped", true),+ ]),+ ).toEqual({+ columns: [+ {+ key: "a",+ name: "Backlog",+ slug: "backlog",+ position: 0,+ isFinal: false,+ },+ {+ key: "b",+ name: "In Progress",+ slug: "in-progress",+ position: 1,+ isFinal: false,+ },+ {+ key: "c",+ name: "Shipped",+ slug: "shipped",+ position: 2,+ isFinal: true,+ },+ ],+ warnings: [],+ });+ });++ it("names columns without letters or numbers Untitled", () => {+ const plan = planImportColumns([column("a", "???"), column("b", "")]);++ expect(plan.columns.map(({ name, slug }) => ({ name, slug }))).toEqual([+ { name: "Untitled", slug: "untitled" },+ { name: "Untitled 2", slug: "untitled-2" },+ ]);+ expect(plan.warnings).toEqual([+ 'Renamed a column to avoid conflicts: "???" to "Untitled".',+ ]);+ });++ it("moves reserved virtual statuses out of the way", () => {+ const plan = planImportColumns([+ column("a", "Planned"),+ column("b", "archived"),+ ]);++ expect(plan.columns.map(({ name, slug }) => ({ name, slug }))).toEqual([+ { name: "Planned list", slug: "planned-list" },+ { name: "archived list", slug: "archived-list" },+ ]);+ });++ it("numbers duplicate slugs", () => {+ const plan = planImportColumns([+ column("a", "Done"),+ column("b", "done"),+ column("c", "DONE!"),+ column("d", "In-Progress"),+ column("e", "In Progress"),+ ]);++ expect(plan.columns.map(({ name }) => name)).toEqual([+ "Done",+ "done 2",+ "DONE! 3",+ "In-Progress",+ "In Progress 2",+ ]);+ expect(new Set(plan.columns.map(({ slug }) => slug)).size).toBe(5);+ expect(plan.warnings).toEqual([+ 'Renamed 3 columns to avoid conflicts: "done" to "done 2", "DONE!" to "DONE! 3", "In Progress" to "In Progress 2".',+ ]);+ });++ it("returns nothing for a source without columns", () => {+ expect(planImportColumns([])).toEqual({ columns: [], warnings: [] });+ });+});diff --git a/apps/api/src/import/writer/plan-import-columns.ts b/apps/api/src/import/writer/plan-import-columns.tsnew file mode 100644index 000000000..c515ae0bf--- /dev/null+++ b/apps/api/src/import/writer/plan-import-columns.ts@@ -0,0 +1,68 @@+import type { ImportedColumn } from "@kaneo/importers";+import { toSlug } from "../../column/controllers/create-column";+import { VIRTUAL_STATUSES } from "../../task/validate-task-fields";++export type PlannedImportColumn = {+ key: string;+ name: string;+ slug: string;+ position: number;+ isFinal: boolean;+};++export type ImportColumnPlan = {+ columns: PlannedImportColumn[];+ warnings: string[];+};++const UNTITLED_COLUMN = "Untitled";++function isReserved(slug: string) {+ return (VIRTUAL_STATUSES as readonly string[]).includes(slug);+}++function baseName(original: string) {+ const name = toSlug(original) ? original : UNTITLED_COLUMN;+ return isReserved(toSlug(name)) ? `${name} list` : name;+}++export function planImportColumns(+ columns: readonly ImportedColumn[],+): ImportColumnPlan {+ const usedSlugs = new Set<string>();+ const planned: PlannedImportColumn[] = [];+ const renamed: string[] = [];++ for (const column of columns) {+ const original = column.name.trim();+ const base = baseName(original);+ let name = base;+ for (let suffix = 2; usedSlugs.has(toSlug(name)); suffix++) {+ name = `${base} ${suffix}`;+ }++ const slug = toSlug(name);+ usedSlugs.add(slug);+ if (original && name !== original) {+ renamed.push(`"${original}" to "${name}"`);+ }++ planned.push({+ key: column.key,+ name,+ slug,+ position: planned.length,+ isFinal: column.isFinal,+ });+ }++ return {+ columns: planned,+ warnings:+ renamed.length > 0+ ? [+ `Renamed ${renamed.length === 1 ? "a column" : `${renamed.length} columns`} to avoid conflicts: ${renamed.join(", ")}.`,+ ]+ : [],+ };+}diff --git a/apps/api/src/import/writer/plan-import-relations.test.ts b/apps/api/src/import/writer/plan-import-relations.test.tsnew file mode 100644index 000000000..2b4e561e4--- /dev/null+++ b/apps/api/src/import/writer/plan-import-relations.test.ts@@ -0,0 +1,65 @@+import type { ImportedRelation } from "@kaneo/importers";+import { describe, expect, it } from "vite-plus/test";+import { planImportRelations } from "./plan-import-relations";++const taskIds = new Map([+ ["a", "task-a"],+ ["b", "task-b"],+ ["c", "task-c"],+]);++describe("planImportRelations", () => {+ it("maps keys to the new task ids", () => {+ expect(+ planImportRelations(+ [+ { sourceKey: "a", targetKey: "b", type: "subtask" },+ { sourceKey: "b", targetKey: "c", type: "blocks" },+ ],+ taskIds,+ ),+ ).toEqual([+ {+ sourceTaskId: "task-a",+ targetTaskId: "task-b",+ relationType: "subtask",+ },+ {+ sourceTaskId: "task-b",+ targetTaskId: "task-c",+ relationType: "blocks",+ },+ ]);+ });++ it("skips self relations, unknown tasks and duplicates in either direction", () => {+ expect(+ planImportRelations(+ [+ { sourceKey: "a", targetKey: "a", type: "related" },+ { sourceKey: "a", targetKey: "missing", type: "related" },+ { sourceKey: "a", targetKey: "b", type: "related" },+ { sourceKey: "b", targetKey: "a", type: "related" },+ { sourceKey: "a", targetKey: "b", type: "blocks" },+ {+ sourceKey: "a",+ targetKey: "b",+ type: "duplicates",+ } as unknown as ImportedRelation,+ ],+ taskIds,+ ),+ ).toEqual([+ {+ sourceTaskId: "task-a",+ targetTaskId: "task-b",+ relationType: "related",+ },+ {+ sourceTaskId: "task-a",+ targetTaskId: "task-b",+ relationType: "blocks",+ },+ ]);+ });+});diff --git a/apps/api/src/import/writer/plan-import-relations.ts b/apps/api/src/import/writer/plan-import-relations.tsnew file mode 100644index 000000000..e66330d8d--- /dev/null+++ b/apps/api/src/import/writer/plan-import-relations.ts@@ -0,0 +1,35 @@+import type { ImportedRelation } from "@kaneo/importers";++export type PlannedImportRelation = {+ sourceTaskId: string;+ targetTaskId: string;+ relationType: ImportedRelation["type"];+};++const RELATION_TYPES = new Set<string>(["subtask", "blocks", "related"]);++export function planImportRelations(+ relations: readonly ImportedRelation[],+ taskIds: ReadonlyMap<string, string>,+): PlannedImportRelation[] {+ const seen = new Set<string>();+ const planned: PlannedImportRelation[] = [];++ for (const relation of relations) {+ if (!RELATION_TYPES.has(relation.type)) continue;+ const sourceTaskId = taskIds.get(relation.sourceKey);+ const targetTaskId = taskIds.get(relation.targetKey);+ if (!sourceTaskId || !targetTaskId || sourceTaskId === targetTaskId) {+ continue;+ }++ const pair = [sourceTaskId, targetTaskId].sort().join(":");+ const identity = `${relation.type}:${pair}`;+ if (seen.has(identity)) continue;+ seen.add(identity);++ planned.push({ sourceTaskId, targetTaskId, relationType: relation.type });+ }++ return planned;+}diff --git a/apps/api/src/import/writer/plan-import-tasks.test.ts b/apps/api/src/import/writer/plan-import-tasks.test.tsnew file mode 100644index 000000000..b70c060b7--- /dev/null+++ b/apps/api/src/import/writer/plan-import-tasks.test.ts@@ -0,0 +1,150 @@+import type { ImportedTask } from "@kaneo/importers";+import { describe, expect, it } from "vite-plus/test";+import { parseImportDate, planImportTasks } from "./plan-import-tasks";++const now = new Date("2026-10-11T12:00:00.000Z");++function task(+ key: string,+ overrides: Partial<ImportedTask> = {},+): ImportedTask {+ return {+ key,+ columnKey: "todo",+ title: `Task ${key}`,+ description: "",+ priority: "medium",+ labelKeys: [],+ comments: [],+ ...overrides,+ };+}++function plan(tasks: ImportedTask[], numbers = tasks.map((_, i) => 41 + i)) {+ let id = 0;+ return planImportTasks({+ tasks,+ columns: new Map([+ ["todo", { id: "col-todo", slug: "to-do" }],+ ["done", { id: "col-done", slug: "done" }],+ ]),+ fallbackColumn: { id: "col-todo", slug: "to-do" },+ numbers,+ now,+ newId: () => `task-${++id}`,+ assign: (person) => (person?.email === "[email protected]" ? "u-ana" : null),+ });+}++describe("planImportTasks", () => {+ it("numbers tasks as given and positions them per column or status", () => {+ const planned = plan([+ task("a"),+ task("b", { columnKey: "done" }),+ task("c"),+ task("d", { columnKey: null }),+ task("e", { archived: true, columnKey: "done" }),+ task("f", { columnKey: null }),+ ]);++ expect(+ planned.map(({ key, number, status, columnId, position }) => ({+ key,+ number,+ status,+ columnId,+ position,+ })),+ ).toEqual([+ {+ key: "a",+ number: 41,+ status: "to-do",+ columnId: "col-todo",+ position: 1,+ },+ {+ key: "b",+ number: 42,+ status: "done",+ columnId: "col-done",+ position: 1,+ },+ {+ key: "c",+ number: 43,+ status: "to-do",+ columnId: "col-todo",+ position: 2,+ },+ { key: "d", number: 44, status: "planned", columnId: null, position: 1 },+ { key: "e", number: 45, status: "archived", columnId: null, position: 1 },+ { key: "f", number: 46, status: "planned", columnId: null, position: 2 },+ ]);+ });++ it("keeps the given numbers apart from board order", () => {+ const planned = plan(+ [task("a"), task("b"), task("c", { columnKey: "done" })],+ [7, 3, 12],+ );++ expect(+ planned.map(({ key, number, position }) => ({ key, number, position })),+ ).toEqual([+ { key: "a", number: 7, position: 1 },+ { key: "b", number: 3, position: 2 },+ { key: "c", number: 12, position: 1 },+ ]);+ });++ it("refuses to plan a task without a number", () => {+ expect(() => plan([task("a"), task("b")], [1])).toThrow(+ "Every imported task needs a number",+ );+ });++ it("puts tasks from an unknown column in the fallback column", () => {+ expect(plan([task("a", { columnKey: "gone" })])[0]).toMatchObject({+ status: "to-do",+ columnId: "col-todo",+ });+ });++ it("cleans titles, priorities and dates", () => {+ const [planned] = plan([+ task("a", {+ title: " ",+ priority: "critical" as ImportedTask["priority"],+ startDate: "not a date",+ dueDate: "2026-11-01",+ createdAt: "2021-03-04T05:06:07.000Z",+ assignee: { email: "[email protected]" },+ }),+ ]);++ expect(planned).toMatchObject({+ id: "task-1",+ title: "Untitled task",+ priority: "no-priority",+ startDate: null,+ dueDate: new Date("2026-11-01T00:00:00.000Z"),+ createdAt: new Date("2021-03-04T05:06:07.000Z"),+ userId: "u-ana",+ });+ });++ it("dates tasks without a source date now", () => {+ expect(plan([task("a")])[0]?.createdAt).toEqual(now);+ });+});++describe("parseImportDate", () => {+ it("rejects dates Postgres cannot store", () => {+ expect(parseImportDate("-010000-01-01T00:00:00Z")).toBeNull();+ expect(parseImportDate(undefined)).toBeNull();+ expect(parseImportDate("2024-02-29")).toEqual(+ new Date("2024-02-29T00:00:00.000Z"),+ );+ });+});diff --git a/apps/api/src/import/writer/plan-import-tasks.ts b/apps/api/src/import/writer/plan-import-tasks.tsnew file mode 100644index 000000000..ce535af8f--- /dev/null+++ b/apps/api/src/import/writer/plan-import-tasks.ts@@ -0,0 +1,108 @@+import type {+ ImportedComment,+ ImportedPerson,+ ImportedTask,+} from "@kaneo/importers";+import { VALID_PRIORITIES } from "../../task/validate-task-fields";++export type BoardColumn = { id: string; slug: string };++export type PlannedImportTask = {+ id: string;+ key: string;+ number: number;+ title: string;+ description: string;+ status: string;+ columnId: string | null;+ position: number;+ priority: string;+ startDate: Date | null;+ dueDate: Date | null;+ createdAt: Date;+ userId: string | null;+ labelKeys: readonly string[];+ comments: readonly ImportedComment[];+};++type PlanImportTasksInput = {+ tasks: readonly ImportedTask[];+ columns: ReadonlyMap<string, BoardColumn>;+ fallbackColumn: BoardColumn | null;+ numbers: readonly number[];+ now: Date;+ newId: () => string;+ assign: (person: ImportedPerson | undefined) => string | null;+};++const UNTITLED_TASK = "Untitled task";+const MIN_YEAR = 1;+const MAX_YEAR = 9999;++export function parseImportDate(value: string | undefined): Date | null {+ if (!value) return null;+ const time = Date.parse(value);+ if (Number.isNaN(time)) return null;+ const date = new Date(time);+ const year = date.getUTCFullYear();+ return year >= MIN_YEAR && year <= MAX_YEAR ? date : null;+}++export function importPriority(priority: string): string {+ return (VALID_PRIORITIES as readonly string[]).includes(priority)+ ? priority+ : "no-priority";+}++function placeTask(+ task: ImportedTask,+ columns: ReadonlyMap<string, BoardColumn>,+ fallbackColumn: BoardColumn | null,+): { status: string; columnId: string | null } {+ if (task.archived) return { status: "archived", columnId: null };+ if (task.columnKey === null) return { status: "planned", columnId: null };+ const column = columns.get(task.columnKey) ?? fallbackColumn;+ return column+ ? { status: column.slug, columnId: column.id }+ : { status: "planned", columnId: null };+}++export function planImportTasks({+ tasks,+ columns,+ fallbackColumn,+ numbers,+ now,+ newId,+ assign,+}: PlanImportTasksInput): PlannedImportTask[] {+ const positions = new Map<string, number>();++ return tasks.map((task, index) => {+ const number = numbers[index];+ if (number === undefined) {+ throw new Error("Every imported task needs a number");+ }+ const placement = placeTask(task, columns, fallbackColumn);+ const bucket = placement.columnId ?? `status:${placement.status}`;+ const position = (positions.get(bucket) ?? 0) + 1;+ positions.set(bucket, position);++ return {+ id: newId(),+ key: task.key,+ number,+ title: task.title.trim() || UNTITLED_TASK,+ description: task.description ?? "",+ ...placement,+ position,+ priority: importPriority(task.priority),+ startDate: parseImportDate(task.startDate),+ dueDate: parseImportDate(task.dueDate),+ createdAt: parseImportDate(task.createdAt) ?? now,+ userId: assign(task.assignee),+ labelKeys: task.labelKeys,+ comments: task.comments,+ };+ });+}diff --git a/apps/api/src/import/writer/write-import-columns.ts b/apps/api/src/import/writer/write-import-columns.tsnew file mode 100644index 000000000..8499a5d4d--- /dev/null+++ b/apps/api/src/import/writer/write-import-columns.ts@@ -0,0 +1,61 @@+import { createId } from "@paralleldrive/cuid2";+import { asc, eq } from "drizzle-orm";+import type db from "../../database";+import { columnTable } from "../../database/schema";+import { chunk } from "./chunk";+import type { ImportColumnPlan } from "./plan-import-columns";+import type { BoardColumn } from "./plan-import-tasks";++type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];++export type ImportBoard = {+ byKey: Map<string, BoardColumn>;+ fallback: BoardColumn | null;+ count: number;+};++export async function writeImportColumns(+ tx: Transaction,+ projectId: string,+ plan: ImportColumnPlan,+): Promise<ImportBoard> {+ if (plan.columns.length === 0) {+ const defaults = await tx+ .select({ id: columnTable.id, slug: columnTable.slug })+ .from(columnTable)+ .where(eq(columnTable.projectId, projectId))+ .orderBy(asc(columnTable.position));+ return {+ byKey: new Map(),+ fallback: defaults[0] ?? null,+ count: defaults.length,+ };+ }++ await tx.delete(columnTable).where(eq(columnTable.projectId, projectId));++ const planned = plan.columns.map((column) => ({+ key: column.key,+ row: {+ id: createId(),+ projectId,+ name: column.name,+ slug: column.slug,+ position: column.position,+ isFinal: column.isFinal,+ },+ }));+ for (const batch of chunk(planned.map(({ row }) => row))) {+ await tx.insert(columnTable).values(batch);+ }++ const byKey = new Map(+ planned.map(({ key, row }) => [key, { id: row.id, slug: row.slug }]),+ );+ const first = planned[0]?.row;+ return {+ byKey,+ fallback: first ? { id: first.id, slug: first.slug } : null,+ count: planned.length,+ };+}diff --git a/apps/api/src/import/writer/write-import-comments.ts b/apps/api/src/import/writer/write-import-comments.tsnew file mode 100644index 000000000..6630180ec--- /dev/null+++ b/apps/api/src/import/writer/write-import-comments.ts@@ -0,0 +1,49 @@+import type { ImportedComment, ImportSourceId } from "@kaneo/importers";+import type db from "../../database";+import { activityTable } from "../../database/schema";+import { chunk } from "./chunk";+import { parseImportDate } from "./plan-import-tasks";++type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];++type TaskComments = { id: string; comments: readonly ImportedComment[] };++const MAX_EXTERNAL_NAME_LENGTH = 120;++export async function writeImportComments(+ tx: Transaction,+ {+ tasks,+ importedBy,+ source,+ now,+ }: {+ tasks: readonly TaskComments[];+ importedBy: string;+ source: ImportSourceId;+ now: Date;+ },+): Promise<number> {+ const rows = tasks.flatMap(({ id: taskId, comments }) =>+ comments+ .filter((comment) => comment.body.trim())+ .map((comment) => ({+ taskId,+ type: "comment",+ userId: importedBy,+ content: comment.body,+ externalUserName: (comment.author.name?.trim() || "Unknown user").slice(+ 0,+ MAX_EXTERNAL_NAME_LENGTH,+ ),+ externalSource: source,+ createdAt: parseImportDate(comment.createdAt) ?? now,+ })),+ );++ for (const batch of chunk(rows)) {+ await tx.insert(activityTable).values(batch);+ }++ return rows.length;+}diff --git a/apps/api/src/import/writer/write-import-labels.ts b/apps/api/src/import/writer/write-import-labels.tsnew file mode 100644index 000000000..b9b3115a2--- /dev/null+++ b/apps/api/src/import/writer/write-import-labels.ts@@ -0,0 +1,98 @@+import type { ImportedLabel } from "@kaneo/importers";+import { and, eq, inArray, isNull, sql } from "drizzle-orm";+import type db from "../../database";+import { labelTable } from "../../database/schema";+import { chunk } from "./chunk";++type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];++type TaskLabelKeys = { id: string; labelKeys: readonly string[] };++const DEFAULT_LABEL_COLOR = "gray";+const MAX_COLOR_LENGTH = 64;++function importColor(color: string | undefined) {+ const trimmed = color?.trim();+ return trimmed && trimmed.length <= MAX_COLOR_LENGTH+ ? trimmed+ : DEFAULT_LABEL_COLOR;+}++export async function writeImportLabels(+ tx: Transaction,+ workspaceId: string,+ labels: readonly ImportedLabel[],+ tasks: readonly TaskLabelKeys[],+): Promise<number> {+ const byKey = new Map(labels.map((label) => [label.key, label]));+ const colors = new Map<string, string>();+ const taskLabels: { taskId: string; name: string }[] = [];++ for (const task of tasks) {+ const names = new Set<string>();+ for (const key of task.labelKeys) {+ const label = byKey.get(key);+ const name = label?.name.trim();+ if (!label || !name) continue;+ names.add(name);+ if (!colors.has(name)) colors.set(name, importColor(label.color));+ }+ for (const name of names) taskLabels.push({ taskId: task.id, name });+ }++ const names = [...colors.keys()];+ if (names.length === 0) return 0;++ for (const batch of chunk(names)) {+ await tx+ .insert(labelTable)+ .values(+ batch.map((name) => ({+ name,+ color: colors.get(name) ?? DEFAULT_LABEL_COLOR,+ taskId: null,+ workspaceId,+ })),+ )+ .onConflictDoNothing({+ target: [labelTable.workspaceId, labelTable.name],+ where: sql`${labelTable.taskId} is null`,+ });+ }++ const definitionColors = new Map<string, string>();+ for (const batch of chunk(names)) {+ const definitions = await tx+ .select({ name: labelTable.name, color: labelTable.color })+ .from(labelTable)+ .where(+ and(+ eq(labelTable.workspaceId, workspaceId),+ isNull(labelTable.taskId),+ inArray(labelTable.name, batch),+ ),+ );+ for (const definition of definitions) {+ definitionColors.set(definition.name, definition.color);+ }+ }++ for (const batch of chunk(taskLabels)) {+ await tx+ .insert(labelTable)+ .values(+ batch.map(({ taskId, name }) => ({+ name,+ color:+ definitionColors.get(name) ??+ colors.get(name) ??+ DEFAULT_LABEL_COLOR,+ taskId,+ workspaceId,+ })),+ )+ .onConflictDoNothing({ target: [labelTable.taskId, labelTable.name] });+ }++ return names.length;+}diff --git a/apps/api/src/import/writer/write-import-relations.ts b/apps/api/src/import/writer/write-import-relations.tsnew file mode 100644index 000000000..b08545354--- /dev/null+++ b/apps/api/src/import/writer/write-import-relations.ts@@ -0,0 +1,16 @@+import type db from "../../database";+import { taskRelationTable } from "../../database/schema";+import { chunk } from "./chunk";+import type { PlannedImportRelation } from "./plan-import-relations";++type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];++export async function writeImportRelations(+ tx: Transaction,+ relations: readonly PlannedImportRelation[],+): Promise<number> {+ for (const batch of chunk(relations)) {+ await tx.insert(taskRelationTable).values(batch);+ }+ return relations.length;+}diff --git a/apps/api/src/import/writer/write-import-tasks.ts b/apps/api/src/import/writer/write-import-tasks.tsnew file mode 100644index 000000000..191a94270--- /dev/null+++ b/apps/api/src/import/writer/write-import-tasks.ts@@ -0,0 +1,44 @@+import type db from "../../database";+import { activityTable, taskTable } from "../../database/schema";+import { chunk } from "./chunk";+import type { PlannedImportTask } from "./plan-import-tasks";++type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];++export async function writeImportTasks(+ tx: Transaction,+ projectId: string,+ importedBy: string,+ tasks: readonly PlannedImportTask[],+) {+ for (const batch of chunk(tasks)) {+ await tx.insert(taskTable).values(+ batch.map((task) => ({+ id: task.id,+ projectId,+ number: task.number,+ title: task.title,+ description: task.description,+ status: task.status,+ columnId: task.columnId,+ position: task.position,+ priority: task.priority,+ startDate: task.startDate,+ dueDate: task.dueDate,+ createdAt: task.createdAt,+ userId: task.userId,+ })),+ );++ await tx.insert(activityTable).values(+ batch.map((task) => ({+ taskId: task.id,+ type: "created",+ userId: importedBy,+ content: null,+ eventData: {},+ createdAt: task.createdAt,+ })),+ );+ }+}diff --git a/apps/api/src/import/writer/write-project-content.ts b/apps/api/src/import/writer/write-project-content.tsnew file mode 100644index 000000000..ad01c86a5--- /dev/null+++ b/apps/api/src/import/writer/write-project-content.ts@@ -0,0 +1,116 @@+import type { ImportedProject, ImportSourceId } from "@kaneo/importers";+import { createId } from "@paralleldrive/cuid2";+import { eq, sql } from "drizzle-orm";+import type db from "../../database";+import { projectTable } from "../../database/schema";+import type { ImportCounts } from "../import-run-project";+import { assignImportTaskNumbers } from "./assign-import-task-numbers";+import { loadAssignableMembers } from "./load-assignable-members";+import { createAssigneeMatcher } from "./match-assignees";+import { planImportColumns } from "./plan-import-columns";+import { planImportRelations } from "./plan-import-relations";+import { planImportTasks } from "./plan-import-tasks";+import { writeImportColumns } from "./write-import-columns";+import { writeImportComments } from "./write-import-comments";+import { writeImportLabels } from "./write-import-labels";+import { writeImportRelations } from "./write-import-relations";+import { writeImportTasks } from "./write-import-tasks";++type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];++export type ProjectContentInput = {+ projectId: string;+ workspaceId: string;+ userId: string;+ source: ImportSourceId;+ project: ImportedProject;+ includeComments: boolean;+};++export async function writeProjectContent(+ tx: Transaction,+ {+ projectId,+ workspaceId,+ userId,+ source,+ project,+ includeComments,+ }: ProjectContentInput,+): Promise<{ counts: ImportCounts; warnings: string[] }> {+ const now = new Date();+ const description = project.description?.trim();+ if (description) {+ await tx+ .update(projectTable)+ .set({ description })+ .where(eq(projectTable.id, projectId));+ }++ const columnPlan = planImportColumns(project.columns);+ const board = await writeImportColumns(tx, projectId, columnPlan);+ const assignees = createAssigneeMatcher(+ await loadAssignableMembers(tx, workspaceId, projectId),+ );++ const { numbers, lastNumber } = assignImportTaskNumbers(project.tasks);+ if (lastNumber > 0) {+ await tx+ .update(projectTable)+ .set({+ lastTaskNumber: sql`GREATEST(${projectTable.lastTaskNumber}, ${lastNumber})`,+ })+ .where(eq(projectTable.id, projectId));+ }+ const tasks = planImportTasks({+ tasks: project.tasks,+ columns: board.byKey,+ fallbackColumn: board.fallback,+ numbers,+ now,+ newId: createId,+ assign: assignees.match,+ });+ await writeImportTasks(tx, projectId, userId, tasks);++ const labels = await writeImportLabels(+ tx,+ workspaceId,+ project.labels,+ tasks,+ );++ const comments = includeComments+ ? await writeImportComments(tx, {+ tasks,+ importedBy: userId,+ source,+ now,+ })+ : 0;++ const relations = await writeImportRelations(+ tx,+ planImportRelations(+ project.relations,+ new Map(tasks.map((task) => [task.key, task.id])),+ ),+ );++ const unmatched = assignees.warning();+ return {+ counts: {+ columns: board.count,+ tasks: tasks.length,+ labels,+ comments,+ assignees: tasks.filter((task) => task.userId).length,+ relations,+ },+ warnings: [+ ...project.warnings,+ ...columnPlan.warnings,+ ...(unmatched ? [unmatched] : []),+ ],+ };+}diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex f872bdbf3..3e9af3bca 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -51,6 +51,8 @@ import githubIntegration, {import gitlabIntegration, {handleGitlabWebhookRoute,} from "./gitlab-integration";+import importRoutes from "./import";+import { stopActiveImports } from "./import/runs/stop-active-imports";import getInstanceStatus from "./instance/controllers/get-instance-status";import invitation from "./invitation";import label from "./label";@@ -871,6 +873,7 @@ export function createApp() {const invitationApi = api.route("/invitation", invitation);const workspaceApi = api.route("/workspace", workspace);const customFieldApi = api.route("/custom-field", customField);+ const importApi = api.route("/import", importRoutes);const userApi = api.route("/user", user);const adminApi = api.route("/admin", admin);@@ -1002,6 +1005,7 @@ export function createApp() {workflowRuleApi,workspaceApi,customFieldApi,+ importApi,oauthApi,};}@@ -1081,6 +1085,7 @@ export async function startServer(const [, signInEmailsDrained] = await Promise.all([drainPasswordResetDeliveries(),drainSignInEmails(),+ stopActiveImports(),]);if (!signInEmailsDrained) {console.warn("Timed out waiting for pending sign-in emails");@@ -1133,6 +1138,7 @@ const {workflowRuleApi,workspaceApi,customFieldApi,+ importApi,oauthApi,} = createdApp;@@ -1175,6 +1181,7 @@ export type AppType =| typeof invitationApi| typeof workspaceApi| typeof customFieldApi+ | typeof importApi| typeof userApi| typeof adminApi| typeof publicProjectApidiff --git a/apps/docs/openapi.json b/apps/docs/openapi.jsonindex 7d0f4f7c0..9c4a080ba 100644--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@ -1721,7 +1721,7 @@"string","null"],- "description": "The tool it was imported from, e.g. planka, trello, jira."+ "description": "The tool it was imported from: planka, trello, jira, plane, linear, kaneo, or a connected forge such as github."},"externalUrl": {"type": [@@ -4678,6 +4678,426 @@"value"]},+ "ImportSourceProjectList": {+ "type": "object",+ "properties": {+ "projects": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ImportSourceProject"+ }+ }+ },+ "required": [+ "projects"+ ]+ },+ "ImportSourceProject": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "detail": {+ "type": "string",+ "description": "Extra context shown next to the name, such as the source workspace or team."+ }+ },+ "required": [+ "id",+ "name"+ ]+ },+ "ImportConnection": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/PlankaImportConnection"+ },+ {+ "$ref": "#/components/schemas/PlaneImportConnection"+ },+ {+ "$ref": "#/components/schemas/LinearImportConnection"+ },+ {+ "$ref": "#/components/schemas/TrelloImportConnection"+ },+ {+ "$ref": "#/components/schemas/KaneoImportConnection"+ }+ ],+ "discriminator": {+ "propertyName": "source",+ "mapping": {+ "planka": "#/components/schemas/PlankaImportConnection",+ "plane": "#/components/schemas/PlaneImportConnection",+ "linear": "#/components/schemas/LinearImportConnection",+ "trello": "#/components/schemas/TrelloImportConnection",+ "kaneo": "#/components/schemas/KaneoImportConnection"+ }+ },+ "description": "Where to import from and how to sign in. Credentials are used only for this request and the import it starts; they are never stored, logged, or returned."+ },+ "PlankaImportConnection": {+ "type": "object",+ "properties": {+ "source": {+ "type": "string",+ "enum": [+ "planka"+ ]+ },+ "url": {+ "type": "string",+ "minLength": 1,+ "maxLength": 2048,+ "description": "Address of the PLANKA instance.",+ "example": "https://planka.example.com"+ },+ "apiKey": {+ "type": "string",+ "minLength": 1,+ "maxLength": 4096,+ "description": "A PLANKA API key. Send it, or username and password. Used only for this import and never stored or logged."+ },+ "username": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "description": "Username or email of a PLANKA account, used with password when no API key is sent."+ },+ "password": {+ "type": "string",+ "minLength": 1,+ "maxLength": 4096,+ "description": "Password of that PLANKA account. Used only for this import and never stored or logged."+ }+ },+ "required": [+ "source",+ "url"+ ]+ },+ "PlaneImportConnection": {+ "type": "object",+ "properties": {+ "source": {+ "type": "string",+ "enum": [+ "plane"+ ]+ },+ "url": {+ "type": "string",+ "minLength": 1,+ "maxLength": 2048,+ "description": "Address of the Plane instance, e.g. https://app.plane.so for Plane Cloud.",+ "example": "https://planka.example.com"+ },+ "apiKey": {+ "type": "string",+ "minLength": 1,+ "maxLength": 4096,+ "description": "A Plane personal access token. Used only for this import and never stored or logged."+ },+ "workspaceSlug": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "description": "Slug of the Plane workspace to read. Optional when the URL already names it."+ }+ },+ "required": [+ "source",+ "url",+ "apiKey"+ ]+ },+ "LinearImportConnection": {+ "type": "object",+ "properties": {+ "source": {+ "type": "string",+ "enum": [+ "linear"+ ]+ },+ "apiKey": {+ "type": "string",+ "minLength": 1,+ "maxLength": 4096,+ "description": "A Linear personal API key. Used only for this import and never stored or logged."+ }+ },+ "required": [+ "source",+ "apiKey"+ ]+ },+ "TrelloImportConnection": {+ "type": "object",+ "properties": {+ "source": {+ "type": "string",+ "enum": [+ "trello"+ ]+ },+ "token": {+ "type": "string",+ "minLength": 1,+ "maxLength": 4096,+ "description": "A Trello token authorized for this Kaneo instance. Used only for this import and never stored or logged."+ },+ "apiKey": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "description": "Trello API key, a public app identifier. Defaults to the server's TRELLO_API_KEY."+ }+ },+ "required": [+ "source",+ "token"+ ]+ },+ "KaneoImportConnection": {+ "type": "object",+ "properties": {+ "source": {+ "type": "string",+ "enum": [+ "kaneo"+ ]+ },+ "url": {+ "type": "string",+ "minLength": 1,+ "maxLength": 2048,+ "description": "Address of the Kaneo instance to import from.",+ "example": "https://planka.example.com"+ },+ "apiKey": {+ "type": "string",+ "minLength": 1,+ "maxLength": 4096,+ "description": "An API key from that Kaneo instance. Used only for this import and never stored or logged."+ }+ },+ "required": [+ "source",+ "url",+ "apiKey"+ ]+ },+ "ImportRunEnvelope": {+ "type": "object",+ "properties": {+ "run": {+ "$ref": "#/components/schemas/ImportRun"+ }+ },+ "required": [+ "run"+ ]+ },+ "ImportRun": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "workspaceId": {+ "type": "string"+ },+ "source": {+ "type": "string",+ "enum": [+ "planka",+ "plane",+ "linear",+ "trello",+ "kaneo"+ ]+ },+ "status": {+ "type": "string",+ "enum": [+ "running",+ "completed",+ "failed"+ ],+ "description": "completed once every selected project was attempted, even if some failed; check each project's status. failed means the run itself stopped."+ },+ "includeComments": {+ "type": "boolean"+ },+ "message": {+ "type": [+ "string",+ "null"+ ],+ "description": "Latest progress line while the run is running."+ },+ "error": {+ "type": [+ "string",+ "null"+ ]+ },+ "projects": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ImportRunProject"+ }+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ },+ "finishedAt": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time"+ }+ },+ "required": [+ "id",+ "workspaceId",+ "source",+ "status",+ "includeComments",+ "message",+ "error",+ "projects",+ "createdAt",+ "finishedAt"+ ]+ },+ "ImportRunProject": {+ "type": "object",+ "properties": {+ "sourceId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "status": {+ "type": "string",+ "enum": [+ "pending",+ "running",+ "completed",+ "failed"+ ]+ },+ "projectId": {+ "type": [+ "string",+ "null"+ ],+ "description": "The Kaneo project created by the import, once completed."+ },+ "projectSlug": {+ "type": [+ "string",+ "null"+ ]+ },+ "counts": {+ "$ref": "#/components/schemas/ImportCounts"+ },+ "warnings": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "error": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "sourceId",+ "name",+ "status",+ "projectId",+ "projectSlug",+ "counts",+ "warnings",+ "error"+ ]+ },+ "ImportCounts": {+ "type": "object",+ "properties": {+ "columns": {+ "type": "integer"+ },+ "tasks": {+ "type": "integer"+ },+ "labels": {+ "type": "integer"+ },+ "comments": {+ "type": "integer"+ },+ "assignees": {+ "type": "integer",+ "description": "Tasks that were assigned to a workspace member."+ },+ "relations": {+ "type": "integer"+ }+ },+ "required": [+ "columns",+ "tasks",+ "labels",+ "comments",+ "assignees",+ "relations"+ ]+ },+ "ImportRunList": {+ "type": "object",+ "properties": {+ "runs": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ImportRun"+ }+ }+ },+ "required": [+ "runs"+ ]+ },+ "TrelloAuthorizeUrl": {+ "type": "object",+ "properties": {+ "authorizeUrl": {+ "type": [+ "string",+ "null"+ ],+ "description": "Trello page where the user approves read access for Kaneo and copies a token. null when the server has no TRELLO_API_KEY; the user then sends their own Trello API key with the token."+ }+ },+ "required": [+ "authorizeUrl"+ ]+ },"CurrentUser": {"type": "object","properties": {@@ -13589,7 +14009,10 @@"enum": ["planka","trello",- "jira"+ "jira",+ "plane",+ "linear",+ "kaneo"],"description": "The tool the comment was imported from. Supplying external attribution requires workspace:manage_settings."}@@ -21087,24 +21510,277 @@}}},- "/workspace": {+ "/workspace": {+ "get": {+ "operationId": "listWorkspaces",+ "tags": [+ "Workspaces"+ ],+ "summary": "List workspaces",+ "description": "List the workspaces where one of the caller's roles grants workspace:read, with the caller's role, sorted by name. Instance admins get every workspace they are a member of, and only those.",+ "responses": {+ "200": {+ "description": "The caller's workspaces",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/Workspace"+ }+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "The API key lacks workspace:read",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ }+ }+ }+ },+ "/workspace/{workspaceId}": {+ "get": {+ "operationId": "getWorkspace",+ "tags": [+ "Workspaces"+ ],+ "summary": "Get workspace",+ "description": "Get a workspace where one of the caller's roles grants workspace:read, with the caller's role. Instance admins can get any workspace, with a null role when they are not a member.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "workspaceId",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "The workspace",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Workspace"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "The API key lacks workspace:read",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "404": {+ "description": "Workspace not found, the caller is not a member of it, or none of their roles grants workspace:read",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ }+ }+ }+ },+ "/workspace/{workspaceId}/members": {+ "get": {+ "operationId": "getWorkspaceMembers",+ "tags": [+ "Workspaces"+ ],+ "summary": "Get workspace members",+ "description": "Get all members of a workspace, with their role. Pass projectId to get only the members who can access that project.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "workspaceId",+ "in": "path"+ },+ {+ "schema": {+ "type": "string",+ "description": "Only return members who can access this project, for example to fill an assignee picker."+ },+ "required": false,+ "description": "Only return members who can access this project, for example to fill an assignee picker.",+ "name": "projectId",+ "in": "query"+ }+ ],+ "responses": {+ "200": {+ "description": "List of workspace members",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/WorkspaceMember"+ }+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "No access to the project",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "404": {+ "description": "Workspace not found, or project not found in this workspace",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ }+ }+ }+ },+ "/workspace/{workspaceId}/project-access/me": {+ "get": {+ "operationId": "getMyProjectAccess",+ "tags": [+ "Workspaces"+ ],+ "summary": "Get my project access",+ "description": "Get the caller's own project access in the workspace: every project, or the selected projects they're limited to. Owners and instance admins always get every project.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "workspaceId",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "The caller's project access",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MemberProjectAccess"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "404": {+ "description": "Workspace not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ }+ }+ }+ },+ "/workspace/{workspaceId}/capabilities": {"get": {- "operationId": "listWorkspaces",+ "operationId": "getMyWorkspaceCapabilities","tags": ["Workspaces"],- "summary": "List workspaces",- "description": "List the workspaces where one of the caller's roles grants workspace:read, with the caller's role, sorted by name. Instance admins get every workspace they are a member of, and only those.",+ "summary": "Get my workspace capabilities",+ "description": "Check every named workspace action for the caller in one request: which of them the caller's roles allow, narrowed by the API key's scope when one is used. Instance admins are allowed everything.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "workspaceId",+ "in": "path"+ }+ ],"responses": {"200": {- "description": "The caller's workspaces",+ "description": "The caller's capabilities in the workspace","content": {"application/json": {"schema": {- "type": "array",- "items": {- "$ref": "#/components/schemas/Workspace"- }+ "$ref": "#/components/schemas/WorkspaceCapabilities"}}}@@ -21119,8 +21795,8 @@}}},- "403": {- "description": "The API key lacks workspace:read",+ "404": {+ "description": "Workspace not found","content": {"application/json": {"schema": {@@ -21135,14 +21811,14 @@}}},- "/workspace/{workspaceId}": {+ "/workspace/{workspaceId}/project-access": {"get": {- "operationId": "getWorkspace",+ "operationId": "getWorkspaceProjectAccess","tags": ["Workspaces"],- "summary": "Get workspace",- "description": "Get a workspace where one of the caller's roles grants workspace:read, with the caller's role. Instance admins can get any workspace, with a null role when they are not a member.",+ "summary": "Get member project access",+ "description": "List the members who are limited to selected projects, with the projects each one can access. Everyone else in the workspace can access every project. A caller whose own access is limited only sees the projects they can access.","parameters": [{"schema": {@@ -21155,11 +21831,15 @@],"responses": {"200": {- "description": "The workspace",+ "description": "Members limited to selected projects","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/Workspace"+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/MemberProjectAccess"+ },+ "description": "Members limited to selected projects. Members not listed can access every project. Project IDs only include projects the caller can access."}}}@@ -21175,7 +21855,7 @@}},"403": {- "description": "The API key lacks workspace:read",+ "description": "Missing member:update permission","content": {"application/json": {"schema": {@@ -21185,7 +21865,7 @@}},"404": {- "description": "Workspace not found, the caller is not a member of it, or none of their roles grants workspace:read",+ "description": "Workspace not found","content": {"application/json": {"schema": {@@ -21200,14 +21880,14 @@}}},- "/workspace/{workspaceId}/members": {- "get": {- "operationId": "getWorkspaceMembers",+ "/workspace/{workspaceId}/members/{userId}/project-access": {+ "put": {+ "operationId": "updateMemberProjectAccess","tags": ["Workspaces"],- "summary": "Get workspace members",- "description": "Get all members of a workspace, with their role. Pass projectId to get only the members who can access that project.",+ "summary": "Update member project access",+ "description": "Give a member access to every project, or limit them to selected projects. Owners always access every project, and you can't change your own access or give access to projects you can't access yourself.","parameters": [{"schema": {@@ -21219,25 +21899,61 @@},{"schema": {- "type": "string",- "description": "Only return members who can access this project, for example to fill an assignee picker."+ "type": "string"},- "required": false,- "description": "Only return members who can access this project, for example to fill an assignee picker.",- "name": "projectId",- "in": "query"+ "required": true,+ "name": "userId",+ "in": "path"}],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "projectAccess": {+ "type": "string",+ "enum": [+ "all",+ "selected"+ ],+ "description": "\"all\" gives access to every project in the workspace, including future ones. \"selected\" limits the member to projectIds."+ },+ "projectIds": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "default": [],+ "description": "Projects the member can access when projectAccess is \"selected\"."+ }+ },+ "required": [+ "projectAccess"+ ]+ }+ }+ }+ },"responses": {"200": {- "description": "List of workspace members",+ "description": "The member's project access","content": {"application/json": {"schema": {- "type": "array",- "items": {- "$ref": "#/components/schemas/WorkspaceMember"- }+ "$ref": "#/components/schemas/MemberProjectAccess"+ }+ }+ }+ },+ "400": {+ "description": "Invalid body, the member is an owner, or a project is not in this workspace",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"}}}@@ -21253,7 +21969,7 @@}},"403": {- "description": "No access to the project",+ "description": "Missing member:update permission, changing your own access, or granting a project you can't access","content": {"application/json": {"schema": {@@ -21263,7 +21979,7 @@}},"404": {- "description": "Workspace not found, or project not found in this workspace",+ "description": "Workspace or member not found","content": {"application/json": {"schema": {@@ -21278,31 +21994,34 @@}}},- "/workspace/{workspaceId}/project-access/me": {+ "/custom-field/project/{projectId}": {"get": {- "operationId": "getMyProjectAccess",+ "operationId": "getCustomFieldsByProject","tags": [- "Workspaces"+ "Custom Fields"],- "summary": "Get my project access",- "description": "Get the caller's own project access in the workspace: every project, or the selected projects they're limited to. Owners and instance admins always get every project.",+ "summary": "Get custom fields",+ "description": "Get all custom field definitions for a project.","parameters": [{"schema": {"type": "string"},"required": true,- "name": "workspaceId",+ "name": "projectId","in": "path"}],"responses": {"200": {- "description": "The caller's project access",+ "description": "List of custom field definitions","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/MemberProjectAccess"+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CustomFieldDefinition"+ }}}}@@ -21317,8 +22036,18 @@}}},+ "403": {+ "description": "No access to the project, or missing read permission",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },"404": {- "description": "Workspace not found",+ "description": "Project not found","content": {"application/json": {"schema": {@@ -21333,31 +22062,34 @@}}},- "/workspace/{workspaceId}/capabilities": {+ "/custom-field/project/{projectId}/values": {"get": {- "operationId": "getMyWorkspaceCapabilities",+ "operationId": "getCustomFieldValuesByProject","tags": [- "Workspaces"+ "Custom Fields"],- "summary": "Get my workspace capabilities",- "description": "Check every named workspace action for the caller in one request: which of them the caller's roles allow, narrowed by the API key's scope when one is used. Instance admins are allowed everything.",+ "summary": "Get project custom field values",+ "description": "Get all custom field values for every task in a project.","parameters": [{"schema": {"type": "string"},"required": true,- "name": "workspaceId",+ "name": "projectId","in": "path"}],"responses": {"200": {- "description": "The caller's capabilities in the workspace",+ "description": "List of custom field values for the project","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/WorkspaceCapabilities"+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CustomFieldValue"+ }}}}@@ -21372,8 +22104,18 @@}}},+ "403": {+ "description": "No access to the project, or missing read permission",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },"404": {- "description": "Workspace not found",+ "description": "Project not found","content": {"application/json": {"schema": {@@ -21388,35 +22130,34 @@}}},- "/workspace/{workspaceId}/project-access": {+ "/custom-field/task/{taskId}": {"get": {- "operationId": "getWorkspaceProjectAccess",+ "operationId": "getCustomFieldValuesByTask","tags": [- "Workspaces"+ "Custom Fields"],- "summary": "Get member project access",- "description": "List the members who are limited to selected projects, with the projects each one can access. Everyone else in the workspace can access every project. A caller whose own access is limited only sees the projects they can access.",+ "summary": "Get task custom field values",+ "description": "Get all custom field values for a task with their definitions.","parameters": [{"schema": {"type": "string"},"required": true,- "name": "workspaceId",+ "name": "taskId","in": "path"}],"responses": {"200": {- "description": "Members limited to selected projects",+ "description": "List of custom field values for the task","content": {"application/json": {"schema": {"type": "array","items": {- "$ref": "#/components/schemas/MemberProjectAccess"- },- "description": "Members limited to selected projects. Members not listed can access every project. Project IDs only include projects the caller can access."+ "$ref": "#/components/schemas/CustomFieldValue"+ }}}}@@ -21432,7 +22173,7 @@}},"403": {- "description": "Missing member:update permission",+ "description": "No access to the project, or missing task:read permission","content": {"application/json": {"schema": {@@ -21442,7 +22183,7 @@}},"404": {- "description": "Workspace not found",+ "description": "Task not found","content": {"application/json": {"schema": {@@ -21457,32 +22198,82 @@}}},- "/workspace/{workspaceId}/members/{userId}/project-access": {- "put": {- "operationId": "updateMemberProjectAccess",+ "/custom-field/project/{projectId}/filter-values": {+ "get": {+ "operationId": "getCustomFieldFilterValues","tags": [- "Workspaces"+ "Custom Fields"],- "summary": "Update member project access",- "description": "Give a member access to every project, or limit them to selected projects. Owners always access every project, and you can't change your own access or give access to projects you can't access yourself.",+ "summary": "Get custom field filter values",+ "description": "Get distinct values used by tasks for each custom field of a project.","parameters": [{"schema": {"type": "string"},"required": true,- "name": "workspaceId",+ "name": "projectId","in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "Distinct values used for each custom field",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CustomFieldFilterValues"+ }+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "No access to the project, or missing read permission",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }},- {- "schema": {- "type": "string"- },- "required": true,- "name": "userId",- "in": "path"+ "404": {+ "description": "Project not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}+ }+ }+ },+ "/custom-field": {+ "post": {+ "operationId": "createCustomField",+ "tags": [+ "Custom Fields"],+ "summary": "Create custom field",+ "description": "Create a custom field definition for a project.","requestBody": {"required": true,"content": {@@ -21490,25 +22281,41 @@"schema": {"type": "object","properties": {- "projectAccess": {+ "projectId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "type": {"type": "string","enum": [- "all",- "selected"- ],- "description": "\"all\" gives access to every project in the workspace, including future ones. \"selected\" limits the member to projectIds."+ "text",+ "number",+ "date",+ "dropdown",+ "boolean",+ "multiselect"+ ]},- "projectIds": {+ "required": {+ "type": "boolean",+ "default": false+ },+ "defaultValue": {+ "type": "string"+ },+ "options": {"type": "array","items": {"type": "string"- },- "default": [],- "description": "Projects the member can access when projectAccess is \"selected\"."+ }}},"required": [- "projectAccess"+ "projectId",+ "name",+ "type"]}}@@ -21516,17 +22323,17 @@},"responses": {"200": {- "description": "The member's project access",+ "description": "The created custom field","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/MemberProjectAccess"+ "$ref": "#/components/schemas/CustomFieldDefinition"}}}},"400": {- "description": "Invalid body, the member is an owner, or a project is not in this workspace",+ "description": "Invalid body","content": {"application/json": {"schema": {@@ -21546,7 +22353,7 @@}},"403": {- "description": "Missing member:update permission, changing your own access, or granting a project you can't access",+ "description": "No access to the project, or missing project:update permission","content": {"application/json": {"schema": {@@ -21556,7 +22363,7 @@}},"404": {- "description": "Workspace or member not found",+ "description": "Project not found","content": {"application/json": {"schema": {@@ -21571,14 +22378,14 @@}}},- "/custom-field/project/{projectId}": {- "get": {- "operationId": "getCustomFieldsByProject",+ "/custom-field/reorder/{projectId}": {+ "put": {+ "operationId": "reorderCustomFields","tags": ["Custom Fields"],- "summary": "Get custom fields",- "description": "Get all custom field definitions for a project.",+ "summary": "Reorder custom fields",+ "description": "Set new positions for a project's custom fields.","parameters": [{"schema": {@@ -21589,16 +22396,56 @@"in": "path"}],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "fields": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "position": {+ "type": "number"+ }+ },+ "required": [+ "id",+ "position"+ ]+ }+ }+ },+ "required": [+ "fields"+ ]+ }+ }+ }+ },"responses": {"200": {- "description": "List of custom field definitions",+ "description": "The reordered custom fields","content": {"application/json": {"schema": {- "type": "array",- "items": {- "$ref": "#/components/schemas/CustomFieldDefinition"- }+ "$ref": "#/components/schemas/ReorderCustomFieldsResponse"+ }+ }+ }+ },+ "400": {+ "description": "A custom field does not belong to this project",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"}}}@@ -21614,7 +22461,7 @@}},"403": {- "description": "No access to the project, or missing read permission",+ "description": "No access to the project, or missing project:update permission","content": {"application/json": {"schema": {@@ -21639,34 +22486,57 @@}}},- "/custom-field/project/{projectId}/values": {- "get": {- "operationId": "getCustomFieldValuesByProject",+ "/custom-field/value": {+ "put": {+ "operationId": "setCustomFieldValue","tags": ["Custom Fields"],- "summary": "Get project custom field values",- "description": "Get all custom field values for every task in a project.",- "parameters": [- {- "schema": {- "type": "string"- },- "required": true,- "name": "projectId",- "in": "path"+ "summary": "Set custom field value",+ "description": "Create or update a custom field value for a task.",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "taskId": {+ "type": "string"+ },+ "fieldId": {+ "type": "string"+ },+ "value": {+ "type": "string"+ }+ },+ "required": [+ "taskId",+ "fieldId",+ "value"+ ]+ }+ }}- ],+ },"responses": {"200": {- "description": "List of custom field values for the project",+ "description": "The saved custom field value","content": {"application/json": {"schema": {- "type": "array",- "items": {- "$ref": "#/components/schemas/CustomFieldValue"- }+ "$ref": "#/components/schemas/SetCustomFieldValueResponse"+ }+ }+ }+ },+ "400": {+ "description": "Invalid body, or unknown custom field",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"}}}@@ -21682,7 +22552,7 @@}},"403": {- "description": "No access to the project, or missing read permission",+ "description": "No access to the project, or missing task:update permission","content": {"application/json": {"schema": {@@ -21692,7 +22562,7 @@}},"404": {- "description": "Project not found",+ "description": "Task not found","content": {"application/json": {"schema": {@@ -21707,34 +22577,31 @@}}},- "/custom-field/task/{taskId}": {- "get": {- "operationId": "getCustomFieldValuesByTask",+ "/custom-field/{id}": {+ "delete": {+ "operationId": "deleteCustomField","tags": ["Custom Fields"],- "summary": "Get task custom field values",- "description": "Get all custom field values for a task with their definitions.",+ "summary": "Delete custom field",+ "description": "Delete a custom field definition by ID.","parameters": [{"schema": {"type": "string"},"required": true,- "name": "taskId",+ "name": "id","in": "path"}],"responses": {"200": {- "description": "List of custom field values for the task",+ "description": "The deleted custom field","content": {"application/json": {"schema": {- "type": "array",- "items": {- "$ref": "#/components/schemas/CustomFieldValue"- }+ "$ref": "#/components/schemas/CustomFieldDefinition"}}}@@ -21750,7 +22617,7 @@}},"403": {- "description": "No access to the project, or missing task:read permission",+ "description": "No access to the project, or missing project:update permission","content": {"application/json": {"schema": {@@ -21760,7 +22627,7 @@}},"404": {- "description": "Task not found",+ "description": "Custom field not found","content": {"application/json": {"schema": {@@ -21775,34 +22642,54 @@}}},- "/custom-field/project/{projectId}/filter-values": {- "get": {- "operationId": "getCustomFieldFilterValues",+ "/import/projects": {+ "post": {+ "operationId": "listImportSourceProjects","tags": [- "Custom Fields"+ "Import"],- "summary": "Get custom field filter values",- "description": "Get distinct values used by tasks for each custom field of a project.",- "parameters": [- {- "schema": {- "type": "string"- },- "required": true,- "name": "projectId",- "in": "path"+ "summary": "List projects in an import source",+ "description": "Sign in to PLANKA, Plane, Linear, Trello or another Kaneo instance and list the projects that can be imported. The credentials are used only for this request; they are never stored, logged, or returned.",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "workspaceId": {+ "type": "string",+ "minLength": 1+ },+ "connection": {+ "$ref": "#/components/schemas/ImportConnection"+ }+ },+ "required": [+ "workspaceId",+ "connection"+ ]+ }+ }}- ],+ },"responses": {"200": {- "description": "Distinct values used for each custom field",+ "description": "Projects available in the source","content": {"application/json": {"schema": {- "type": "array",- "items": {- "$ref": "#/components/schemas/CustomFieldFilterValues"- }+ "$ref": "#/components/schemas/ImportSourceProjectList"+ }+ }+ }+ },+ "400": {+ "description": "Invalid body, credentials the source rejected, or a destination this server may not reach",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"}}}@@ -21817,8 +22704,18 @@}}},+ "402": {+ "description": "Workspace plan has expired",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },"403": {- "description": "No access to the project, or missing read permission",+ "description": "Missing workspace:manage_settings or project:create permission","content": {"application/json": {"schema": {@@ -21828,7 +22725,7 @@}},"404": {- "description": "Project not found",+ "description": "Workspace not found","content": {"application/json": {"schema": {@@ -21839,18 +22736,28 @@},"429": {"$ref": "#/components/responses/ApiKeyRateLimited"+ },+ "502": {+ "description": "The source could not be reached or answered with an error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }}}}},- "/custom-field": {+ "/import/runs": {"post": {- "operationId": "createCustomField",+ "operationId": "startImportRun","tags": [- "Custom Fields"+ "Import"],- "summary": "Create custom field",- "description": "Create a custom field definition for a project.",+ "summary": "Start an import",+ "description": "Import the selected source projects into the workspace as new Kaneo projects. The import runs in the background; poll getImportRun for progress. The credentials are held in memory only while the import runs; they are never stored, logged, or returned. Imported tasks do not send notifications or trigger integrations.","requestBody": {"required": true,"content": {@@ -21858,59 +22765,52 @@"schema": {"type": "object","properties": {- "projectId": {- "type": "string"- },- "name": {- "type": "string"- },- "type": {+ "workspaceId": {"type": "string",- "enum": [- "text",- "number",- "date",- "dropdown",- "boolean",- "multiselect"- ]- },- "required": {- "type": "boolean",- "default": false+ "minLength": 1},- "defaultValue": {- "type": "string"+ "connection": {+ "$ref": "#/components/schemas/ImportConnection"},- "options": {+ "projectIds": {"type": "array","items": {- "type": "string"- }+ "type": "string",+ "minLength": 1,+ "maxLength": 512+ },+ "minItems": 1,+ "maxItems": 50,+ "description": "Source project IDs from listImportSourceProjects, imported in this order."+ },+ "includeComments": {+ "type": "boolean",+ "default": true,+ "description": "Import task comments too. Defaults to true."}},"required": [- "projectId",- "name",- "type"+ "workspaceId",+ "connection",+ "projectIds"]}}}},"responses": {- "200": {- "description": "The created custom field",+ "202": {+ "description": "The import started","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/CustomFieldDefinition"+ "$ref": "#/components/schemas/ImportRunEnvelope"}}}},"400": {- "description": "Invalid body",+ "description": "Invalid body, credentials the source rejected, a destination this server may not reach, or a selected project the source no longer lists","content": {"application/json": {"schema": {@@ -21929,8 +22829,18 @@}}},+ "402": {+ "description": "Workspace plan has expired",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },"403": {- "description": "No access to the project, or missing project:update permission",+ "description": "Missing workspace:manage_settings or project:create permission","content": {"application/json": {"schema": {@@ -21940,7 +22850,17 @@}},"404": {- "description": "Project not found",+ "description": "Workspace not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "409": {+ "description": "Another import is already running in this workspace","content": {"application/json": {"schema": {@@ -21950,79 +22870,53 @@}},"429": {- "$ref": "#/components/responses/ApiKeyRateLimited"+ "description": "This server is already running its maximum number of imports, or the API key exceeded its rate limit",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "502": {+ "description": "The source could not be reached or answered with an error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }}}}},- "/custom-field/reorder/{projectId}": {- "put": {- "operationId": "reorderCustomFields",+ "/import/runs/{workspaceId}": {+ "get": {+ "operationId": "listImportRuns","tags": [- "Custom Fields"+ "Import"],- "summary": "Reorder custom fields",- "description": "Set new positions for a project's custom fields.",+ "summary": "List imports",+ "description": "The workspace's 20 most recent imports, newest first. A run whose server stopped reporting progress is returned as failed.","parameters": [{"schema": {"type": "string"},"required": true,- "name": "projectId",+ "name": "workspaceId","in": "path"}],- "requestBody": {- "required": true,- "content": {- "application/json": {- "schema": {- "type": "object",- "properties": {- "fields": {- "type": "array",- "items": {- "type": "object",- "properties": {- "id": {- "type": "string"- },- "position": {- "type": "number"- }- },- "required": [- "id",- "position"- ]- }- }- },- "required": [- "fields"- ]- }- }- }- },"responses": {"200": {- "description": "The reordered custom fields",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ReorderCustomFieldsResponse"- }- }- }- },- "400": {- "description": "A custom field does not belong to this project",+ "description": "Recent imports","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/ApiError"+ "$ref": "#/components/schemas/ImportRunList"}}}@@ -22038,7 +22932,7 @@}},"403": {- "description": "No access to the project, or missing project:update permission",+ "description": "Missing workspace:manage_settings or project:create permission","content": {"application/json": {"schema": {@@ -22048,7 +22942,7 @@}},"404": {- "description": "Project not found",+ "description": "Workspace not found","content": {"application/json": {"schema": {@@ -22063,57 +22957,31 @@}}},- "/custom-field/value": {- "put": {- "operationId": "setCustomFieldValue",+ "/import/trello/authorize-url/{workspaceId}": {+ "get": {+ "operationId": "getTrelloAuthorizeUrl","tags": [- "Custom Fields"+ "Import"],- "summary": "Set custom field value",- "description": "Create or update a custom field value for a task.",- "requestBody": {- "required": true,- "content": {- "application/json": {- "schema": {- "type": "object",- "properties": {- "taskId": {- "type": "string"- },- "fieldId": {- "type": "string"- },- "value": {- "type": "string"- }- },- "required": [- "taskId",- "fieldId",- "value"- ]- }- }+ "summary": "Get the Trello authorize link",+ "description": "Link to Trello's authorize page for this server's Trello app, where the user approves read access and copies a token for startImportRun. null when the server has no TRELLO_API_KEY.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "workspaceId",+ "in": "path"}- },+ ],"responses": {"200": {- "description": "The saved custom field value",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/SetCustomFieldValueResponse"- }- }- }- },- "400": {- "description": "Invalid body, or unknown custom field",+ "description": "The Trello authorize link","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/ApiError"+ "$ref": "#/components/schemas/TrelloAuthorizeUrl"}}}@@ -22129,7 +22997,7 @@}},"403": {- "description": "No access to the project, or missing task:update permission",+ "description": "Missing workspace:manage_settings or project:create permission","content": {"application/json": {"schema": {@@ -22139,7 +23007,7 @@}},"404": {- "description": "Task not found",+ "description": "Workspace not found","content": {"application/json": {"schema": {@@ -22154,31 +23022,39 @@}}},- "/custom-field/{id}": {- "delete": {- "operationId": "deleteCustomField",+ "/import/runs/{workspaceId}/{runId}": {+ "get": {+ "operationId": "getImportRun","tags": [- "Custom Fields"+ "Import"],- "summary": "Delete custom field",- "description": "Delete a custom field definition by ID.",+ "summary": "Get an import",+ "description": "Progress and outcome of one import, including each project's status, counts and warnings.","parameters": [{"schema": {"type": "string"},"required": true,- "name": "id",+ "name": "workspaceId",+ "in": "path"+ },+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "runId","in": "path"}],"responses": {"200": {- "description": "The deleted custom field",+ "description": "The import","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/CustomFieldDefinition"+ "$ref": "#/components/schemas/ImportRunEnvelope"}}}@@ -22194,7 +23070,7 @@}},"403": {- "description": "No access to the project, or missing project:update permission",+ "description": "Missing workspace:manage_settings or project:create permission","content": {"application/json": {"schema": {@@ -22204,7 +23080,7 @@}},"404": {- "description": "Custom field not found",+ "description": "Workspace or import not found","content": {"application/json": {"schema": {diff --git a/tests/api-integration/import.test.ts b/tests/api-integration/import.test.tsnew file mode 100644index 000000000..160786567--- /dev/null+++ b/tests/api-integration/import.test.ts@@ -0,0 +1,903 @@+import { randomUUID } from "node:crypto";+import { and, asc, eq, inArray, isNull } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import type {+ ImportedProject,+ ImportSource,+ ReadProjectOptions,+} from "../../packages/importers/dist/index.js";+import db, { schema } from "../../apps/api/src/database";+import { waitForActiveImports } from "../../apps/api/src/import/active-imports";+import { createApp } from "../../apps/api/src/index";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import { readErrorBody } from "./helpers/error-body";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const importers = vi.hoisted(() => ({ connectSource: vi.fn() }));+vi.mock("../../packages/importers/dist/index.js", async (original) => ({+ ...(await original<+ typeof import("../../packages/importers/dist/index.js")+ >()),+ connectSource: importers.connectSource,+}));++const SECRET = "planka-secret-key-0123456789";++const connection = {+ source: "planka",+ url: "https://planka.example.com",+ apiKey: SECRET,+};++function plankaProject(memberEmail: string): ImportedProject {+ return {+ name: "Website Relaunch",+ description: "Everything for the relaunch",+ columns: [+ { key: "c1", name: "Backlog", isFinal: false },+ { key: "c2", name: "Doing", isFinal: false },+ { key: "c3", name: "Shipped", isFinal: true },+ { key: "c4", name: "Planned", isFinal: false },+ ],+ labels: [+ { key: "l1", name: "Bug", color: "red" },+ { key: "l2", name: "Design", color: "purple" },+ { key: "l3", name: "Unused", color: "gray" },+ ],+ tasks: [+ {+ key: "t1",+ columnKey: "c1",+ title: "Write the copy",+ description: "Draft **all** pages",+ priority: "high",+ createdAt: "2023-05-06T07:08:09.000Z",+ dueDate: "2024-02-01T00:00:00.000Z",+ assignee: { name: "Mira", email: memberEmail.toUpperCase() },+ labelKeys: ["l1", "l2", "l1"],+ comments: [+ {+ author: { name: "Ana" },+ body: "Looks good",+ createdAt: "2024-01-02T03:04:05.000Z",+ },+ { author: {}, body: "No author" },+ { author: { name: "Empty" }, body: " " },+ ],+ },+ {+ key: "t2",+ columnKey: "c1",+ title: " ",+ description: "",+ priority: "bogus" as ImportedProject["tasks"][number]["priority"],+ assignee: { name: "Stranger", email: "[email protected]" },+ labelKeys: [],+ comments: [],+ },+ {+ key: "t3",+ columnKey: null,+ title: "Someday",+ description: "",+ priority: "low",+ labelKeys: [],+ comments: [],+ },+ {+ key: "t4",+ columnKey: "c3",+ archived: true,+ title: "Old launch",+ description: "",+ priority: "no-priority",+ labelKeys: [],+ comments: [],+ },+ {+ key: "t5",+ columnKey: "c3",+ title: "Ship it",+ description: "",+ priority: "urgent",+ labelKeys: ["l1"],+ comments: [],+ },+ ],+ relations: [+ { sourceKey: "t1", targetKey: "t5", type: "subtask" },+ { sourceKey: "t5", targetKey: "t1", type: "subtask" },+ { sourceKey: "t2", targetKey: "t2", type: "related" },+ { sourceKey: "t1", targetKey: "t3", type: "blocks" },+ ],+ warnings: ["2 attachments were skipped."],+ };+}++function numberedProject(): ImportedProject {+ const task = (key: string, title: string, number?: number) => ({+ key,+ ...(number === undefined ? {} : { number }),+ columnKey: "c1",+ title,+ description: "",+ priority: "no-priority" as const,+ labelKeys: [],+ comments: [],+ });+ return {+ name: "Engineering",+ key: "eng",+ columns: [{ key: "c1", name: "To Do", isFinal: false }],+ labels: [],+ tasks: [+ task("a", "Seven", 7),+ task("b", "No number"),+ task("c", "Three", 3),+ task("d", "Another seven", 7),+ ],+ relations: [],+ warnings: [],+ };+}++function fakeSource(+ read: (id: string, options: ReadProjectOptions) => Promise<ImportedProject>,+): ImportSource {+ return {+ listProjects: vi.fn(async () => [+ { id: "p1", name: "Website Relaunch", detail: "Marketing" },+ { id: "p2", name: "Broken board" },+ ]),+ readProject: vi.fn(read),+ };+}++class SourceHttpError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ this.name = "SourceHttpError";+ }+}++async function createAdmin() {+ return createWorkspaceMember({ role: "admin", userName: "Importer" });+}++async function addMember(workspaceId: string, name: string, role = "member") {+ const id = `user-${randomUUID()}`;+ const [user] = await db+ .insert(schema.userTable)+ .values({ id, email: `${id}@example.com`, emailVerified: true, name })+ .returning();+ await db.insert(schema.workspaceUserTable).values({+ workspaceId,+ userId: id,+ role,+ joinedAt: new Date(),+ });+ return user;+}++function post(path: string, body: unknown) {+ return createApp().app.request(`/api/import${path}`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });+}++function get(path: string) {+ return createApp().app.request(`/api/import${path}`);+}++async function importProject(workspaceId: string) {+ const started = await post("/runs", {+ workspaceId,+ connection,+ projectIds: ["p1"],+ });+ expect(started.status).toBe(202);+ const { run } = (await started.json()) as { run: { id: string } };+ await waitForActiveImports();++ const polled = await get(`/runs/${workspaceId}/${run.id}`);+ const { run: finished } = (await polled.json()) as {+ run: {+ projects: {+ status: string;+ projectId: string | null;+ projectSlug: string | null;+ }[];+ };+ };+ const [imported] = finished.projects;+ expect(imported?.status).toBe("completed");+ return imported as { projectId: string; projectSlug: string };+}++describe("API integration: import from other tools", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ importers.connectSource.mockReset();+ });++ it("lists the projects of a source without echoing credentials", async () => {+ const admin = await createAdmin();+ importers.connectSource.mockResolvedValue(+ fakeSource(async () => plankaProject("")),+ );+ mockAuthenticatedSession(admin.user);++ const response = await post("/projects", {+ workspaceId: admin.workspace.id,+ connection,+ });++ expect(response.status).toBe(200);+ const text = await response.text();+ expect(JSON.parse(text)).toEqual({+ projects: [+ { id: "p1", name: "Website Relaunch", detail: "Marketing" },+ { id: "p2", name: "Broken board" },+ ],+ });+ expect(text).not.toContain(SECRET);+ expect(importers.connectSource).toHaveBeenCalledWith(+ connection,+ expect.objectContaining({+ fetch: expect.any(Function),+ signal: expect.any(AbortSignal),+ }),+ );+ });++ it("explains rejected credentials", async () => {+ const admin = await createAdmin();+ importers.connectSource.mockRejectedValue(+ new SourceHttpError(`PLANKA /api/users/me: unauthorized ${SECRET}`, 401),+ );+ mockAuthenticatedSession(admin.user);++ const response = await post("/projects", {+ workspaceId: admin.workspace.id,+ connection,+ });++ expect(response.status).toBe(400);+ const body = await readErrorBody(response);+ expect(body.message).toBe(+ "Could not sign in to PLANKA. Check the API key.",+ );+ });++ it("asks for a Trello API key when the server has none", async () => {+ vi.stubEnv("TRELLO_API_KEY", "");+ const admin = await createAdmin();+ mockAuthenticatedSession(admin.user);++ const response = await post("/projects", {+ workspaceId: admin.workspace.id,+ connection: { source: "trello", token: "trello-token-123456" },+ });++ expect(response.status).toBe(400);+ expect((await readErrorBody(response)).message).toBe(+ "Add a Trello API key.",+ );+ expect(importers.connectSource).not.toHaveBeenCalled();+ vi.unstubAllEnvs();+ });++ it("imports projects in the background and reports each one", async () => {+ const admin = await createAdmin();+ const workspaceId = admin.workspace.id;+ const member = await addMember(workspaceId, "Mira");+ await db.insert(schema.labelTable).values({+ name: "Bug",+ color: "#123456",+ workspaceId,+ taskId: null,+ });+ const source = fakeSource(async (id, options) => {+ options.onProgress?.("Reading cards (1 of 5)");+ if (id === "p2") {+ throw new SourceHttpError("PLANKA /api/boards/p2: boom", 500);+ }+ expect(options.includeComments).toBe(true);+ return plankaProject(member.email);+ });+ importers.connectSource.mockResolvedValue(source);+ mockAuthenticatedSession(admin.user);++ const started = await post("/runs", {+ workspaceId,+ connection,+ projectIds: ["p2", "p1"],+ });+ expect(started.status).toBe(202);+ const { run } = (await started.json()) as {+ run: { id: string; status: string; projects: { name: string }[] };+ };+ expect(run.status).toBe("running");+ expect(run.projects.map((project) => project.name)).toEqual([+ "Broken board",+ "Website Relaunch",+ ]);++ await waitForActiveImports();++ const polled = await get(`/runs/${workspaceId}/${run.id}`);+ expect(polled.status).toBe(200);+ const { run: finished } = (await polled.json()) as {+ run: {+ status: string;+ error: string | null;+ message: string | null;+ finishedAt: string | null;+ projects: {+ sourceId: string;+ status: string;+ projectId: string | null;+ projectSlug: string | null;+ counts: Record<string, number>;+ warnings: string[];+ error: string | null;+ }[];+ };+ };+ expect(finished).toMatchObject({+ status: "completed",+ error: null,+ message: null,+ });+ expect(finished.finishedAt).not.toBeNull();+ const [broken, imported] = finished.projects;+ expect(broken).toMatchObject({+ sourceId: "p2",+ status: "failed",+ projectId: null,+ error: "PLANKA returned an error (HTTP 500). Try again later.",+ });+ expect(imported).toMatchObject({+ sourceId: "p1",+ status: "completed",+ projectSlug: "WR",+ error: null,+ counts: {+ columns: 4,+ tasks: 5,+ labels: 2,+ comments: 2,+ assignees: 1,+ relations: 2,+ },+ });+ expect(imported?.warnings).toEqual([+ "2 attachments were skipped.",+ 'Renamed a column to avoid conflicts: "Planned" to "Planned list".',+ "1 task was assigned to someone who is not a member of this workspace (Stranger). Invite them, then assign the task.",+ ]);++ const projectId = imported?.projectId ?? "";+ const [project] = await db+ .select()+ .from(schema.projectTable)+ .where(eq(schema.projectTable.workspaceId, workspaceId));+ expect(project).toMatchObject({+ id: projectId,+ name: "Website Relaunch",+ slug: "WR",+ description: "Everything for the relaunch",+ lastTaskNumber: 5,+ });++ const columns = await db+ .select()+ .from(schema.columnTable)+ .where(eq(schema.columnTable.projectId, projectId))+ .orderBy(asc(schema.columnTable.position));+ expect(+ columns.map(({ name, slug, position, isFinal }) => ({+ name,+ slug,+ position,+ isFinal,+ })),+ ).toEqual([+ { name: "Backlog", slug: "backlog", position: 0, isFinal: false },+ { name: "Doing", slug: "doing", position: 1, isFinal: false },+ { name: "Shipped", slug: "shipped", position: 2, isFinal: true },+ {+ name: "Planned list",+ slug: "planned-list",+ position: 3,+ isFinal: false,+ },+ ]);+ const columnId = (slug: string) =>+ columns.find((column) => column.slug === slug)?.id;++ const tasks = await db+ .select()+ .from(schema.taskTable)+ .where(eq(schema.taskTable.projectId, projectId))+ .orderBy(asc(schema.taskTable.number));+ expect(+ tasks.map((task) => ({+ number: task.number,+ title: task.title,+ status: task.status,+ columnId: task.columnId,+ position: task.position,+ priority: task.priority,+ userId: task.userId,+ })),+ ).toEqual([+ {+ number: 1,+ title: "Write the copy",+ status: "backlog",+ columnId: columnId("backlog"),+ position: 1,+ priority: "high",+ userId: member.id,+ },+ {+ number: 2,+ title: "Untitled task",+ status: "backlog",+ columnId: columnId("backlog"),+ position: 2,+ priority: "no-priority",+ userId: null,+ },+ {+ number: 3,+ title: "Someday",+ status: "planned",+ columnId: null,+ position: 1,+ priority: "low",+ userId: null,+ },+ {+ number: 4,+ title: "Old launch",+ status: "archived",+ columnId: null,+ position: 1,+ priority: "no-priority",+ userId: null,+ },+ {+ number: 5,+ title: "Ship it",+ status: "shipped",+ columnId: columnId("shipped"),+ position: 1,+ priority: "urgent",+ userId: null,+ },+ ]);+ const [first, , someday, , shipIt] = tasks;+ expect(first?.description).toBe("Draft **all** pages");+ expect(first?.createdAt.toISOString()).toBe("2023-05-06T07:08:09.000Z");+ expect(first?.dueDate?.toISOString()).toBe("2024-02-01T00:00:00.000Z");++ const definitions = await db+ .select({ name: schema.labelTable.name, color: schema.labelTable.color })+ .from(schema.labelTable)+ .where(+ and(+ eq(schema.labelTable.workspaceId, workspaceId),+ isNull(schema.labelTable.taskId),+ ),+ )+ .orderBy(asc(schema.labelTable.name));+ expect(definitions).toEqual([+ { name: "Bug", color: "#123456" },+ { name: "Design", color: "purple" },+ ]);+ const taskLabels = await db+ .select({+ taskId: schema.labelTable.taskId,+ name: schema.labelTable.name,+ color: schema.labelTable.color,+ })+ .from(schema.labelTable)+ .where(+ inArray(+ schema.labelTable.taskId,+ tasks.map((task) => task.id),+ ),+ )+ .orderBy(asc(schema.labelTable.name));+ expect(taskLabels).toEqual(+ expect.arrayContaining([+ { taskId: first?.id, name: "Bug", color: "#123456" },+ { taskId: first?.id, name: "Design", color: "purple" },+ { taskId: shipIt?.id, name: "Bug", color: "#123456" },+ ]),+ );+ expect(taskLabels).toHaveLength(3);++ const activities = await db+ .select()+ .from(schema.activityTable)+ .where(+ inArray(+ schema.activityTable.taskId,+ tasks.map((task) => task.id),+ ),+ );+ const created = activities.filter(+ (activity) => activity.type === "created",+ );+ expect(created).toHaveLength(5);+ expect(created.every((activity) => activity.userId === admin.user.id)).toBe(+ true,+ );+ expect(+ created.find((activity) => activity.taskId === first?.id)?.createdAt,+ ).toEqual(first?.createdAt);+ const comments = activities+ .filter((activity) => activity.type === "comment")+ .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());+ expect(+ comments.map((comment) => ({+ taskId: comment.taskId,+ userId: comment.userId,+ content: comment.content,+ externalUserName: comment.externalUserName,+ externalSource: comment.externalSource,+ })),+ ).toEqual([+ {+ taskId: first?.id,+ userId: admin.user.id,+ content: "Looks good",+ externalUserName: "Ana",+ externalSource: "planka",+ },+ {+ taskId: first?.id,+ userId: admin.user.id,+ content: "No author",+ externalUserName: "Unknown user",+ externalSource: "planka",+ },+ ]);+ expect(comments[0]?.createdAt.toISOString()).toBe(+ "2024-01-02T03:04:05.000Z",+ );++ const relations = await db+ .select({+ sourceTaskId: schema.taskRelationTable.sourceTaskId,+ targetTaskId: schema.taskRelationTable.targetTaskId,+ relationType: schema.taskRelationTable.relationType,+ })+ .from(schema.taskRelationTable)+ .where(+ inArray(+ schema.taskRelationTable.sourceTaskId,+ tasks.map((task) => task.id),+ ),+ );+ expect(relations).toEqual(+ expect.arrayContaining([+ {+ sourceTaskId: first?.id,+ targetTaskId: shipIt?.id,+ relationType: "subtask",+ },+ {+ sourceTaskId: first?.id,+ targetTaskId: someday?.id,+ relationType: "blocks",+ },+ ]),+ );+ expect(relations).toHaveLength(2);++ const notifications = await db.select().from(schema.notificationTable);+ expect(notifications).toEqual([]);++ const [storedRun] = await db+ .select()+ .from(schema.importRunTable)+ .where(eq(schema.importRunTable.id, run.id));+ expect(storedRun?.userId).toBe(admin.user.id);+ expect(JSON.stringify(storedRun)).not.toContain(SECRET);++ const listed = await get(`/runs/${workspaceId}`);+ expect(listed.status).toBe(200);+ const listedText = await listed.text();+ expect(listedText).not.toContain(SECRET);+ expect(JSON.parse(listedText).runs).toHaveLength(1);+ });++ it("keeps the source key and task numbers", async () => {+ const admin = await createAdmin();+ const workspaceId = admin.workspace.id;+ importers.connectSource.mockResolvedValue(+ fakeSource(async () => numberedProject()),+ );+ mockAuthenticatedSession(admin.user);++ const imported = await importProject(workspaceId);+ expect(imported.projectSlug).toBe("ENG");++ const [project] = await db+ .select()+ .from(schema.projectTable)+ .where(eq(schema.projectTable.id, imported.projectId));+ expect(project).toMatchObject({ slug: "ENG", lastTaskNumber: 9 });++ const tasks = await db+ .select()+ .from(schema.taskTable)+ .where(eq(schema.taskTable.projectId, imported.projectId))+ .orderBy(asc(schema.taskTable.number));+ expect(+ tasks.map(({ number, title, status, position }) => ({+ number,+ title,+ status,+ position,+ })),+ ).toEqual([+ { number: 3, title: "Three", status: "to-do", position: 3 },+ { number: 7, title: "Seven", status: "to-do", position: 1 },+ { number: 8, title: "No number", status: "to-do", position: 2 },+ { number: 9, title: "Another seven", status: "to-do", position: 4 },+ ]);++ const created = await createApp().app.request(+ `/api/task/${imported.projectId}`,+ {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ title: "Made after the import",+ description: "",+ priority: "low",+ status: "to-do",+ }),+ },+ );+ expect(created.status).toBe(200);+ expect(((await created.json()) as { number: number }).number).toBe(10);+ });++ it("suffixes the source key when the workspace already uses it", async () => {+ const admin = await createAdmin();+ const workspaceId = admin.workspace.id;+ await createProjectFixture({ workspaceId, name: "Existing", slug: "ENG" });+ importers.connectSource.mockResolvedValue(+ fakeSource(async () => numberedProject()),+ );+ mockAuthenticatedSession(admin.user);++ const imported = await importProject(workspaceId);++ expect(imported.projectSlug).toBe("ENG-2");+ const [project] = await db+ .select({ slug: schema.projectTable.slug })+ .from(schema.projectTable)+ .where(eq(schema.projectTable.id, imported.projectId));+ expect(project?.slug).toBe("ENG-2");+ });++ it("refuses members and viewers", async () => {+ const admin = await createAdmin();+ const workspaceId = admin.workspace.id;+ const member = await addMember(workspaceId, "Member");+ const viewer = await addMember(workspaceId, "Viewer", "viewer");++ for (const user of [member, viewer]) {+ mockAuthenticatedSession(user);+ const listed = await post("/projects", { workspaceId, connection });+ expect(listed.status).toBe(403);+ const started = await post("/runs", {+ workspaceId,+ connection,+ projectIds: ["p1"],+ });+ expect(started.status).toBe(403);+ expect((await get(`/runs/${workspaceId}`)).status).toBe(403);+ expect((await get(`/trello/authorize-url/${workspaceId}`)).status).toBe(+ 403,+ );+ vi.restoreAllMocks();+ }++ expect(importers.connectSource).not.toHaveBeenCalled();+ });++ it("links admins to Trello's authorize page only when the server has a key", async () => {+ const admin = await createAdmin();+ const workspaceId = admin.workspace.id;+ mockAuthenticatedSession(admin.user);++ vi.stubEnv("TRELLO_API_KEY", "");+ const unset = await get(`/trello/authorize-url/${workspaceId}`);+ expect(unset.status).toBe(200);+ expect(await unset.json()).toEqual({ authorizeUrl: null });++ vi.stubEnv("TRELLO_API_KEY", " trello-app-key ");+ const set = await get(`/trello/authorize-url/${workspaceId}`);+ expect(set.status).toBe(200);+ const body = (await set.json()) as Record<string, unknown>;+ expect(Object.keys(body)).toEqual(["authorizeUrl"]);+ const url = new URL(String(body.authorizeUrl));+ expect(url.origin + url.pathname).toBe("https://trello.com/1/authorize");+ expect(url.searchParams.get("key")).toBe("trello-app-key");+ expect(url.searchParams.get("scope")).toBe("read");++ const config = await createApp().app.request("/api/config");+ expect(await config.text()).not.toContain("trello-app-key");+ vi.unstubAllEnvs();+ });++ it("allows one running import per workspace", async () => {+ const admin = await createAdmin();+ const workspaceId = admin.workspace.id;+ await db.insert(schema.importRunTable).values({+ workspaceId,+ userId: admin.user.id,+ source: "linear",+ projects: [],+ });+ importers.connectSource.mockResolvedValue(+ fakeSource(async () => plankaProject("")),+ );+ mockAuthenticatedSession(admin.user);++ const response = await post("/runs", {+ workspaceId,+ connection,+ projectIds: ["p1"],+ });++ expect(response.status).toBe(409);+ expect(importers.connectSource).not.toHaveBeenCalled();+ });++ it("reports and settles a run whose server stopped answering", async () => {+ const admin = await createAdmin();+ const workspaceId = admin.workspace.id;+ const [stale] = await db+ .insert(schema.importRunTable)+ .values({+ workspaceId,+ userId: admin.user.id,+ source: "trello",+ projects: [+ {+ sourceId: "b1",+ name: "Board",+ status: "running",+ projectId: null,+ projectSlug: null,+ counts: {+ columns: 0,+ tasks: 0,+ labels: 0,+ comments: 0,+ assignees: 0,+ relations: 0,+ },+ warnings: [],+ error: null,+ },+ ],+ heartbeatAt: new Date(Date.now() - 5 * 60_000),+ })+ .returning();+ mockAuthenticatedSession(admin.user);++ const response = await get(`/runs/${workspaceId}`);++ expect(response.status).toBe(200);+ const { runs } = (await response.json()) as {+ runs: { status: string; error: string; projects: { status: string }[] }[];+ };+ expect(runs[0]).toMatchObject({+ status: "failed",+ error: "The import was interrupted before it finished.",+ projects: [{ status: "failed" }],+ });+ const [stored] = await db+ .select()+ .from(schema.importRunTable)+ .where(eq(schema.importRunTable.id, stale?.id ?? ""));+ expect(stored?.status).toBe("failed");+ expect(stored?.finishedAt).not.toBeNull();+ });++ it("limits how many imports one server runs at once", async () => {+ let release: () => void = () => {};+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ importers.connectSource.mockImplementation(async () =>+ fakeSource(async () => {+ await gate;+ return { ...plankaProject(""), tasks: [], relations: [] };+ }),+ );++ try {+ for (let index = 0; index < 2; index++) {+ const admin = await createAdmin();+ mockAuthenticatedSession(admin.user);+ const response = await post("/runs", {+ workspaceId: admin.workspace.id,+ connection,+ projectIds: ["p1"],+ });+ expect(response.status).toBe(202);+ vi.restoreAllMocks();+ }++ const third = await createAdmin();+ mockAuthenticatedSession(third.user);+ const response = await post("/runs", {+ workspaceId: third.workspace.id,+ connection,+ projectIds: ["p1"],+ });+ expect(response.status).toBe(429);+ } finally {+ release();+ await waitForActiveImports();+ }+ });++ it("rejects projects the source does not list and runs from other workspaces", async () => {+ const admin = await createAdmin();+ const other = await createAdmin();+ const [foreign] = await db+ .insert(schema.importRunTable)+ .values({+ workspaceId: other.workspace.id,+ source: "planka",+ projects: [],+ status: "completed",+ })+ .returning();+ importers.connectSource.mockResolvedValue(+ fakeSource(async () => plankaProject("")),+ );+ mockAuthenticatedSession(admin.user);++ const missing = await post("/runs", {+ workspaceId: admin.workspace.id,+ connection,+ projectIds: ["p9"],+ });+ expect(missing.status).toBe(400);+ expect((await readErrorBody(missing)).message).toBe(+ "A selected project is no longer available in PLANKA. Refresh the list and try again.",+ );++ const duplicate = await post("/runs", {+ workspaceId: admin.workspace.id,+ connection,+ projectIds: ["p1", "p1"],+ });+ expect(duplicate.status).toBe(400);++ const notHere = await get(`/runs/${admin.workspace.id}/${foreign?.id}`);+ expect(notHere.status).toBe(404);+ });+});