{"version":3,"file":"context-Dp9WNshw.mjs","names":["GH","B64_NEWLINES","b64encode","b64decode"],"sources":["../src/plugins/storage-query.ts","../src/database/repositories/plugin-storage.ts","../src/content/git-store.ts","../src/plugins/git-storage.ts","../src/plugins/context.ts"],"sourcesContent":["/**\n * Plugin Storage Query Validation and Building\n *\n * Validates that queries only use indexed fields and builds SQL WHERE clauses.\n *\n * @see PLUGIN-SYSTEM.md § Plugin Storage > Query Validation\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { pluginDataExtractExpr, pluginDataOrderExpr } from \"../database/dialect-helpers.js\";\nimport type { WhereClause, WhereValue, RangeFilter, InFilter, StartsWithFilter } from \"./types.js\";\n\n/**\n * Error thrown when querying non-indexed fields\n */\nexport class StorageQueryError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic field?: string,\n\t\tpublic suggestion?: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"StorageQueryError\";\n\t}\n}\n\n/**\n * Check if a value is a range filter\n */\nexport function isRangeFilter(value: WhereValue): value is RangeFilter {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"gt\" in value || \"gte\" in value || \"lt\" in value || \"lte\" in value;\n}\n\n/**\n * Check if a value is an IN filter\n */\nexport function isInFilter(value: WhereValue): value is InFilter {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"in\" in value && Array.isArray(value.in);\n}\n\n/**\n * Check if a value is a startsWith filter\n */\nexport function isStartsWithFilter(value: WhereValue): value is StartsWithFilter {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"startsWith\" in value && typeof value.startsWith === \"string\";\n}\n\n/**\n * Escape LIKE pattern metacharacters so a startsWith prefix matches\n * literally. Without this, `%` and `_` in the prefix act as wildcards\n * (e.g. `{ startsWith: \"50%\" }` would match \"50x off\").\n */\nexport function escapeLikePattern(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"%\", \"\\\\%\").replaceAll(\"_\", \"\\\\_\");\n}\n\n/**\n * Get the set of indexed fields from index declarations\n */\nexport function getIndexedFields(indexes: Array<string | string[]>): Set<string> {\n\tconst fields = new Set<string>();\n\tfor (const index of indexes) {\n\t\tif (Array.isArray(index)) {\n\t\t\tfor (const field of index) {\n\t\t\t\tfields.add(field);\n\t\t\t}\n\t\t} else {\n\t\t\tfields.add(index);\n\t\t}\n\t}\n\treturn fields;\n}\n\n/**\n * Validate that all fields in a where clause are indexed\n */\nexport function validateWhereClause(\n\twhere: WhereClause,\n\tindexedFields: Set<string>,\n\tpluginId: string,\n\tcollection: string,\n): void {\n\tfor (const field of Object.keys(where)) {\n\t\tif (!indexedFields.has(field)) {\n\t\t\tthrow new StorageQueryError(\n\t\t\t\t`Cannot query on non-indexed field '${field}'.`,\n\t\t\t\tfield,\n\t\t\t\t`Add '${field}' to storage.${collection}.indexes in plugin '${pluginId}' to enable this query.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Validate orderBy fields are indexed\n */\nexport function validateOrderByClause(\n\torderBy: Record<string, \"asc\" | \"desc\">,\n\tindexedFields: Set<string>,\n\tpluginId: string,\n\tcollection: string,\n): void {\n\tfor (const field of Object.keys(orderBy)) {\n\t\tif (!indexedFields.has(field)) {\n\t\t\tthrow new StorageQueryError(\n\t\t\t\t`Cannot order by non-indexed field '${field}'.`,\n\t\t\t\tfield,\n\t\t\t\t`Add '${field}' to storage.${collection}.indexes in plugin '${pluginId}' to enable ordering by this field.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * SQL expression for extracting a queryable field from the `_plugin_storage.data`\n * column.\n *\n * Delegates to `pluginDataExtractExpr`, which validates the field name before\n * interpolation and applies the dialect-correct extraction: a `::jsonb` cast on\n * Postgres (the `data` column is `text`) plus an optional type-guarded\n * `::numeric` cast so numeric comparisons don't fall back to lexical text\n * ordering.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function jsonExtract(\n\tdb: Kysely<any>,\n\tfield: string,\n\toptions?: { numeric?: boolean },\n): string {\n\treturn pluginDataExtractExpr(db, field, options);\n}\n\n/**\n * SQL expression for ordering by a `_plugin_storage.data` field.\n *\n * Delegates to `pluginDataOrderExpr`, which orders over the jsonb-native value\n * on Postgres so numeric fields sort numerically (not lexically) while staying\n * total across heterogeneous data. SQLite keeps `json_extract` (already numeric).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function jsonOrderExtract(db: Kysely<any>, field: string): string {\n\treturn pluginDataOrderExpr(db, field);\n}\n\n/**\n * Build a WHERE clause condition for a single field\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildCondition(\n\tdb: Kysely<any>,\n\tfield: string,\n\tvalue: WhereValue,\n): { sql: string; params: unknown[] } {\n\t// Numeric-vs-text is decided per condition from the JS type of the bound\n\t// value. On Postgres a text extract compared to a bound number would sort\n\t// lexically (`'9' >= '10'` is TRUE); a type-guarded `::numeric` cast on the\n\t// extract fixes it. String/boolean operands keep text comparison. SQLite is\n\t// unaffected — `json_extract` already returns a typed value.\n\tconst extractFor = (numeric: boolean): string => jsonExtract(db, field, { numeric });\n\n\tif (value === null) {\n\t\treturn { sql: `${extractFor(false)} IS NULL`, params: [] };\n\t}\n\n\tif (typeof value === \"number\") {\n\t\treturn { sql: `${extractFor(true)} = ?`, params: [value] };\n\t}\n\n\tif (typeof value === \"string\") {\n\t\treturn { sql: `${extractFor(false)} = ?`, params: [value] };\n\t}\n\n\tif (typeof value === \"boolean\") {\n\t\t// JSON booleans are stored as true/false strings\n\t\treturn { sql: `${extractFor(false)} = ?`, params: [value] };\n\t}\n\n\tif (isInFilter(value)) {\n\t\tconst numeric = value.in.length > 0 && value.in.every((v) => typeof v === \"number\");\n\t\tconst placeholders = value.in.map(() => \"?\").join(\", \");\n\t\treturn {\n\t\t\tsql: `${extractFor(numeric)} IN (${placeholders})`,\n\t\t\tparams: value.in,\n\t\t};\n\t}\n\n\tif (isStartsWithFilter(value)) {\n\t\t// ESCAPE '\\' works on both SQLite and PostgreSQL. startsWith is a string\n\t\t// operation, so always compare as text.\n\t\treturn {\n\t\t\tsql: `${extractFor(false)} LIKE ? ESCAPE '\\\\'`,\n\t\t\tparams: [`${escapeLikePattern(value.startsWith)}%`],\n\t\t};\n\t}\n\n\tif (isRangeFilter(value)) {\n\t\tconst conditions: string[] = [];\n\t\tconst params: unknown[] = [];\n\n\t\t// Each bound is cast to numeric only when its own operand is a number, so\n\t\t// a mixed range (e.g. a string lower bound) stays correct per side.\n\t\tconst pushBound = (op: string, bound: string | number): void => {\n\t\t\tconditions.push(`${extractFor(typeof bound === \"number\")} ${op} ?`);\n\t\t\tparams.push(bound);\n\t\t};\n\n\t\tif (value.gt !== undefined) pushBound(\">\", value.gt);\n\t\tif (value.gte !== undefined) pushBound(\">=\", value.gte);\n\t\tif (value.lt !== undefined) pushBound(\"<\", value.lt);\n\t\tif (value.lte !== undefined) pushBound(\"<=\", value.lte);\n\n\t\treturn {\n\t\t\tsql: conditions.join(\" AND \"),\n\t\t\tparams,\n\t\t};\n\t}\n\n\tthrow new StorageQueryError(`Unknown filter type for field '${field}'`);\n}\n\n/**\n * Build a complete WHERE clause from a WhereClause object\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildWhereClause(\n\tdb: Kysely<any>,\n\twhere: WhereClause,\n): {\n\tsql: string;\n\tparams: unknown[];\n} {\n\tconst conditions: string[] = [];\n\tconst params: unknown[] = [];\n\n\tfor (const [field, value] of Object.entries(where)) {\n\t\tconst condition = buildCondition(db, field, value);\n\t\tconditions.push(condition.sql);\n\t\tparams.push(...condition.params);\n\t}\n\n\tif (conditions.length === 0) {\n\t\treturn { sql: \"\", params: [] };\n\t}\n\n\treturn {\n\t\tsql: conditions.join(\" AND \"),\n\t\tparams,\n\t};\n}\n\n/**\n * Build ORDER BY clause\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildOrderByClause(\n\tdb: Kysely<any>,\n\torderBy: Record<string, \"asc\" | \"desc\">,\n): string {\n\tconst clauses: string[] = [];\n\n\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\tclauses.push(`${jsonOrderExtract(db, field)} ${direction.toUpperCase()}`);\n\t}\n\n\tif (clauses.length === 0) {\n\t\treturn \"\";\n\t}\n\n\treturn `ORDER BY ${clauses.join(\", \")}`;\n}\n","/**\n * Plugin Storage Repository\n *\n * Provides a document store API for plugin data storage.\n * Uses a single _plugin_storage table with JSON documents and expression indexes.\n *\n * @see PLUGIN-SYSTEM.md § Plugin Storage > Full API Reference\n */\n\nimport type { Kysely, RawBuilder } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport {\n\tbuildWhereClause,\n\tvalidateWhereClause,\n\tvalidateOrderByClause,\n\tgetIndexedFields,\n\tjsonOrderExtract,\n} from \"../../plugins/storage-query.js\";\nimport type {\n\tStorageCollection,\n\tQueryOptions,\n\tPaginatedResult,\n\tWhereClause,\n} from \"../../plugins/types.js\";\nimport { withTransaction } from \"../transaction.js\";\nimport type { Database } from \"../types.js\";\nimport { encodeCursor, decodeCursor } from \"./types.js\";\n\n/**\n * Interleave a `?`-placeholder SQL string with its params into a single\n * boolean raw expression. Used as a WHERE predicate directly — wrapping it\n * in `(...) = 1` breaks on Postgres, which has a strict boolean type (#920).\n */\nfunction rawWhereExpr(sqlText: string, params: unknown[]): RawBuilder<boolean> {\n\tconst parts: ReturnType<typeof sql>[] = [];\n\tlet paramIndex = 0;\n\tconst sqlParts = sqlText.split(\"?\");\n\tfor (let i = 0; i < sqlParts.length; i++) {\n\t\tif (i > 0) {\n\t\t\tparts.push(sql`${params[paramIndex++]}`);\n\t\t}\n\t\tif (sqlParts[i]) {\n\t\t\tparts.push(sql.raw(sqlParts[i]));\n\t\t}\n\t}\n\treturn sql<boolean>`(${sql.join(parts, sql.raw(\"\"))})`;\n}\n\n/**\n * Plugin Storage Repository\n *\n * Implements the StorageCollection interface for a specific plugin and collection.\n */\nexport class PluginStorageRepository<T = unknown> implements StorageCollection<T> {\n\tprivate indexedFields: Set<string>;\n\n\tconstructor(\n\t\tprivate db: Kysely<Database>,\n\t\tprivate pluginId: string,\n\t\tprivate collection: string,\n\t\tindexes: Array<string | string[]>,\n\t) {\n\t\tthis.indexedFields = getIndexedFields(indexes);\n\t}\n\n\t/**\n\t * Get a document by ID\n\t */\n\tasync get(id: string): Promise<T | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select(\"data\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) return null;\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- JSON.parse returns any; generic callers provide T\n\t\treturn JSON.parse(row.data) as T;\n\t}\n\n\t/**\n\t * Store a document\n\t */\n\tasync put(id: string, data: T): Promise<void> {\n\t\tconst now = new Date().toISOString();\n\t\tconst jsonData = JSON.stringify(data);\n\n\t\tawait this.db\n\t\t\t.insertInto(\"_plugin_storage\")\n\t\t\t.values({\n\t\t\t\tplugin_id: this.pluginId,\n\t\t\t\tcollection: this.collection,\n\t\t\t\tid,\n\t\t\t\tdata: jsonData,\n\t\t\t\tcreated_at: now,\n\t\t\t\tupdated_at: now,\n\t\t\t})\n\t\t\t.onConflict((oc) =>\n\t\t\t\toc.columns([\"plugin_id\", \"collection\", \"id\"]).doUpdateSet({\n\t\t\t\t\tdata: jsonData,\n\t\t\t\t\tupdated_at: now,\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.execute();\n\t}\n\n\t/**\n\t * Delete a document\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_plugin_storage\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn (result.numDeletedRows ?? 0) > 0;\n\t}\n\n\t/**\n\t * Check if a document exists\n\t */\n\tasync exists(id: string): Promise<boolean> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn !!row;\n\t}\n\n\t/**\n\t * Get multiple documents by ID\n\t */\n\tasync getMany(ids: string[]): Promise<Map<string, T>> {\n\t\tif (ids.length === 0) return new Map();\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select([\"id\", \"data\"])\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"in\", ids)\n\t\t\t.execute();\n\n\t\tconst result = new Map<string, T>();\n\t\tfor (const row of rows) {\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- JSON.parse returns any; generic callers provide T\n\t\t\tresult.set(row.id, JSON.parse(row.data) as T);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Store multiple documents\n\t */\n\tasync putMany(items: Array<{ id: string; data: T }>): Promise<void> {\n\t\tif (items.length === 0) return;\n\n\t\tconst now = new Date().toISOString();\n\n\t\t// SQLite doesn't support batch upserts well, so we do them one at a time\n\t\t// In a transaction for atomicity\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tfor (const item of items) {\n\t\t\t\tconst jsonData = JSON.stringify(item.data);\n\t\t\t\tawait trx\n\t\t\t\t\t.insertInto(\"_plugin_storage\")\n\t\t\t\t\t.values({\n\t\t\t\t\t\tplugin_id: this.pluginId,\n\t\t\t\t\t\tcollection: this.collection,\n\t\t\t\t\t\tid: item.id,\n\t\t\t\t\t\tdata: jsonData,\n\t\t\t\t\t\tcreated_at: now,\n\t\t\t\t\t\tupdated_at: now,\n\t\t\t\t\t})\n\t\t\t\t\t.onConflict((oc) =>\n\t\t\t\t\t\toc.columns([\"plugin_id\", \"collection\", \"id\"]).doUpdateSet({\n\t\t\t\t\t\t\tdata: jsonData,\n\t\t\t\t\t\t\tupdated_at: now,\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t\t.execute();\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Delete multiple documents\n\t */\n\tasync deleteMany(ids: string[]): Promise<number> {\n\t\tif (ids.length === 0) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_plugin_storage\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"in\", ids)\n\t\t\t.executeTakeFirst();\n\n\t\treturn Number(result.numDeletedRows ?? 0);\n\t}\n\n\t/**\n\t * Query documents with filters\n\t */\n\tasync query(options: QueryOptions = {}): Promise<PaginatedResult<{ id: string; data: T }>> {\n\t\tconst { where = {}, orderBy = {}, cursor } = options;\n\t\tconst limit = Math.min(options.limit ?? 50, 100);\n\n\t\t// Validate that all queried fields are indexed\n\t\tvalidateWhereClause(where, this.indexedFields, this.pluginId, this.collection);\n\t\tif (Object.keys(orderBy).length > 0) {\n\t\t\tvalidateOrderByClause(orderBy, this.indexedFields, this.pluginId, this.collection);\n\t\t}\n\n\t\t// Build base query\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select([\"id\", \"data\", \"created_at\"])\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection);\n\n\t\t// Add JSON extraction WHERE conditions\n\t\tconst whereResult = buildWhereClause(this.db, where);\n\t\tif (whereResult.sql) {\n\t\t\tquery = query.where(rawWhereExpr(whereResult.sql, whereResult.params));\n\t\t}\n\n\t\t// Handle cursor-based pagination — throws on invalid cursor.\n\t\tif (cursor) {\n\t\t\tconst decoded = decodeCursor(cursor);\n\t\t\tquery = query.where(({ eb }) =>\n\t\t\t\teb(sql`(created_at, id)`, \">\", sql`(${decoded.orderValue}, ${decoded.id})`),\n\t\t\t);\n\t\t}\n\n\t\t// Build ORDER BY using sql template\n\t\tif (Object.keys(orderBy).length > 0) {\n\t\t\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\t\t\t// Order over the jsonb-native value on Postgres so numeric fields sort\n\t\t\t\t// numerically, not lexically. See pluginDataOrderExpr.\n\t\t\t\tconst extract = jsonOrderExtract(this.db, field);\n\t\t\t\tconst orderExpr =\n\t\t\t\t\tdirection === \"desc\" ? sql`${sql.raw(extract)} desc` : sql`${sql.raw(extract)} asc`;\n\t\t\t\tquery = query.orderBy(orderExpr);\n\t\t\t}\n\t\t} else {\n\t\t\t// Default ordering for consistent pagination\n\t\t\tquery = query.orderBy(\"created_at\", \"asc\").orderBy(\"id\", \"asc\");\n\t\t}\n\n\t\t// Apply limit (fetch one extra to detect if there's more)\n\t\tquery = query.limit(limit + 1);\n\n\t\tconst rows = await query.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => ({\n\t\t\tid: row.id,\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- JSON.parse returns any; generic callers provide T\n\t\t\tdata: JSON.parse(row.data) as T,\n\t\t}));\n\n\t\t// Generate cursor for next page if there are more results\n\t\tlet nextCursor: string | undefined;\n\t\tif (hasMore) {\n\t\t\tconst lastItem = rows[limit - 1];\n\t\t\tif (lastItem) {\n\t\t\t\tnextCursor = encodeCursor(lastItem.created_at, lastItem.id);\n\t\t\t}\n\t\t}\n\n\t\treturn { items, cursor: nextCursor, hasMore };\n\t}\n\n\t/**\n\t * Count documents matching a filter\n\t */\n\tasync count(where?: WhereClause): Promise<number> {\n\t\tif (where && Object.keys(where).length > 0) {\n\t\t\tvalidateWhereClause(where, this.indexedFields, this.pluginId, this.collection);\n\t\t}\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select(sql<number>`COUNT(*)`.as(\"count\"))\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection);\n\n\t\t// Add JSON extraction WHERE conditions\n\t\tif (where && Object.keys(where).length > 0) {\n\t\t\tconst whereResult = buildWhereClause(this.db, where);\n\t\t\tif (whereResult.sql) {\n\t\t\t\tquery = query.where(rawWhereExpr(whereResult.sql, whereResult.params));\n\t\t\t}\n\t\t}\n\n\t\tconst result = await query.executeTakeFirst();\n\t\t// Number() because the pg driver returns COUNT(*) (bigint) as a string.\n\t\treturn Number(result?.count ?? 0);\n\t}\n}\n\n/**\n * Create a scoped storage accessor for a plugin\n */\nexport function createPluginStorageAccessor(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tstorageConfig: Record<\n\t\tstring,\n\t\t{ indexes: Array<string | string[]>; uniqueIndexes?: Array<string | string[]> }\n\t>,\n): Record<string, StorageCollection> {\n\tconst accessor: Record<string, StorageCollection> = {};\n\n\tfor (const [collectionName, config] of Object.entries(storageConfig)) {\n\t\tconst allIndexes = [...config.indexes, ...(config.uniqueIndexes ?? [])];\n\t\taccessor[collectionName] = new PluginStorageRepository(\n\t\t\tdb,\n\t\t\tpluginId,\n\t\t\tcollectionName,\n\t\t\tallIndexes,\n\t\t);\n\t}\n\n\treturn accessor;\n}\n\n/**\n * Delete all storage data for a plugin\n */\nexport async function deleteAllPluginStorage(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n): Promise<number> {\n\tconst result = await db\n\t\t.deleteFrom(\"_plugin_storage\")\n\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t.executeTakeFirst();\n\n\treturn Number(result.numDeletedRows ?? 0);\n}\n\n/**\n * Delete all storage data for a plugin collection\n */\nexport async function deletePluginCollection(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tcollection: string,\n): Promise<number> {\n\tconst result = await db\n\t\t.deleteFrom(\"_plugin_storage\")\n\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t.where(\"collection\", \"=\", collection)\n\t\t.executeTakeFirst();\n\n\treturn Number(result.numDeletedRows ?? 0);\n}\n","/**\n * Git-backed collections: entries are JSON files in the site's git repo,\n * `content/<collection>/<slug>.json`, read from and written to GitHub\n * directly — saving in the admin is a commit, and the same files are what\n * the static frontend build renders from, so this content never round-trips\n * through the database. Only available once the site's GitHub connection\n * (Settings → General) has stored `github:token/owner/repo`.\n *\n * Entries keep the ContentItem shape the admin already understands. The id\n * IS the slug (files have no other identity); there are no drafts,\n * revisions, trash or scheduling — the git history is the revision history.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport type { Database } from \"../database/types.js\";\nimport { OptionsRepository } from \"../database/repositories/options.js\";\nimport type { ContentItem } from \"../plugins/types.js\";\nimport { slugify } from \"../utils/slugify.js\";\n\nexport interface GitRepoConnection {\n\ttoken: string;\n\towner: string;\n\trepo: string;\n\tbranch: string;\n}\n\ninterface GitEntryFile {\n\t$schema?: string;\n\tslug: string;\n\tstatus: string;\n\tlocale?: string | null;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\tpublishedAt?: string | null;\n\tdata: Record<string, unknown>;\n}\n\ninterface GhFile {\n\tname: string;\n\tpath: string;\n\tsha: string;\n\ttype: string;\n\tcontent?: string;\n\tencoding?: string;\n}\n\nexport class GitStoreError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly code: \"NOT_CONNECTED\" | \"NOT_FOUND\" | \"CONFLICT\" | \"GITHUB\",\n\t\tpublic readonly status = 500,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\nconst GH = \"https://api.github.com\";\nconst B64_NEWLINES = /\\n/g;\n\n/** The repo connection stored on this site, or null when GitHub isn't connected. */\nexport async function gitConnection(db: Kysely<Database>): Promise<GitRepoConnection | null> {\n\tconst options = new OptionsRepository(db);\n\tconst map = await options.getMany<string>([\n\t\t\"github:token\",\n\t\t\"github:owner\",\n\t\t\"github:repo\",\n\t\t\"github:branch\",\n\t]);\n\tconst token = map.get(\"github:token\") ?? \"\";\n\tconst owner = map.get(\"github:owner\") ?? \"\";\n\tconst repo = map.get(\"github:repo\") ?? \"\";\n\tif (!token || !owner || !repo) return null;\n\treturn { token, owner, repo, branch: map.get(\"github:branch\") || \"main\" };\n}\n\nfunction b64encode(text: string): string {\n\treturn btoa(String.fromCharCode(...new TextEncoder().encode(text)));\n}\n\nfunction b64decode(b64: string): string {\n\tconst bin = atob(b64.replace(B64_NEWLINES, \"\"));\n\tconst bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));\n\treturn new TextDecoder().decode(bytes);\n}\n\nexport class GitContentStore {\n\tconstructor(\n\t\tprivate readonly conn: GitRepoConnection,\n\t\tprivate readonly collection: string,\n\t) {}\n\n\tprivate get dir(): string {\n\t\treturn `content/${this.collection}`;\n\t}\n\n\tprivate async gh<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<{ ok: boolean; status: number; json: T | null }> {\n\t\tconst res = await fetch(`${GH}${path}`, {\n\t\t\tmethod,\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${this.conn.token}`,\n\t\t\t\tAccept: \"application/vnd.github+json\",\n\t\t\t\t\"User-Agent\": \"premium-cms\",\n\t\t\t\t\"X-GitHub-Api-Version\": \"2022-11-28\",\n\t\t\t\t...(body !== undefined ? { \"Content-Type\": \"application/json\" } : {}),\n\t\t\t},\n\t\t\tbody: body === undefined ? undefined : JSON.stringify(body),\n\t\t});\n\t\tlet json: T | null = null;\n\t\ttry {\n\t\t\tjson = (await res.json()) as T;\n\t\t} catch {\n\t\t\tjson = null;\n\t\t}\n\t\tif (res.status === 401 || res.status === 403) {\n\t\t\tthrow new GitStoreError(\n\t\t\t\t\"GitHub rejected the site's token — reconnect GitHub in Settings → General.\",\n\t\t\t\t\"GITHUB\",\n\t\t\t\t502,\n\t\t\t);\n\t\t}\n\t\treturn { ok: res.ok, status: res.status, json };\n\t}\n\n\tprivate toItem(file: GitEntryFile): ContentItem {\n\t\treturn {\n\t\t\tid: file.slug,\n\t\t\ttype: this.collection,\n\t\t\tslug: file.slug,\n\t\t\tstatus: file.status || \"published\",\n\t\t\tlocale: file.locale ?? null,\n\t\t\tdata: file.data ?? {},\n\t\t\tcreatedAt: file.createdAt,\n\t\t\tupdatedAt: file.updatedAt,\n\t\t\tpublishedAt: file.publishedAt ?? (file.status === \"published\" ? file.updatedAt : null),\n\t\t};\n\t}\n\n\tprivate async readFile(slug: string): Promise<{ file: GitEntryFile; sha: string } | null> {\n\t\tconst r = await this.gh<GhFile>(\n\t\t\t\"GET\",\n\t\t\t`/repos/${this.conn.owner}/${this.conn.repo}/contents/${this.dir}/${encodeURIComponent(slug)}.json?ref=${encodeURIComponent(this.conn.branch)}`,\n\t\t);\n\t\tif (r.status === 404 || !r.json?.content) return null;\n\t\ttry {\n\t\t\treturn { file: JSON.parse(b64decode(r.json.content)) as GitEntryFile, sha: r.json.sha };\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate async writeFile(\n\t\tslug: string,\n\t\tfile: GitEntryFile,\n\t\tmessage: string,\n\t\tsha?: string,\n\t): Promise<void> {\n\t\tconst body: Record<string, unknown> = {\n\t\t\tmessage,\n\t\t\tcontent: b64encode(`${JSON.stringify(file, null, \"\\t\")}\\n`),\n\t\t\tbranch: this.conn.branch,\n\t\t};\n\t\tif (sha) body.sha = sha;\n\t\tconst r = await this.gh<{ message?: string }>(\n\t\t\t\"PUT\",\n\t\t\t`/repos/${this.conn.owner}/${this.conn.repo}/contents/${this.dir}/${encodeURIComponent(slug)}.json`,\n\t\t\tbody,\n\t\t);\n\t\tif (r.status === 409 || r.status === 422) {\n\t\t\tthrow new GitStoreError(\n\t\t\t\t\"The file changed in git since it was loaded — reload and try again.\",\n\t\t\t\t\"CONFLICT\",\n\t\t\t\t409,\n\t\t\t);\n\t\t}\n\t\tif (!r.ok) throw new GitStoreError(r.json?.message || `GitHub ${r.status}`, \"GITHUB\", 502);\n\t}\n\n\t/** Every entry in the collection (one listing call + one read per file). */\n\tasync list(): Promise<ContentItem[]> {\n\t\tconst r = await this.gh<GhFile[]>(\n\t\t\t\"GET\",\n\t\t\t`/repos/${this.conn.owner}/${this.conn.repo}/contents/${this.dir}?ref=${encodeURIComponent(this.conn.branch)}`,\n\t\t);\n\t\tif (r.status === 404 || !Array.isArray(r.json)) return [];\n\t\tconst items: ContentItem[] = [];\n\t\tfor (const f of r.json) {\n\t\t\tif (f.type !== \"file\" || !f.name.endsWith(\".json\")) continue;\n\t\t\tconst read = await this.readFile(f.name.slice(0, -5));\n\t\t\tif (read) items.push(this.toItem(read.file));\n\t\t}\n\t\treturn items.toSorted((a, b) => b.updatedAt.localeCompare(a.updatedAt));\n\t}\n\n\tasync get(idOrSlug: string): Promise<ContentItem | null> {\n\t\tconst read = await this.readFile(idOrSlug);\n\t\treturn read ? this.toItem(read.file) : null;\n\t}\n\n\tasync create(input: {\n\t\tslug?: string | null;\n\t\tstatus?: string;\n\t\tlocale?: string;\n\t\tdata: Record<string, unknown>;\n\t}): Promise<ContentItem> {\n\t\tconst title = typeof input.data.title === \"string\" ? input.data.title : \"\";\n\t\tlet slug = (input.slug && slugify(input.slug)) || slugify(title) || `entry-${Date.now()}`;\n\t\tif (await this.readFile(slug)) slug = `${slug}-${Date.now().toString(36)}`;\n\t\tconst now = new Date().toISOString();\n\t\tconst file: GitEntryFile = {\n\t\t\t$schema: \"../../seed/.schemas/content-entry.schema.json\",\n\t\t\tslug,\n\t\t\tstatus: input.status || \"published\",\n\t\t\tlocale: input.locale ?? null,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tpublishedAt: (input.status || \"published\") === \"published\" ? now : null,\n\t\t\tdata: input.data,\n\t\t};\n\t\tawait this.writeFile(slug, file, `content(${this.collection}): add ${slug}`);\n\t\treturn this.toItem(file);\n\t}\n\n\tasync update(\n\t\tidOrSlug: string,\n\t\tinput: { slug?: string | null; status?: string; data?: Record<string, unknown> },\n\t): Promise<ContentItem> {\n\t\tconst read = await this.readFile(idOrSlug);\n\t\tif (!read) throw new GitStoreError(`Entry not found: ${idOrSlug}`, \"NOT_FOUND\", 404);\n\t\tconst now = new Date().toISOString();\n\t\tconst next: GitEntryFile = {\n\t\t\t...read.file,\n\t\t\tstatus: input.status ?? read.file.status,\n\t\t\tdata: input.data ? { ...read.file.data, ...input.data } : read.file.data,\n\t\t\tupdatedAt: now,\n\t\t};\n\t\tif (next.status === \"published\" && !next.publishedAt) next.publishedAt = now;\n\t\tconst newSlug = input.slug ? slugify(input.slug) : \"\";\n\t\tif (newSlug && newSlug !== read.file.slug) {\n\t\t\tnext.slug = newSlug;\n\t\t\tawait this.writeFile(newSlug, next, `content(${this.collection}): rename ${read.file.slug} → ${newSlug}`);\n\t\t\tawait this.remove(read.file.slug, `content(${this.collection}): remove ${read.file.slug} (renamed)`);\n\t\t\treturn this.toItem(next);\n\t\t}\n\t\tawait this.writeFile(read.file.slug, next, `content(${this.collection}): update ${read.file.slug}`, read.sha);\n\t\treturn this.toItem(next);\n\t}\n\n\tasync remove(idOrSlug: string, message?: string): Promise<boolean> {\n\t\tconst read = await this.readFile(idOrSlug);\n\t\tif (!read) return false;\n\t\tconst r = await this.gh<{ message?: string }>(\n\t\t\t\"DELETE\",\n\t\t\t`/repos/${this.conn.owner}/${this.conn.repo}/contents/${this.dir}/${encodeURIComponent(idOrSlug)}.json`,\n\t\t\t{ message: message ?? `content(${this.collection}): remove ${idOrSlug}`, sha: read.sha, branch: this.conn.branch },\n\t\t);\n\t\tif (!r.ok) throw new GitStoreError(r.json?.message || `GitHub ${r.status}`, \"GITHUB\", 502);\n\t\treturn true;\n\t}\n}\n","/**\n * Git-backed plugin storage collection: each entry is a JSON file at\n * `content/<pluginId>/<collection>/<id>.json` in the site's git repo, written\n * through the GitHub Contents API with the site's connection — so a plugin's\n * definitions (a form's fields, say) are versioned with the site and readable\n * by the static frontend build, while high-churn data (submissions) stays in\n * the database. Queries are answered in memory over the directory listing;\n * these collections are small by design.\n *\n * Unavailable until GitHub is connected: every call throws `GitStoreError`\n * with code NOT_CONNECTED, which routes surface as a 409.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { GitStoreError, gitConnection, type GitRepoConnection } from \"../content/git-store.js\";\nimport type { Database } from \"../database/types.js\";\nimport type {\n\tPaginatedResult,\n\tQueryOptions,\n\tStorageCollection,\n\tWhereClause,\n\tWhereValue,\n} from \"./types.js\";\n\nconst GH = \"https://api.github.com\";\nconst B64_NEWLINES = /\\n/g;\nconst SAFE_ID = /^[A-Za-z0-9_.-]{1,120}$/;\n\ninterface GhFile {\n\tname: string;\n\tsha: string;\n\ttype: string;\n\tcontent?: string;\n}\n\nfunction b64encode(text: string): string {\n\treturn btoa(String.fromCharCode(...new TextEncoder().encode(text)));\n}\nfunction b64decode(b64: string): string {\n\tconst bin = atob(b64.replace(B64_NEWLINES, \"\"));\n\treturn new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)));\n}\n\nfunction matches(value: unknown, want: WhereValue): boolean {\n\tif (want === null || typeof want !== \"object\") return value === want;\n\tif (\"in\" in want) return want.in.includes(value as string | number);\n\tif (\"startsWith\" in want) return typeof value === \"string\" && value.startsWith(want.startsWith);\n\tconst v = value as number | string;\n\tif (want.gt !== undefined && !(v > want.gt)) return false;\n\tif (want.gte !== undefined && !(v >= want.gte)) return false;\n\tif (want.lt !== undefined && !(v < want.lt)) return false;\n\tif (want.lte !== undefined && !(v <= want.lte)) return false;\n\treturn true;\n}\n\nexport class GitStorageCollection<T = unknown> implements StorageCollection<T> {\n\tprivate cache: { at: number; items: Array<{ id: string; data: T; sha: string }> } | null = null;\n\n\tconstructor(\n\t\tprivate readonly db: Kysely<Database>,\n\t\tprivate readonly pluginId: string,\n\t\tprivate readonly collection: string,\n\t) {}\n\n\tprivate get dir(): string {\n\t\treturn `content/${this.pluginId}/${this.collection}`;\n\t}\n\n\tprivate async conn(): Promise<GitRepoConnection> {\n\t\tconst c = await gitConnection(this.db);\n\t\tif (!c) {\n\t\t\tthrow new GitStoreError(\n\t\t\t\t`\"${this.collection}\" is stored in git — connect GitHub in Settings → General first.`,\n\t\t\t\t\"NOT_CONNECTED\",\n\t\t\t\t409,\n\t\t\t);\n\t\t}\n\t\treturn c;\n\t}\n\n\tprivate async gh<R>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<{ ok: boolean; status: number; json: R | null }> {\n\t\tconst c = await this.conn();\n\t\tconst res = await fetch(`${GH}/repos/${c.owner}/${c.repo}${path}`, {\n\t\t\tmethod,\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${c.token}`,\n\t\t\t\tAccept: \"application/vnd.github+json\",\n\t\t\t\t\"User-Agent\": \"premium-cms\",\n\t\t\t\t\"X-GitHub-Api-Version\": \"2022-11-28\",\n\t\t\t\t...(body !== undefined ? { \"Content-Type\": \"application/json\" } : {}),\n\t\t\t},\n\t\t\tbody: body === undefined ? undefined : JSON.stringify({ branch: c.branch, ...(body as object) }),\n\t\t});\n\t\tlet json: R | null = null;\n\t\ttry {\n\t\t\tjson = (await res.json()) as R;\n\t\t} catch {\n\t\t\tjson = null;\n\t\t}\n\t\tif (res.status === 401 || res.status === 403) {\n\t\t\tthrow new GitStoreError(\"GitHub rejected the site's token — reconnect GitHub.\", \"GITHUB\", 502);\n\t\t}\n\t\treturn { ok: res.ok, status: res.status, json };\n\t}\n\n\tprivate assertId(id: string): void {\n\t\tif (!SAFE_ID.test(id)) throw new GitStoreError(`Invalid id \"${id}\"`, \"GITHUB\", 400);\n\t}\n\n\tprivate async readOne(id: string): Promise<{ data: T; sha: string } | null> {\n\t\tthis.assertId(id);\n\t\tconst c = await this.conn();\n\t\tconst r = await this.gh<GhFile>(\"GET\", `/contents/${this.dir}/${id}.json?ref=${encodeURIComponent(c.branch)}`);\n\t\tif (r.status === 404 || !r.json?.content) return null;\n\t\ttry {\n\t\t\treturn { data: JSON.parse(b64decode(r.json.content)) as T, sha: r.json.sha };\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate async readAll(): Promise<Array<{ id: string; data: T; sha: string }>> {\n\t\tif (this.cache && Date.now() - this.cache.at < 2000) return this.cache.items;\n\t\tconst c = await this.conn();\n\t\tconst r = await this.gh<GhFile[]>(\"GET\", `/contents/${this.dir}?ref=${encodeURIComponent(c.branch)}`);\n\t\tconst items: Array<{ id: string; data: T; sha: string }> = [];\n\t\tif (r.status !== 404 && Array.isArray(r.json)) {\n\t\t\tfor (const f of r.json) {\n\t\t\t\tif (f.type !== \"file\" || !f.name.endsWith(\".json\")) continue;\n\t\t\t\tconst id = f.name.slice(0, -5);\n\t\t\t\tconst one = await this.readOne(id);\n\t\t\t\tif (one) items.push({ id, ...one });\n\t\t\t}\n\t\t}\n\t\tthis.cache = { at: Date.now(), items };\n\t\treturn items;\n\t}\n\n\tasync get(id: string): Promise<T | null> {\n\t\treturn (await this.readOne(id))?.data ?? null;\n\t}\n\n\tasync put(id: string, data: T): Promise<void> {\n\t\tthis.assertId(id);\n\t\tconst existing = await this.readOne(id);\n\t\tconst r = await this.gh<{ message?: string }>(\"PUT\", `/contents/${this.dir}/${id}.json`, {\n\t\t\tmessage: `${this.pluginId}(${this.collection}): ${existing ? \"update\" : \"add\"} ${id}`,\n\t\t\tcontent: b64encode(`${JSON.stringify(data, null, \"\\t\")}\\n`),\n\t\t\t...(existing ? { sha: existing.sha } : {}),\n\t\t});\n\t\tthis.cache = null;\n\t\tif (r.status === 409 || r.status === 422)\n\t\t\tthrow new GitStoreError(\"The file changed in git since it was loaded — reload and try again.\", \"CONFLICT\", 409);\n\t\tif (!r.ok) throw new GitStoreError(r.json?.message || `GitHub ${r.status}`, \"GITHUB\", 502);\n\t}\n\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst existing = await this.readOne(id);\n\t\tif (!existing) return false;\n\t\tconst r = await this.gh<{ message?: string }>(\"DELETE\", `/contents/${this.dir}/${id}.json`, {\n\t\t\tmessage: `${this.pluginId}(${this.collection}): remove ${id}`,\n\t\t\tsha: existing.sha,\n\t\t});\n\t\tthis.cache = null;\n\t\tif (!r.ok) throw new GitStoreError(r.json?.message || `GitHub ${r.status}`, \"GITHUB\", 502);\n\t\treturn true;\n\t}\n\n\tasync exists(id: string): Promise<boolean> {\n\t\treturn (await this.readOne(id)) !== null;\n\t}\n\n\tasync getMany(ids: string[]): Promise<Map<string, T>> {\n\t\tconst out = new Map<string, T>();\n\t\tfor (const id of ids) {\n\t\t\tconst one = await this.readOne(id);\n\t\t\tif (one) out.set(id, one.data);\n\t\t}\n\t\treturn out;\n\t}\n\n\tasync putMany(items: Array<{ id: string; data: T }>): Promise<void> {\n\t\tfor (const it of items) await this.put(it.id, it.data);\n\t}\n\n\tasync deleteMany(ids: string[]): Promise<number> {\n\t\tlet n = 0;\n\t\tfor (const id of ids) if (await this.delete(id)) n++;\n\t\treturn n;\n\t}\n\n\tprivate filter(items: Array<{ id: string; data: T }>, where?: WhereClause) {\n\t\tif (!where) return items;\n\t\treturn items.filter((it) =>\n\t\t\tObject.entries(where).every(([k, want]) =>\n\t\t\t\tmatches((it.data as Record<string, unknown>)[k], want),\n\t\t\t),\n\t\t);\n\t}\n\n\tasync query(options?: QueryOptions): Promise<PaginatedResult<{ id: string; data: T }>> {\n\t\tlet items = this.filter(await this.readAll(), options?.where);\n\t\tconst [field, dir] = Object.entries(options?.orderBy ?? {})[0] ?? [];\n\t\tif (field) {\n\t\t\titems = items.toSorted((a, b) => {\n\t\t\t\tconst av = (a.data as Record<string, unknown>)[field] as string | number;\n\t\t\t\tconst bv = (b.data as Record<string, unknown>)[field] as string | number;\n\t\t\t\tconst cmp = av === bv ? 0 : av > bv ? 1 : -1;\n\t\t\t\treturn dir === \"desc\" ? -cmp : cmp;\n\t\t\t});\n\t\t}\n\t\tconst limit = Math.min(Math.max(options?.limit ?? 50, 1), 1000);\n\t\tconst offset = options?.cursor ? Number(options.cursor) || 0 : 0;\n\t\tconst page = items.slice(offset, offset + limit);\n\t\tconst hasMore = offset + limit < items.length;\n\t\treturn {\n\t\t\titems: page.map(({ id, data }) => ({ id, data })),\n\t\t\tcursor: hasMore ? String(offset + limit) : undefined,\n\t\t\thasMore,\n\t\t};\n\t}\n\n\tasync count(where?: WhereClause): Promise<number> {\n\t\treturn this.filter(await this.readAll(), where).length;\n\t}\n}\n","/**\n * Plugin Context v2\n *\n * Creates the unified context object provided to plugins in all hooks and routes.\n *\n */\n\nimport type { Kysely } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { ContentRepository } from \"../database/repositories/content.js\";\nimport { MediaRepository } from \"../database/repositories/media.js\";\nimport { OptionsRepository } from \"../database/repositories/options.js\";\nimport { PluginStorageRepository } from \"../database/repositories/plugin-storage.js\";\nimport { SeoRepository } from \"../database/repositories/seo.js\";\nimport { TaxonomyRepository, type Taxonomy } from \"../database/repositories/taxonomy.js\";\nimport { AuthzRepository } from \"../database/repositories/authz.js\";\nimport { UserRepository } from \"../database/repositories/user.js\";\nimport { withTransaction } from \"../database/transaction.js\";\nimport type { Database } from \"../database/types.js\";\nimport { resolveContentCreateLocale } from \"../i18n/config.js\";\nimport {\n\tresolveAndValidateExternalUrl,\n\tSsrfError,\n\tstripCredentialHeaders,\n} from \"../import/ssrf.js\";\nimport { enrichImageMetadata } from \"../media/enrich.js\";\nimport { markContentMediaUsageCollectionStaleSafely } from \"../media/usage/content-refresh.js\";\nimport { invalidateSiteSettingsCache } from \"../settings/index.js\";\nimport type { Storage } from \"../storage/types.js\";\nimport { GitStorageCollection } from \"./git-storage.js\";\nimport { CronAccessImpl } from \"./cron.js\";\nimport type { EmailPipeline } from \"./email.js\";\nimport type {\n\tGitHubConnectionAccess,\n\tResolvedPlugin,\n\tPluginContext,\n\tPluginStorageConfig,\n\tStorageCollection,\n\tKVAccess,\n\tCronAccess,\n\tEmailAccess,\n\tContentAccess,\n\tContentAccessWithWrite,\n\tMediaAccess,\n\tMediaAccessWithWrite,\n\tHttpAccess,\n\tLogAccess,\n\tSiteInfo,\n\tUserAccess,\n\tUserInfo,\n\tContentItem,\n\tContentCreateOptions,\n\tContentItemSeoInput,\n\tContentWriteInput,\n\tMediaItem,\n\tPaginatedResult,\n\tQueryOptions,\n\tContentListOptions,\n\tMediaListOptions,\n\tTaxonomyAccess,\n\tTaxonomyDefInfo,\n\tTaxonomyTermInfo,\n\tTaxonomyReadOptions,\n} from \"./types.js\";\n\n// =============================================================================\n// KV Access\n// =============================================================================\n\n/**\n * Create KV accessor for a plugin\n * All keys are automatically prefixed with the plugin ID\n */\nexport function createKVAccess(optionsRepo: OptionsRepository, pluginId: string): KVAccess {\n\tconst prefix = `plugin:${pluginId}:`;\n\n\treturn {\n\t\tasync get<T>(key: string): Promise<T | null> {\n\t\t\treturn optionsRepo.get<T>(`${prefix}${key}`);\n\t\t},\n\n\t\tasync set(key: string, value: unknown): Promise<void> {\n\t\t\tawait optionsRepo.set(`${prefix}${key}`, value);\n\t\t},\n\n\t\tasync delete(key: string): Promise<boolean> {\n\t\t\treturn optionsRepo.delete(`${prefix}${key}`);\n\t\t},\n\n\t\tasync list(keyPrefix?: string): Promise<Array<{ key: string; value: unknown }>> {\n\t\t\tconst fullPrefix = `${prefix}${keyPrefix ?? \"\"}`;\n\t\t\tconst entriesMap = await optionsRepo.getByPrefix(fullPrefix);\n\t\t\tconst result: Array<{ key: string; value: unknown }> = [];\n\t\t\tfor (const [fullKey, value] of entriesMap) {\n\t\t\t\tresult.push({\n\t\t\t\t\tkey: fullKey.slice(prefix.length),\n\t\t\t\t\tvalue,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Storage Access\n// =============================================================================\n\n/**\n * Create storage collection accessor for a plugin\n * Wraps PluginStorageRepository with the v2 interface (no async iterators)\n */\nfunction createStorageCollection<T>(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tcollectionName: string,\n\tindexes: Array<string | string[]>,\n): StorageCollection<T> {\n\tconst repo = new PluginStorageRepository<T>(db, pluginId, collectionName, indexes);\n\n\treturn {\n\t\tget: (id) => repo.get(id),\n\t\tput: (id, data) => repo.put(id, data),\n\t\tdelete: (id) => repo.delete(id),\n\t\texists: (id) => repo.exists(id),\n\t\tgetMany: (ids) => repo.getMany(ids),\n\t\tputMany: (items) => repo.putMany(items),\n\t\tdeleteMany: (ids) => repo.deleteMany(ids),\n\t\tcount: (where) => repo.count(where),\n\n\t\t// Query returns PaginatedResult instead of the old format\n\t\tasync query(options?: QueryOptions): Promise<PaginatedResult<{ id: string; data: T }>> {\n\t\t\tconst result = await repo.query({\n\t\t\t\twhere: options?.where,\n\t\t\t\torderBy: options?.orderBy,\n\t\t\t\tlimit: options?.limit,\n\t\t\t\tcursor: options?.cursor,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\titems: result.items,\n\t\t\t\tcursor: result.cursor,\n\t\t\t\thasMore: result.hasMore,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Create storage accessor with all declared collections\n */\nexport function createStorageAccess<T extends PluginStorageConfig>(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tstorageConfig: T,\n): Record<string, StorageCollection> {\n\tconst storage: Record<string, StorageCollection> = {};\n\n\tfor (const [collectionName, config] of Object.entries(storageConfig)) {\n\t\tif (config.storage === \"git\") {\n\t\t\tstorage[collectionName] = new GitStorageCollection(db, pluginId, collectionName);\n\t\t\tcontinue;\n\t\t}\n\t\tconst allIndexes = [...config.indexes, ...(config.uniqueIndexes ?? [])];\n\t\tstorage[collectionName] = createStorageCollection(db, pluginId, collectionName, allIndexes);\n\t}\n\n\treturn storage;\n}\n\n// =============================================================================\n// Content Access\n// =============================================================================\n\n/**\n * Extract `seo` from a plugin-supplied content write input and return both\n * parts. Mutates nothing — returns a new field map without the `seo` key.\n */\nfunction splitSeoFromInput(input: ContentWriteInput): {\n\tfields: Record<string, unknown>;\n\tseo: ContentItemSeoInput | undefined;\n} {\n\tconst { seo, ...fields } = input;\n\t// Reject non-object seo values rather than silently dropping them.\n\tif (seo !== undefined && (seo === null || typeof seo !== \"object\" || Array.isArray(seo))) {\n\t\tthrow new Error(\"content.seo must be an object\");\n\t}\n\treturn { fields, seo };\n}\n\n/**\n * Reject writing SEO to a collection that does not have it enabled.\n * Matches the REST API behavior (VALIDATION_ERROR).\n */\nasync function assertSeoEnabled(\n\tseoRepo: SeoRepository,\n\tcollection: string,\n\tseo: ContentItemSeoInput | undefined,\n): Promise<boolean> {\n\tconst hasSeo = await seoRepo.isEnabled(collection);\n\tif (seo !== undefined && !hasSeo) {\n\t\tthrow new Error(\n\t\t\t`Collection \"${collection}\" does not have SEO enabled. ` +\n\t\t\t\t`Remove the seo field or enable SEO on this collection.`,\n\t\t);\n\t}\n\treturn hasSeo;\n}\n\n/**\n * Parse the `collections` JSON column into a string array (`[]` on anything\n * else). Mirrors the guards in the Cloudflare/workerd bridges so an\n * in-process plugin degrades on malformed data instead of crashing.\n */\nfunction parseCollectionsColumn(value: string | null): string[] {\n\tif (!value) return [];\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value);\n\t\treturn Array.isArray(parsed)\n\t\t\t? parsed.filter((item): item is string => typeof item === \"string\")\n\t\t\t: [];\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/** Map a repository `Taxonomy` row to the plugin-facing term shape. */\nfunction taxonomyToTermInfo(term: Taxonomy): TaxonomyTermInfo {\n\treturn {\n\t\tid: term.id,\n\t\ttaxonomy: term.name,\n\t\tslug: term.slug,\n\t\tlabel: term.label,\n\t\tparentId: term.parentId,\n\t\tdata: term.data,\n\t\tlocale: term.locale,\n\t\ttranslationGroup: term.translationGroup,\n\t};\n}\n\n/**\n * Create read-only content access\n */\nexport function createContentAccess(db: Kysely<Database>): ContentAccess {\n\tconst contentRepo = new ContentRepository(db);\n\tconst seoRepo = new SeoRepository(db);\n\n\treturn {\n\t\tasync get(collection: string, id: string): Promise<ContentItem | null> {\n\t\t\tconst item = await contentRepo.findById(collection, id);\n\t\t\tif (!item) return null;\n\n\t\t\tconst result: ContentItem = {\n\t\t\t\tid: item.id,\n\t\t\t\ttype: item.type,\n\t\t\t\tslug: item.slug,\n\t\t\t\tstatus: item.status,\n\t\t\t\tdata: item.data,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\tlocale: item.locale,\n\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t\tscheduledAt: item.scheduledAt,\n\t\t\t};\n\n\t\t\tif (await seoRepo.isEnabled(collection)) {\n\t\t\t\tresult.seo = await seoRepo.get(collection, item.id);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t},\n\n\t\tasync list(\n\t\t\tcollection: string,\n\t\t\toptions?: ContentListOptions,\n\t\t): Promise<PaginatedResult<ContentItem>> {\n\t\t\t// Convert orderBy format if provided\n\t\t\tlet orderBy: { field: string; direction: \"asc\" | \"desc\" } | undefined;\n\t\t\tif (options?.orderBy) {\n\t\t\t\tconst entries = Object.entries(options.orderBy);\n\t\t\t\tconst first = entries[0];\n\t\t\t\tif (first) {\n\t\t\t\t\torderBy = { field: first[0], direction: first[1] };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst result = await contentRepo.findMany(collection, {\n\t\t\t\tlimit: options?.limit ?? 50,\n\t\t\t\tcursor: options?.cursor,\n\t\t\t\torderBy,\n\t\t\t\twhere: options?.where,\n\t\t\t});\n\n\t\t\tconst items: ContentItem[] = result.items.map((item) => ({\n\t\t\t\tid: item.id,\n\t\t\t\ttype: item.type,\n\t\t\t\tslug: item.slug,\n\t\t\t\tstatus: item.status,\n\t\t\t\tdata: item.data,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\tlocale: item.locale,\n\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t\tscheduledAt: item.scheduledAt,\n\t\t\t}));\n\n\t\t\tif (items.length > 0 && (await seoRepo.isEnabled(collection))) {\n\t\t\t\tconst seoMap = await seoRepo.getMany(\n\t\t\t\t\tcollection,\n\t\t\t\t\titems.map((i) => i.id),\n\t\t\t\t);\n\t\t\t\tfor (const item of items) {\n\t\t\t\t\tconst seo = seoMap.get(item.id);\n\t\t\t\t\tif (seo) item.seo = seo;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\titems,\n\t\t\t\tcursor: result.nextCursor,\n\t\t\t\thasMore: !!result.nextCursor,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Create read-only taxonomy access (gated on `taxonomies:read`).\n */\nexport function createTaxonomyAccess(db: Kysely<Database>): TaxonomyAccess {\n\tconst taxonomyRepo = new TaxonomyRepository(db);\n\n\treturn {\n\t\tasync getAll(options?: TaxonomyReadOptions): Promise<TaxonomyDefInfo[]> {\n\t\t\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll();\n\t\t\tif (options?.locale !== undefined) query = query.where(\"locale\", \"=\", options.locale);\n\t\t\tconst rows = await query.orderBy(\"name\", \"asc\").execute();\n\t\t\treturn rows.map((row) => ({\n\t\t\t\tname: row.name,\n\t\t\t\tlabel: row.label,\n\t\t\t\tlabelSingular: row.label_singular,\n\t\t\t\thierarchical: row.hierarchical === 1,\n\t\t\t\tcollections: parseCollectionsColumn(row.collections),\n\t\t\t\tlocale: row.locale,\n\t\t\t}));\n\t\t},\n\n\t\tasync getTerms(taxonomy: string, options?: TaxonomyReadOptions): Promise<TaxonomyTermInfo[]> {\n\t\t\tconst terms = await taxonomyRepo.findByName(taxonomy, { locale: options?.locale });\n\t\t\treturn terms.map(taxonomyToTermInfo);\n\t\t},\n\n\t\tasync getEntryTerms(\n\t\t\tcollection: string,\n\t\t\tentryId: string,\n\t\t\toptions?: TaxonomyReadOptions & { taxonomy?: string },\n\t\t): Promise<TaxonomyTermInfo[]> {\n\t\t\tconst terms = await taxonomyRepo.getTermsForEntry(\n\t\t\t\tcollection,\n\t\t\t\tentryId,\n\t\t\t\toptions?.taxonomy,\n\t\t\t\toptions?.locale,\n\t\t\t);\n\t\t\treturn terms.map(taxonomyToTermInfo);\n\t\t},\n\t};\n}\n\n/**\n * Create full content access with write operations.\n *\n * `create` and `update` accept a reserved `seo` key in their `data`\n * argument. When present, it is routed to the core SEO panel\n * (`_emdash_seo`) via `SeoRepository.upsert`, in the same transaction as\n * the content write. The returned `ContentItem.seo` reflects the resulting\n * SEO state for SEO-enabled collections.\n */\nexport function createContentAccessWithWrite(\n\tdb: Kysely<Database>,\n\tbeforeContentWrite?: () => Promise<void>,\n): ContentAccessWithWrite {\n\tconst readAccess = createContentAccess(db);\n\n\treturn {\n\t\t...readAccess,\n\n\t\tasync create(\n\t\t\tcollection: string,\n\t\t\tdata: ContentWriteInput,\n\t\t\toptions?: ContentCreateOptions,\n\t\t): Promise<ContentItem> {\n\t\t\tconst locale = resolveContentCreateLocale(options?.locale);\n\t\t\tawait beforeContentWrite?.();\n\t\t\tconst { fields, seo } = splitSeoFromInput(data);\n\t\t\tlet contentMutated = false;\n\n\t\t\ttry {\n\t\t\t\tconst created = await withTransaction(db, async (trx) => {\n\t\t\t\t\tconst trxContentRepo = new ContentRepository(trx);\n\t\t\t\t\tconst trxSeoRepo = new SeoRepository(trx);\n\n\t\t\t\t\tconst hasSeo = await assertSeoEnabled(trxSeoRepo, collection, seo);\n\n\t\t\t\t\tconst item = await trxContentRepo.create({\n\t\t\t\t\t\ttype: collection,\n\t\t\t\t\t\tdata: fields,\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t});\n\t\t\t\t\tcontentMutated = true;\n\n\t\t\t\t\tconst result: ContentItem = {\n\t\t\t\t\t\tid: item.id,\n\t\t\t\t\t\ttype: item.type,\n\t\t\t\t\t\tslug: item.slug,\n\t\t\t\t\t\tstatus: item.status,\n\t\t\t\t\t\tdata: item.data,\n\t\t\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\t\t\tlocale: item.locale,\n\t\t\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t\t\t\tscheduledAt: item.scheduledAt,\n\t\t\t\t\t};\n\n\t\t\t\t\tif (hasSeo) {\n\t\t\t\t\t\tresult.seo =\n\t\t\t\t\t\t\tseo !== undefined\n\t\t\t\t\t\t\t\t? await trxSeoRepo.upsert(collection, item.id, seo)\n\t\t\t\t\t\t\t\t: await trxSeoRepo.get(collection, item.id);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn result;\n\t\t\t\t});\n\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(db, collection, \"CONTENT_USAGE_STALE\");\n\t\t\t\treturn created;\n\t\t\t} catch (error) {\n\t\t\t\tif (contentMutated) {\n\t\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(db, collection, \"CONTENT_USAGE_STALE\");\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\n\t\tasync update(collection: string, id: string, data: ContentWriteInput): Promise<ContentItem> {\n\t\t\tawait beforeContentWrite?.();\n\t\t\tconst { fields, seo } = splitSeoFromInput(data);\n\t\t\tconst hasFieldUpdates = Object.keys(fields).length > 0;\n\t\t\tlet contentMutated = false;\n\n\t\t\ttry {\n\t\t\t\tconst updated = await withTransaction(db, async (trx) => {\n\t\t\t\t\tconst trxContentRepo = new ContentRepository(trx);\n\t\t\t\t\tconst trxSeoRepo = new SeoRepository(trx);\n\n\t\t\t\t\tconst hasSeo = await assertSeoEnabled(trxSeoRepo, collection, seo);\n\n\t\t\t\t\t// Pass the `data` payload to ContentRepository.updateDraftAware only when\n\t\t\t\t\t// there are field updates — passing an empty object would still\n\t\t\t\t\t// bump updated_at/version, but we want a seo-only call to touch\n\t\t\t\t\t// only the SEO table. updateDraftAware delegates no-op writes to\n\t\t\t\t\t// ContentRepository.update.\n\t\t\t\t\tconst item = hasFieldUpdates\n\t\t\t\t\t\t? await trxContentRepo.updateDraftAware(collection, id, { data: fields })\n\t\t\t\t\t\t: await (async () => {\n\t\t\t\t\t\t\t\tconst existing = await trxContentRepo.findById(collection, id);\n\t\t\t\t\t\t\t\tif (!existing) throw new Error(\"Content not found\");\n\t\t\t\t\t\t\t\treturn existing;\n\t\t\t\t\t\t\t})();\n\t\t\t\t\tif (hasFieldUpdates) contentMutated = true;\n\n\t\t\t\t\tconst result: ContentItem = {\n\t\t\t\t\t\tid: item.id,\n\t\t\t\t\t\ttype: item.type,\n\t\t\t\t\t\tslug: item.slug,\n\t\t\t\t\t\tstatus: item.status,\n\t\t\t\t\t\tdata: item.data,\n\t\t\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\t\t\tlocale: item.locale,\n\t\t\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t\t\t\tscheduledAt: item.scheduledAt,\n\t\t\t\t\t};\n\n\t\t\t\t\tif (hasSeo) {\n\t\t\t\t\t\tresult.seo =\n\t\t\t\t\t\t\tseo !== undefined\n\t\t\t\t\t\t\t\t? await trxSeoRepo.upsert(collection, item.id, seo)\n\t\t\t\t\t\t\t\t: await trxSeoRepo.get(collection, item.id);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn result;\n\t\t\t\t});\n\t\t\t\tif (hasFieldUpdates) {\n\t\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(db, collection, \"CONTENT_USAGE_STALE\");\n\t\t\t\t}\n\t\t\t\treturn updated;\n\t\t\t} catch (error) {\n\t\t\t\tif (contentMutated) {\n\t\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(db, collection, \"CONTENT_USAGE_STALE\");\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\n\t\tasync delete(collection: string, id: string): Promise<boolean> {\n\t\t\tawait beforeContentWrite?.();\n\t\t\tconst contentRepo = new ContentRepository(db);\n\t\t\tconst deleted = await contentRepo.delete(collection, id);\n\t\t\tif (deleted) {\n\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(db, collection, \"CONTENT_USAGE_STALE\");\n\t\t\t}\n\t\t\treturn deleted;\n\t\t},\n\t\tasync permanentDelete(collection: string, id: string): Promise<boolean> {\n\t\t\tawait beforeContentWrite?.();\n\t\t\tconst contentRepo = new ContentRepository(db);\n\t\t\tconst deleted = await contentRepo.permanentDelete(collection, id);\n\t\t\tif (deleted) {\n\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(db, collection, \"CONTENT_USAGE_STALE\");\n\t\t\t}\n\t\t\treturn deleted;\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Media Access\n// =============================================================================\n\n/**\n * Create read-only media access\n */\nexport function createMediaAccess(db: Kysely<Database>): MediaAccess {\n\tconst mediaRepo = new MediaRepository(db);\n\n\treturn {\n\t\tasync get(id: string): Promise<MediaItem | null> {\n\t\t\tconst item = await mediaRepo.findById(id);\n\t\t\tif (!item) return null;\n\n\t\t\treturn {\n\t\t\t\tid: item.id,\n\t\t\t\tfilename: item.filename,\n\t\t\t\tmimeType: item.mimeType,\n\t\t\t\tsize: item.size,\n\t\t\t\t// Construct URL from storage key (or use a sensible default path)\n\t\t\t\turl: `/media/${item.id}/${item.filename}`,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t};\n\t\t},\n\n\t\tasync list(options?: MediaListOptions): Promise<PaginatedResult<MediaItem>> {\n\t\t\tconst result = await mediaRepo.findMany({\n\t\t\t\tlimit: options?.limit ?? 50,\n\t\t\t\tcursor: options?.cursor,\n\t\t\t\tmimeType: options?.mimeType,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\titems: result.items.map((item) => ({\n\t\t\t\t\tid: item.id,\n\t\t\t\t\tfilename: item.filename,\n\t\t\t\t\tmimeType: item.mimeType,\n\t\t\t\t\tsize: item.size,\n\t\t\t\t\turl: `/media/${item.id}/${item.filename}`,\n\t\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\t})),\n\t\t\t\tcursor: result.nextCursor,\n\t\t\t\thasMore: !!result.nextCursor,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Create full media access with write operations.\n *\n * `getUploadUrlFn` is optional: when omitted, `getUploadUrl()` is derived from\n * `storage` (create a pending record + a signed PUT URL), mirroring the REST\n * `/_emdash/api/media/upload-url` endpoint. `upload()` only needs `storage`.\n * If storage is not provided, both throw at call time.\n */\nexport function createMediaAccessWithWrite(\n\tdb: Kysely<Database>,\n\tgetUploadUrlFn:\n\t\t| ((filename: string, contentType: string) => Promise<{ uploadUrl: string; mediaId: string }>)\n\t\t| undefined,\n\tstorage?: Storage,\n): MediaAccessWithWrite {\n\tconst mediaRepo = new MediaRepository(db);\n\tconst readAccess = createMediaAccess(db);\n\n\tconst getUploadUrl =\n\t\tgetUploadUrlFn ??\n\t\t(async (filename: string, contentType: string) => {\n\t\t\tif (!storage) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Media getUploadUrl() requires a storage backend. Configure storage in PluginContextFactoryOptions.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst basename = filename.split(\"/\").pop() ?? filename;\n\t\t\tconst dotIdx = basename.lastIndexOf(\".\");\n\t\t\tconst ext = dotIdx > 0 ? basename.slice(dotIdx).toLowerCase() : \"\";\n\t\t\tconst storageKey = `${ulid()}${ext}`;\n\n\t\t\tconst media = await mediaRepo.createPending({\n\t\t\t\tfilename: basename,\n\t\t\t\tmimeType: contentType,\n\t\t\t\tstorageKey,\n\t\t\t});\n\n\t\t\tconst signed = await storage.getSignedUploadUrl({\n\t\t\t\tkey: storageKey,\n\t\t\t\tcontentType,\n\t\t\t\texpiresIn: 3600,\n\t\t\t});\n\n\t\t\treturn { uploadUrl: signed.url, mediaId: media.id };\n\t\t});\n\n\treturn {\n\t\t...readAccess,\n\n\t\tgetUploadUrl,\n\n\t\tasync upload(\n\t\t\tfilename: string,\n\t\t\tcontentType: string,\n\t\t\tbytes: ArrayBuffer,\n\t\t): Promise<{ mediaId: string; storageKey: string; url: string }> {\n\t\t\tif (!storage) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Media upload() requires a storage backend. Configure storage in PluginContextFactoryOptions.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Generate a storage key with a unique prefix\n\t\t\tconst keyPrefix = ulid();\n\t\t\t// Extract extension from basename (ignore path separators)\n\t\t\tconst basename = filename.split(\"/\").pop() ?? filename;\n\t\t\tconst dotIdx = basename.lastIndexOf(\".\");\n\t\t\tconst ext = dotIdx > 0 ? basename.slice(dotIdx).toLowerCase() : \"\";\n\t\t\tconst storageKey = `${keyPrefix}${ext}`;\n\n\t\t\t// Upload to storage first\n\t\t\tawait storage.upload({\n\t\t\t\tkey: storageKey,\n\t\t\t\tbody: new Uint8Array(bytes),\n\t\t\t\tcontentType,\n\t\t\t});\n\n\t\t\t// Derive dimensions + LQIP placeholders (no-op for non-images).\n\t\t\tconst enriched = await enrichImageMetadata(new Uint8Array(bytes), contentType);\n\n\t\t\t// Create DB record — clean up storage on failure\n\t\t\tlet media;\n\t\t\ttry {\n\t\t\t\tmedia = await mediaRepo.create({\n\t\t\t\t\tfilename: basename,\n\t\t\t\t\tmimeType: contentType,\n\t\t\t\t\tsize: bytes.byteLength,\n\t\t\t\t\tstorageKey,\n\t\t\t\t\tstatus: \"ready\",\n\t\t\t\t\twidth: enriched.width,\n\t\t\t\t\theight: enriched.height,\n\t\t\t\t\tblurhash: enriched.blurhash,\n\t\t\t\t\tdominantColor: enriched.dominantColor,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait storage.delete(storageKey);\n\t\t\t\t} catch {\n\t\t\t\t\t// Best-effort cleanup\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tmediaId: media.id,\n\t\t\t\tstorageKey,\n\t\t\t\turl: `/_emdash/api/media/file/${storageKey}`,\n\t\t\t};\n\t\t},\n\n\t\tasync delete(id: string): Promise<boolean> {\n\t\t\tconst deleted = await mediaRepo.delete(id);\n\t\t\t// Plugins can delete media that's referenced by site settings\n\t\t\t// (`logo`, `favicon`, `seo.defaultOgImage`); the worker-scoped\n\t\t\t// resolved-URL cache must be dropped or it will keep serving\n\t\t\t// 404s. Matches the invalidation in\n\t\t\t// `EmDashRuntime.handleMediaDelete`.\n\t\t\tif (deleted) {\n\t\t\t\tinvalidateSiteSettingsCache();\n\t\t\t}\n\t\t\treturn deleted;\n\t\t},\n\t};\n}\n\n// =============================================================================\n// HTTP Access\n// =============================================================================\n\n/** Maximum number of redirects to follow in plugin HTTP access */\nconst MAX_PLUGIN_REDIRECTS = 5;\n\n/**\n * Check if a hostname matches any pattern in the allowed list.\n * Patterns: \"*\" matches all, \"*.example.com\" matches subdomains AND bare \"example.com\",\n * \"api.example.com\" matches exactly.\n */\nfunction isHostAllowed(host: string, allowedHosts: string[]): boolean {\n\treturn allowedHosts.some((pattern) => {\n\t\tif (pattern === \"*\") return true;\n\t\tif (pattern.startsWith(\"*.\")) {\n\t\t\tconst suffix = pattern.slice(1); // \".example.com\"\n\t\t\t// Match subdomains (foo.example.com) and bare domain (example.com)\n\t\t\treturn host.endsWith(suffix) || host === pattern.slice(2);\n\t\t}\n\t\treturn host === pattern;\n\t});\n}\n\n/**\n * Create HTTP access with host validation.\n *\n * Uses redirect: \"manual\" to re-validate each redirect target against\n * the allowedHosts list, preventing redirects to unauthorized hosts.\n */\nexport function createHttpAccess(pluginId: string, allowedHosts: string[]): HttpAccess {\n\treturn {\n\t\tasync fetch(url: string, init?: RequestInit): Promise<Response> {\n\t\t\t// Deny by default — plugins must declare allowed hosts\n\t\t\tif (allowedHosts.length === 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Plugin \"${pluginId}\" has no allowed hosts configured. ` +\n\t\t\t\t\t\t`Add hosts to the plugin's allowedHosts array to enable HTTP requests.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet currentUrl = url;\n\t\t\tlet currentInit = init;\n\n\t\t\tfor (let i = 0; i <= MAX_PLUGIN_REDIRECTS; i++) {\n\t\t\t\tconst hostname = new URL(currentUrl).hostname;\n\t\t\t\tif (!isHostAllowed(hostname, allowedHosts)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Plugin \"${pluginId}\" is not allowed to fetch from host \"${hostname}\". ` +\n\t\t\t\t\t\t\t`Allowed hosts: ${allowedHosts.join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst response = await globalThis.fetch(currentUrl, {\n\t\t\t\t\t...currentInit,\n\t\t\t\t\tredirect: \"manual\",\n\t\t\t\t});\n\n\t\t\t\t// Not a redirect -- return directly\n\t\t\t\tif (response.status < 300 || response.status >= 400) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Extract redirect target\n\t\t\t\tconst location = response.headers.get(\"Location\");\n\t\t\t\tif (!location) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Resolve relative redirects; strip credentials on cross-origin hops\n\t\t\t\tconst previousOrigin = new URL(currentUrl).origin;\n\t\t\t\tcurrentUrl = new URL(location, currentUrl).href;\n\t\t\t\tconst nextOrigin = new URL(currentUrl).origin;\n\n\t\t\t\tif (previousOrigin !== nextOrigin && currentInit) {\n\t\t\t\t\tcurrentInit = stripCredentialHeaders(currentInit);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthrow new Error(`Plugin \"${pluginId}\": too many redirects (max ${MAX_PLUGIN_REDIRECTS})`);\n\t\t},\n\t};\n}\n\n/**\n * Create unrestricted HTTP access (for plugins with network:fetch:any capability).\n * No host validation, but applies SSRF protection on redirect targets to\n * prevent plugins from being tricked into reaching internal services.\n */\nexport function createUnrestrictedHttpAccess(pluginId: string): HttpAccess {\n\treturn {\n\t\tasync fetch(url: string, init?: RequestInit): Promise<Response> {\n\t\t\tlet currentUrl = url;\n\t\t\tlet currentInit = init;\n\n\t\t\tfor (let i = 0; i <= MAX_PLUGIN_REDIRECTS; i++) {\n\t\t\t\t// Validate each URL against SSRF rules (private IPs, metadata\n\t\t\t\t// endpoints, wildcard DNS, resolved-IP private ranges).\n\t\t\t\ttry {\n\t\t\t\t\tawait resolveAndValidateExternalUrl(currentUrl);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconst msg = e instanceof SsrfError ? e.message : \"SSRF validation failed\";\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Plugin \"${pluginId}\": blocked fetch to \"${new URL(currentUrl).hostname}\": ${msg}`,\n\t\t\t\t\t\t{ cause: e },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst response = await globalThis.fetch(currentUrl, {\n\t\t\t\t\t...currentInit,\n\t\t\t\t\tredirect: \"manual\",\n\t\t\t\t});\n\n\t\t\t\t// Not a redirect -- return directly\n\t\t\t\tif (response.status < 300 || response.status >= 400) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Extract redirect target\n\t\t\t\tconst location = response.headers.get(\"Location\");\n\t\t\t\tif (!location) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Resolve relative redirects; strip credentials on cross-origin hops\n\t\t\t\tconst previousOrigin = new URL(currentUrl).origin;\n\t\t\t\tcurrentUrl = new URL(location, currentUrl).href;\n\t\t\t\tconst nextOrigin = new URL(currentUrl).origin;\n\n\t\t\t\tif (previousOrigin !== nextOrigin && currentInit) {\n\t\t\t\t\tcurrentInit = stripCredentialHeaders(currentInit);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthrow new Error(`Plugin \"${pluginId}\": too many redirects (max ${MAX_PLUGIN_REDIRECTS})`);\n\t\t},\n\t};\n}\n\n/**\n * Create blocked HTTP access (for plugins without network:request capability)\n */\nexport function createBlockedHttpAccess(pluginId: string): HttpAccess {\n\treturn {\n\t\tasync fetch(): Promise<never> {\n\t\t\tthrow new Error(\n\t\t\t\t`Plugin \"${pluginId}\" does not have the \"network:request\" capability. ` +\n\t\t\t\t\t`Add \"network:request\" to the plugin's capabilities to enable HTTP requests.`,\n\t\t\t);\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Log Access\n// =============================================================================\n\n/**\n * Create logger for a plugin\n */\nexport function createLogAccess(pluginId: string): LogAccess {\n\tconst prefix = `[plugin:${pluginId}]`;\n\n\treturn {\n\t\tdebug(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.debug(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.debug(prefix, message);\n\t\t\t}\n\t\t},\n\n\t\tinfo(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.info(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.info(prefix, message);\n\t\t\t}\n\t\t},\n\n\t\twarn(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.warn(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.warn(prefix, message);\n\t\t\t}\n\t\t},\n\n\t\terror(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.error(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.error(prefix, message);\n\t\t\t}\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Site Info\n// =============================================================================\n\nconst TRAILING_SLASH_RE = /\\/$/;\n\n/**\n * Options for creating site info\n */\nexport interface SiteInfoOptions {\n\t/** Site name from options table */\n\tsiteName?: string;\n\t/** Site URL from options table or Astro config */\n\tsiteUrl?: string;\n\t/** The site's platform origin (`custom_domain:default_url`), when hosted by a control plane. */\n\tplatformUrl?: string;\n\t/** Site locale from options table */\n\tlocale?: string;\n\t/** Astro's `trailingSlash` config (from `virtual:emdash/config`). */\n\ttrailingSlash?: \"always\" | \"never\" | \"ignore\";\n}\n\n/**\n * Create site info from config and settings.\n *\n * Resolution order for URL:\n * 1. options table (emdash:site_url)\n * 2. Astro `site` config\n * 3. fallback to empty string\n */\nexport function createSiteInfo(options: SiteInfoOptions): SiteInfo {\n\treturn {\n\t\tname: options.siteName ?? \"\",\n\t\turl: (options.siteUrl ?? \"\").replace(TRAILING_SLASH_RE, \"\"), // strip trailing slash\n\t\t...(options.platformUrl ? { platformUrl: options.platformUrl.replace(TRAILING_SLASH_RE, \"\") } : {}),\n\t\tlocale: options.locale ?? \"en\",\n\t\ttrailingSlash: options.trailingSlash ?? \"ignore\", // Astro's default\n\t};\n}\n\n/**\n * Create a URL helper that generates absolute URLs from relative paths.\n * Validates that path starts with \"/\" and rejects protocol-relative paths (\"//\").\n */\nexport function createUrlHelper(siteUrl: string): (path: string) => string {\n\tconst base = siteUrl.replace(TRAILING_SLASH_RE, \"\"); // strip trailing slash\n\n\treturn (path: string): string => {\n\t\tif (!path.startsWith(\"/\")) {\n\t\t\tthrow new Error(`URL path must start with \"/\", got: \"${path}\"`);\n\t\t}\n\t\tif (path.startsWith(\"//\")) {\n\t\t\tthrow new Error(`URL path must not be protocol-relative, got: \"${path}\"`);\n\t\t}\n\t\treturn `${base}${path}`;\n\t};\n}\n\n// =============================================================================\n// User Access\n// =============================================================================\n\n/**\n * Convert a UserRepository user to the plugin-facing UserInfo shape.\n * Strips sensitive fields (avatarUrl, emailVerified, data).\n */\nfunction toUserInfo(user: {\n\tid: string;\n\temail: string;\n\tname: string | null;\n\trole: number;\n\troleId?: string | null;\n\tcreatedAt: string;\n}): UserInfo {\n\treturn {\n\t\tid: user.id,\n\t\temail: user.email,\n\t\tname: user.name,\n\t\trole: user.role,\n\t\troleId: user.roleId ?? null,\n\t\tcreatedAt: user.createdAt,\n\t};\n}\n\n/**\n * Create read-only user access for plugins.\n * Excludes sensitive fields (password hashes, sessions, passkeys, avatar URL, data).\n */\nexport function createUserAccess(db: Kysely<Database>): UserAccess {\n\tconst userRepo = new UserRepository(db);\n\n\treturn {\n\t\tasync get(id: string): Promise<UserInfo | null> {\n\t\t\tconst user = await userRepo.findById(id);\n\t\t\tif (!user) return null;\n\t\t\treturn toUserInfo(user);\n\t\t},\n\n\t\tasync getByEmail(email: string): Promise<UserInfo | null> {\n\t\t\tconst user = await userRepo.findByEmail(email);\n\t\t\tif (!user) return null;\n\t\t\treturn toUserInfo(user);\n\t\t},\n\n\t\tasync list(opts?: {\n\t\t\trole?: number;\n\t\t\tlimit?: number;\n\t\t\tcursor?: string;\n\t\t}): Promise<{ items: UserInfo[]; nextCursor?: string }> {\n\t\t\tconst result = await userRepo.findMany({\n\t\t\t\trole: opts?.role as 10 | 20 | 30 | 40 | 50 | undefined,\n\t\t\t\tcursor: opts?.cursor,\n\t\t\t\tlimit: opts?.limit,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\titems: result.items.map(toUserInfo),\n\t\t\t\tnextCursor: result.nextCursor,\n\t\t\t};\n\t\t},\n\n\t\tasync listRoles() {\n\t\t\tconst roles = await new AuthzRepository(db).listRoles();\n\t\t\treturn roles.map((r) => ({ id: r.id, slug: r.slug, name: r.name, level: r.level, builtin: r.builtin }));\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Plugin Context Factory\n// =============================================================================\n\nexport interface PluginContextFactoryOptions {\n\tdb: Kysely<Database>;\n\tbeforeContentWrite?: () => Promise<void>;\n\t/**\n\t * Resolver for the database connection, preferred over `db` when present.\n\t * Called per `createContext()` so connection-backed adapters (e.g. Postgres\n\t * over Hyperdrive) get the current request/event-scoped connection from ALS\n\t * rather than a snapshot of the per-isolate singleton — reusing the\n\t * singleton's socket from a later event trips workerd's cross-request I/O\n\t * guard. When omitted, `db` is used directly (correct for stateless\n\t * adapters like D1 and Node SQLite). `db` remains required as the fallback.\n\t */\n\tgetDb?: () => Kysely<Database>;\n\t/**\n\t * Storage backend for direct media uploads.\n\t * If not provided, upload() will throw.\n\t */\n\tstorage?: Storage;\n\t/**\n\t * Explicit provider for `ctx.media.getUploadUrl()`. Optional: when omitted\n\t * but `storage` is configured, the factory derives a working `getUploadUrl()`\n\t * (and `upload()`) from storage. Only when neither `getUploadUrl` nor\n\t * `storage` is present do media write operations become unavailable.\n\t */\n\tgetUploadUrl?: (\n\t\tfilename: string,\n\t\tcontentType: string,\n\t) => Promise<{ uploadUrl: string; mediaId: string }>;\n\t/**\n\t * Site information for ctx.site and ctx.url().\n\t * If not provided, site info will have empty defaults.\n\t */\n\tsiteInfo?: SiteInfoOptions;\n\t/**\n\t * Callback to notify the cron scheduler that the next due time may have changed.\n\t * If not provided, ctx.cron will not be available.\n\t */\n\tcronReschedule?: () => void;\n\t/**\n\t * Email pipeline instance for ctx.email.\n\t * If not provided (or no provider configured), ctx.email will be undefined.\n\t */\n\temailPipeline?: EmailPipeline;\n\t/**\n\t * Pre-resolved list of trusted proxy header names (from the runtime\n\t * `EmDashConfig.trustedProxyHeaders` or the env var). Plugin route\n\t * handlers pass this to `extractRequestMeta` so plugins see the same\n\t * client IP the core auth path does.\n\t */\n\ttrustedProxyHeaders?: string[];\n}\n\n/**\n * Factory for creating plugin contexts\n */\nexport class PluginContextFactory {\n\tprivate resolveDb: () => Kysely<Database>;\n\tprivate beforeContentWrite?: () => Promise<void>;\n\tprivate storage?: Storage;\n\tprivate getUploadUrl?: (\n\t\tfilename: string,\n\t\tcontentType: string,\n\t) => Promise<{ uploadUrl: string; mediaId: string }>;\n\tprivate site: SiteInfo;\n\tprivate urlHelper: (path: string) => string;\n\tprivate cronReschedule?: () => void;\n\tprivate emailPipeline?: EmailPipeline;\n\t/**\n\t * Plugin IDs already warned about a missing media-write backend, so the\n\t * warning fires once per factory instead of on every hook/route context\n\t * creation (which would spam logs for hook-participating plugins).\n\t */\n\tprivate warnedMissingMediaBackend = new Set<string>();\n\n\tconstructor(options: PluginContextFactoryOptions) {\n\t\tconst fixedDb = options.db;\n\t\tthis.resolveDb = options.getDb ?? (() => fixedDb);\n\t\tthis.beforeContentWrite = options.beforeContentWrite;\n\t\tthis.storage = options.storage;\n\t\tthis.getUploadUrl = options.getUploadUrl;\n\t\tthis.site = createSiteInfo(options.siteInfo ?? {});\n\t\tthis.urlHelper = createUrlHelper(this.site.url);\n\t\tthis.cronReschedule = options.cronReschedule;\n\t\tthis.emailPipeline = options.emailPipeline;\n\t}\n\n\t/**\n\t * Create the unified plugin context\n\t */\n\tcreateContext(plugin: ResolvedPlugin): PluginContext {\n\t\tconst capabilities = new Set(plugin.capabilities);\n\n\t\t// Resolve the connection once per context. For stateless adapters this\n\t\t// is the singleton; for connection-backed adapters it's the current\n\t\t// request/event-scoped connection from ALS. All repos below are built\n\t\t// from this local `db` so a hook never queries a stale singleton socket.\n\t\tconst db = this.resolveDb();\n\t\tconst optionsRepo = new OptionsRepository(db);\n\n\t\t// Always available\n\t\tconst kv = createKVAccess(optionsRepo, plugin.id);\n\t\tconst log = createLogAccess(plugin.id);\n\t\tconst storage = createStorageAccess(db, plugin.id, plugin.storage);\n\n\t\t// Capability-gated: content\n\t\t// Note: capabilities reach this point already normalized to the\n\t\t// canonical names by definePlugin / adaptSandboxEntry. Deprecated\n\t\t// names (\"read:content\", \"write:content\") never appear here.\n\t\tlet content: ContentAccess | ContentAccessWithWrite | undefined;\n\t\tif (capabilities.has(\"content:write\")) {\n\t\t\tcontent = createContentAccessWithWrite(db, this.beforeContentWrite);\n\t\t} else if (capabilities.has(\"content:read\")) {\n\t\t\tcontent = createContentAccess(db);\n\t\t}\n\n\t\t// Capability-gated: taxonomies (read-only)\n\t\tlet taxonomies: TaxonomyAccess | undefined;\n\t\tif (capabilities.has(\"taxonomies:read\")) {\n\t\t\ttaxonomies = createTaxonomyAccess(db);\n\t\t}\n\n\t\t// Capability-gated: media\n\t\t// `upload()` only needs `storage`; `getUploadUrl()` is derived from\n\t\t// storage when no explicit provider is wired. Granting write access on\n\t\t// either avoids silently degrading media:write to read-only — the bug\n\t\t// where the runtime threads `storage` but not `getUploadUrl`.\n\t\tlet media: MediaAccess | MediaAccessWithWrite | undefined;\n\t\tif (capabilities.has(\"media:write\")) {\n\t\t\tif (this.getUploadUrl || this.storage) {\n\t\t\t\tmedia = createMediaAccessWithWrite(db, this.getUploadUrl, this.storage);\n\t\t\t} else {\n\t\t\t\tif (!this.warnedMissingMediaBackend.has(plugin.id)) {\n\t\t\t\t\tthis.warnedMissingMediaBackend.add(plugin.id);\n\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\"declares the media:write capability but no storage backend is configured; upload() is unavailable.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (capabilities.has(\"media:read\")) {\n\t\t\t\t\tmedia = createMediaAccess(db);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (capabilities.has(\"media:read\")) {\n\t\t\tmedia = createMediaAccess(db);\n\t\t}\n\n\t\t// Capability-gated: http\n\t\tlet http: HttpAccess | undefined;\n\t\tif (capabilities.has(\"network:request:unrestricted\")) {\n\t\t\thttp = createUnrestrictedHttpAccess(plugin.id);\n\t\t} else if (capabilities.has(\"network:request\")) {\n\t\t\thttp = createHttpAccess(plugin.id, plugin.allowedHosts);\n\t\t}\n\n\t\t// Capability-gated: users\n\t\tlet users: UserAccess | undefined;\n\t\tif (capabilities.has(\"users:read\")) {\n\t\t\tusers = createUserAccess(db);\n\t\t}\n\n\t\tlet github: GitHubConnectionAccess | undefined;\n\t\tif (capabilities.has(\"github:connection\")) {\n\t\t\tgithub = {\n\t\t\t\tasync get() {\n\t\t\t\t\tconst map = await new OptionsRepository(db).getMany<string>([\n\t\t\t\t\t\t\"github:token\",\n\t\t\t\t\t\t\"github:owner\",\n\t\t\t\t\t\t\"github:repo\",\n\t\t\t\t\t\t\"github:branch\",\n\t\t\t\t\t\t\"emdash:frontend_token\",\n\t\t\t\t\t]);\n\t\t\t\t\tconst token = map.get(\"github:token\") ?? \"\";\n\t\t\t\t\tconst owner = map.get(\"github:owner\") ?? \"\";\n\t\t\t\t\tconst repo = map.get(\"github:repo\") ?? \"\";\n\t\t\t\t\tif (!token || !owner || !repo) return null;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\towner,\n\t\t\t\t\t\trepo,\n\t\t\t\t\t\tbranch: map.get(\"github:branch\") || \"main\",\n\t\t\t\t\t\tfrontendToken: map.get(\"emdash:frontend_token\") ?? \"\",\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Cron access — always available (scoped to plugin), but only if\n\t\t// the runtime provided a reschedule callback (i.e. cron is wired up).\n\t\tlet cron: CronAccess | undefined;\n\t\tif (this.cronReschedule) {\n\t\t\tcron = new CronAccessImpl(db, plugin.id, this.cronReschedule);\n\t\t}\n\n\t\t// Email access — requires email:send capability AND a configured provider\n\t\tlet email: EmailAccess | undefined;\n\t\tif (capabilities.has(\"email:send\") && this.emailPipeline?.isAvailable()) {\n\t\t\tconst pipeline = this.emailPipeline;\n\t\t\tconst pluginId = plugin.id;\n\t\t\temail = {\n\t\t\t\tsend: (message) => pipeline.send(message, pluginId),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tplugin: {\n\t\t\t\tid: plugin.id,\n\t\t\t\tversion: plugin.version,\n\t\t\t},\n\t\t\tstorage,\n\t\t\tkv,\n\t\t\tcontent,\n\t\t\ttaxonomies,\n\t\t\tmedia,\n\t\t\thttp,\n\t\t\tlog,\n\t\t\tsite: this.site,\n\t\t\turl: this.urlHelper,\n\t\t\tusers,\n\t\t\tgithub,\n\t\t\tcron,\n\t\t\temail,\n\t\t};\n\t}\n}\n\n/**\n * Create a plugin context for a resolved plugin\n */\nexport function createPluginContext(\n\toptions: PluginContextFactoryOptions,\n\tplugin: ResolvedPlugin,\n): PluginContext {\n\tconst factory = new PluginContextFactory(options);\n\treturn factory.createContext(plugin);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAa,oBAAb,cAAuC,MAAM;CAC5C,YACC,SACA,AAAO,OACP,AAAO,YACN;AACD,QAAM,QAAQ;EAHP;EACA;AAGP,OAAK,OAAO;;;;;;AAOd,SAAgB,cAAc,OAAyC;AACtE,KAAI,OAAO,UAAU,YAAY,UAAU,K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