{"version":3,"file":"prepare.mjs","names":[],"sources":["../../../../../../src/astro/routes/api/import/wordpress/prepare.ts"],"sourcesContent":["/**\n * WordPress import prepare endpoint\n *\n * POST /_emdash/api/import/wordpress/prepare\n *\n * Creates collections and fields needed for import.\n * This is called after analyze, before execute.\n */\n\nimport type { APIRoute } from \"astro\";\n\nimport { requirePerm } from \"#api/authorize.js\";\nimport { apiError, apiSuccess, handleError } from \"#api/error.js\";\nimport { isParseError, parseBody } from \"#api/parse.js\";\nimport { wpPrepareBody } from \"#api/schemas.js\";\nimport { FIELD_TYPES, type FieldType } from \"#schema/types.js\";\nimport type { EmDashHandlers } from \"#types\";\n\nimport { capitalize, sanitizeSlug, singularize, type ImportFieldDef } from \"./analyze.js\";\n\n/** Validate that a string is a known FieldType, returning undefined if not */\nfunction asFieldType(value: string): FieldType | undefined {\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- validated by includes check\n\treturn (FIELD_TYPES as readonly string[]).includes(value) ? (value as FieldType) : undefined;\n}\n\nexport const prerender = false;\n\ninterface PrepareRequest {\n\tpostTypes: Array<{\n\t\tname: string;\n\t\tcollection: string;\n\t\tfields: ImportFieldDef[];\n\t}>;\n}\n\nexport interface PrepareResult {\n\tsuccess: boolean;\n\tcollectionsCreated: string[];\n\tfieldsCreated: Array<{ collection: string; field: string }>;\n\terrors: Array<{ collection: string; error: string }>;\n}\n\nexport const POST: APIRoute = async ({ request, locals }) => {\n\tconst { emdash, user } = locals;\n\n\tif (!emdash?.db) {\n\t\treturn apiError(\"NOT_CONFIGURED\", \"EmDash not configured\", 500);\n\t}\n\n\tconst denied = requirePerm(user, \"import:execute\");\n\tif (denied) return denied;\n\n\ttry {\n\t\tconst body = await parseBody(request, wpPrepareBody);\n\t\tif (isParseError(body)) return body;\n\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- Zod schema output narrowed to PrepareRequest\n\t\tconst result = await prepareImport(emdash.db, body as PrepareRequest);\n\n\t\t// Invalidate the URL pattern cache when prepare adds new collections so\n\t\t// public routing picks up their patterns immediately. The manifest\n\t\t// itself is built fresh per admin request, so cross-request\n\t\t// staleness (the original failure mode in #747) is no longer\n\t\t// possible — the execute step always reads live schema.\n\t\tif (result.collectionsCreated.length > 0) {\n\t\t\temdash.invalidateUrlPatternCache();\n\t\t}\n\n\t\treturn apiSuccess(result, result.success ? 200 : 400);\n\t} catch (error) {\n\t\treturn handleError(error, \"Failed to prepare import\", \"WXR_PREPARE_ERROR\");\n\t}\n};\n\nasync function prepareImport(\n\tdb: NonNullable<EmDashHandlers[\"db\"]>,\n\trequest: PrepareRequest,\n): Promise<PrepareResult> {\n\tconst { SchemaRegistry } = await import(\"#schema/registry.js\");\n\tconst registry = new SchemaRegistry(db);\n\n\tconst result: PrepareResult = {\n\t\tsuccess: true,\n\t\tcollectionsCreated: [],\n\t\tfieldsCreated: [],\n\t\terrors: [],\n\t};\n\n\tfor (const postType of request.postTypes) {\n\t\tconst collectionSlug = sanitizeSlug(postType.collection);\n\n\t\ttry {\n\t\t\t// Check if collection exists\n\t\t\tlet collection = await registry.getCollection(collectionSlug);\n\n\t\t\tif (!collection) {\n\t\t\t\t// Create the collection\n\t\t\t\tconst label = capitalize(collectionSlug);\n\t\t\t\tconst labelSingular = capitalize(singularize(collectionSlug));\n\n\t\t\t\t// Enable search by default for posts and pages\n\t\t\t\tconst isSearchable = [\"posts\", \"pages\", \"post\", \"page\"].includes(collectionSlug);\n\t\t\t\tconst supports: (\"revisions\" | \"drafts\" | \"search\")[] = [\"revisions\", \"drafts\"];\n\t\t\t\tif (isSearchable) {\n\t\t\t\t\tsupports.push(\"search\");\n\t\t\t\t}\n\n\t\t\t\t// Default URL patterns for known post types\n\t\t\t\tconst urlPattern =\n\t\t\t\t\tcollectionSlug === \"pages\"\n\t\t\t\t\t\t? \"/{slug}\"\n\t\t\t\t\t\t: collectionSlug === \"posts\"\n\t\t\t\t\t\t\t? \"/blog/{slug}\"\n\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\tcollection = await registry.createCollection({\n\t\t\t\t\tslug: collectionSlug,\n\t\t\t\t\tlabel,\n\t\t\t\t\tlabelSingular,\n\t\t\t\t\tdescription: `Imported from WordPress post type: ${postType.name}`,\n\t\t\t\t\tsupports,\n\t\t\t\t\turlPattern,\n\t\t\t\t});\n\n\t\t\t\tresult.collectionsCreated.push(collectionSlug);\n\t\t\t}\n\n\t\t\t// Create missing fields\n\t\t\tconst existingFields = await registry.listFields(collection.id);\n\t\t\tconst existingFieldSlugs = new Set(existingFields.map((f) => f.slug));\n\n\t\t\tfor (const field of postType.fields) {\n\t\t\t\tif (existingFieldSlugs.has(field.slug)) {\n\t\t\t\t\t// Field already exists - skip\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst fieldType = asFieldType(field.type);\n\t\t\t\tif (!fieldType) {\n\t\t\t\t\tresult.errors.push({\n\t\t\t\t\t\tcollection: collectionSlug,\n\t\t\t\t\t\terror: `Unknown field type \"${field.type}\" for field \"${field.slug}\"`,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tawait registry.createField(collectionSlug, {\n\t\t\t\t\tslug: field.slug,\n\t\t\t\t\tlabel: field.label,\n\t\t\t\t\ttype: fieldType,\n\t\t\t\t\trequired: field.required,\n\t\t\t\t\tunique: false,\n\t\t\t\t\tsearchable: field.searchable ?? false,\n\t\t\t\t\tsortOrder: existingFields.length + result.fieldsCreated.length,\n\t\t\t\t});\n\n\t\t\t\tresult.fieldsCreated.push({\n\t\t\t\t\tcollection: collectionSlug,\n\t\t\t\t\tfield: field.slug,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Enable search if collection supports it and has searchable fields\n\t\t\tconst isSearchable = [\"posts\", \"pages\", \"post\", \"page\"].includes(collectionSlug);\n\t\t\tif (isSearchable) {\n\t\t\t\tconst { FTSManager } = await import(\"#search/fts-manager.js\");\n\t\t\t\tconst ftsManager = new FTSManager(db);\n\n\t\t\t\tconst searchableFields = await ftsManager.getSearchableFields(collectionSlug);\n\t\t\t\tif (searchableFields.length > 0) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait ftsManager.enableSearch(collectionSlug);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Ignore - search can be enabled manually later\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(`Prepare error for collection \"${collectionSlug}\":`, error);\n\t\t\tresult.success = false;\n\t\t\tresult.errors.push({\n\t\t\t\tcollection: collectionSlug,\n\t\t\t\terror: \"Failed to prepare collection\",\n\t\t\t});\n\t\t}\n\t}\n\n\treturn result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,SAAS,YAAY,OAAsC;AAE1D,QAAQ,YAAkC,SAAS,MAAM,GAAI,QAAsB;;AAGpF,MAAa,YAAY;AAiBzB,MAAa,OAAiB,OAAO,EAAE,SAAS,aAAa;CAC5D,MAAM,EAAE,QAAQ,SAAS;AAEzB,KAAI,CAAC,QAAQ,GACZ,QAAO,SAAS,kBAAkB,yBAAyB,IAAI;CAGhE,MAAM,SAAS,YAAY,MAAM,iBAAiB;AAClD,KAAI,OAAQ,QAAO;AAEnB,KAAI;EACH,MAAM,OAAO,MAAM,UAAU,SAAS,cAAc;AACpD,MAAI,aAAa,KAAK,CAAE,QAAO;EAG/B,MAAM,SAAS,MAAM,cAAc,OAAO,IAAI,KAAuB;AAOrE,MAAI,OAAO,mBAAmB,SAAS,EACtC,QAAO,2BAA2B;AAGnC,SAAO,WAAW,QAAQ,OAAO,UAAU,MAAM,IAAI;UAC7C,OAAO;AACf,SAAO,YAAY,OAAO,4BAA4B,oBAAoB;;;AAI5E,eAAe,cACd,IACA,SACyB;CACzB,MAAM,EAAE,mBAAmB,MAAM,OAAO;CACxC,MAAM,WAAW,IAAI,eAAe,GAAG;CAEvC,MAAM,SAAwB;EAC7B,SAAS;EACT,oBAAoB,EAAE;EACtB,eAAe,EAAE;EACjB,QAAQ,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