@adatechnology/content-module 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -1
- package/dist/index.cjs +1013 -106
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +546 -3
- package/dist/index.d.ts +546 -3
- package/dist/index.js +936 -45
- package/dist/index.js.map +1 -1
- package/dist/migrations/0001_scheduling.sql +32 -0
- package/dist/migrations/meta/0001_snapshot.json +454 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/package.json +3 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../node_modules/.pnpm/tsup@8.5.1_@swc+core@1.16.2_@swc+helpers@0.5.23__jiti@2.7.0_postcss@8.5.28_tsx@4.23.13_typescript@5.9.3_yaml@2.9.1/node_modules/tsup/assets/esm_shims.js","../src/ContentModule.ts","../src/repositories/PostRepository.ts","../src/schema/schema.ts","../src/repositories/conditions.ts","../src/use-cases/Feed.use-cases.ts","../src/use-cases/Post.use-cases.ts","../src/shared/isUniqueViolation.ts","../src/shared/notifyPostChanged.ts","../src/shared/toContract.ts","../src/use-cases/PublicPost.use-cases.ts","../src/use-cases/UploadCoverImage.use-case.ts","../src/shared/coverImage.constant.ts","../src/http/adminRoutes.ts","../src/http/requireCompany.ts","../src/http/publicRoutes.ts","../src/http/routes.ts","../src/runMigrations.ts","../src/testing/inMemoryPostStore.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Composição raiz do módulo de conteúdo (blog, novidades, notícias). Recebe a conexão Drizzle do\n * host e devolve os use-cases; as rotas saem de `createContentRoutes` sobre este objeto.\n */\n\nimport { ConfigMissingError } from '@adatechnology/content-contracts'\nimport type {\n ClockPort,\n ContentHooks,\n ContentImageStoragePort,\n ContentModuleConfig,\n LoggerPort,\n} from '@adatechnology/content-contracts'\n\nimport type { ContentDatabase } from './database.types'\nimport { PostRepository } from './repositories/PostRepository'\nimport type { ContentDependencies, PostStorePort } from './use-cases/contentModule.types'\nimport { BuildFeedUseCase, ListSitemapEntriesUseCase } from './use-cases/Feed.use-cases'\nimport {\n ArchivePostUseCase,\n CreatePostUseCase,\n GetPostUseCase,\n ListPostsUseCase,\n PublishPostUseCase,\n UnpublishPostUseCase,\n UpdatePostUseCase,\n} from './use-cases/Post.use-cases'\nimport {\n GetPublishedPostBySlugUseCase,\n ListPublishedPostsUseCase,\n ListTagsUseCase,\n} from './use-cases/PublicPost.use-cases'\nimport { UploadCoverImageUseCase } from './use-cases/UploadCoverImage.use-case'\n\nexport type ContentModuleProviders = {\n /** Sem storage, a capa é só por URL e a rota de upload não sobe. */\n readonly imageStorage?: ContentImageStoragePort\n /** Padrão: relógio do sistema. Os testes injetam um fixo para provar o agendamento. */\n readonly clock?: ClockPort\n readonly logger?: LoggerPort\n /** Troca a persistência (ex.: dublê em memória num teste do host). Padrão: Drizzle sobre `db`. */\n readonly postStore?: PostStorePort\n}\n\nexport type CreateContentModuleParams = {\n readonly db?: ContentDatabase\n readonly config?: ContentModuleConfig\n readonly providers?: ContentModuleProviders\n readonly hooks?: ContentHooks\n}\n\nexport type ContentModule = {\n readonly useCases: {\n readonly createPost: CreatePostUseCase\n readonly updatePost: UpdatePostUseCase\n readonly archivePost: ArchivePostUseCase\n readonly publishPost: PublishPostUseCase\n readonly unpublishPost: UnpublishPostUseCase\n readonly getPost: GetPostUseCase\n readonly listPosts: ListPostsUseCase\n readonly getPublishedPostBySlug: GetPublishedPostBySlugUseCase\n readonly listPublishedPosts: ListPublishedPostsUseCase\n readonly listTags: ListTagsUseCase\n /** Capacidade por ausência: sem `providers.imageStorage`, não existe. */\n readonly uploadCoverImage?: UploadCoverImageUseCase\n /** Sem `config.feed`, feed e sitemap não existem. */\n readonly buildFeed?: BuildFeedUseCase\n readonly listSitemapEntries?: ListSitemapEntriesUseCase\n }\n readonly config: ContentModuleConfig\n}\n\nconst SYSTEM_CLOCK: ClockPort = { now: () => new Date() }\n\nfunction assertValidConfig(config: ContentModuleConfig): void {\n // Feed com endereço relativo geraria links quebrados em todo leitor de RSS — falha no boot.\n if (config.feed && !/^https?:\\/\\/[^/]/i.test(config.feed.siteUrl)) throw new ConfigMissingError('feed.siteUrl')\n if (config.feed && !config.feed.title.trim()) throw new ConfigMissingError('feed.title')\n if (config.feed?.postPathTemplate && !config.feed.postPathTemplate.includes('{slug}')) {\n throw new ConfigMissingError('feed.postPathTemplate')\n }\n if (config.wordsPerMinute !== undefined && !(config.wordsPerMinute > 0))\n throw new ConfigMissingError('wordsPerMinute')\n}\n\nexport function createContentModule(params: CreateContentModuleParams): ContentModule {\n const config = params.config ?? {}\n assertValidConfig(config)\n\n const posts = params.providers?.postStore ?? (params.db ? new PostRepository(params.db) : undefined)\n if (!posts) throw new ConfigMissingError('db')\n\n const dependencies: ContentDependencies = {\n posts,\n config,\n clock: params.providers?.clock ?? SYSTEM_CLOCK,\n ...(params.hooks ? { hooks: params.hooks } : {}),\n ...(params.providers?.imageStorage ? { imageStorage: params.providers.imageStorage } : {}),\n ...(params.providers?.logger ? { logger: params.providers.logger } : {}),\n }\n\n return {\n useCases: {\n createPost: new CreatePostUseCase(dependencies),\n updatePost: new UpdatePostUseCase(dependencies),\n archivePost: new ArchivePostUseCase(dependencies),\n publishPost: new PublishPostUseCase(dependencies),\n unpublishPost: new UnpublishPostUseCase(dependencies),\n getPost: new GetPostUseCase(dependencies),\n listPosts: new ListPostsUseCase(dependencies),\n getPublishedPostBySlug: new GetPublishedPostBySlugUseCase(dependencies),\n listPublishedPosts: new ListPublishedPostsUseCase(dependencies),\n listTags: new ListTagsUseCase(dependencies),\n ...(dependencies.imageStorage ? { uploadCoverImage: new UploadCoverImageUseCase(dependencies) } : {}),\n ...(config.feed\n ? {\n buildFeed: new BuildFeedUseCase(dependencies, config.feed),\n listSitemapEntries: new ListSitemapEntriesUseCase(dependencies, config.feed),\n }\n : {}),\n },\n config,\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { asc, desc, sql } from 'drizzle-orm'\nimport type { TagCount } from '@adatechnology/content-contracts'\n\nimport type { ContentDatabase } from '../database.types'\nimport { posts, type NewPostRow, type PostRow } from '../schema/schema'\nimport type { PostAdminListQuery, PostPage, PostPublicListQuery, PostStorePort } from '../use-cases/contentModule.types'\nimport {\n postAdminListCondition,\n postOwnedByCondition,\n postPublicCondition,\n postPublicSlugCondition,\n postSlugCondition,\n} from './conditions'\n\nconst TAG_LIST_LIMIT = 200\n\nexport class PostRepository implements PostStorePort {\n constructor(private readonly db: ContentDatabase) {}\n\n async create(values: NewPostRow): Promise<PostRow> {\n const [row] = await this.db.insert(posts).values(values).returning()\n if (!row) throw new Error('content-module: insert em posts não retornou linha')\n return row\n }\n\n async findById(params: { companyId: string; id: string }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postOwnedByCondition(params)).limit(1)\n return row\n }\n\n async findBySlug(params: { companyId: string; slug: string }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postSlugCondition(params)).limit(1)\n return row\n }\n\n async findPublicBySlug(params: { companyId: string; slug: string; now: Date }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postPublicSlugCondition(params)).limit(1)\n return row\n }\n\n async update(params: { companyId: string; id: string; values: Partial<NewPostRow> }): Promise<PostRow | undefined> {\n const [row] = await this.db\n .update(posts)\n .set({ ...params.values, updatedAt: new Date() })\n .where(postOwnedByCondition(params))\n .returning()\n return row\n }\n\n async listForAdmin(query: PostAdminListQuery): Promise<PostPage> {\n const where = postAdminListCondition(query)\n // Mais recente primeiro pela última edição: é o que o painel está mexendo agora.\n const [rows, [counted]] = await Promise.all([\n this.db\n .select()\n .from(posts)\n .where(where)\n .orderBy(desc(posts.updatedAt), asc(posts.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n this.db\n .select({ value: sql<number>`count(*)::int` })\n .from(posts)\n .where(where),\n ])\n return { rows, total: counted?.value ?? 0 }\n }\n\n async listPublic(query: PostPublicListQuery): Promise<PostPage> {\n const where = postPublicCondition(query)\n const [rows, [counted]] = await Promise.all([\n this.db\n .select()\n .from(posts)\n .where(where)\n .orderBy(desc(posts.publishedAt), asc(posts.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n this.db\n .select({ value: sql<number>`count(*)::int` })\n .from(posts)\n .where(where),\n ])\n return { rows, total: counted?.value ?? 0 }\n }\n\n async listTags(params: { companyId: string; publicAt?: Date }): Promise<readonly TagCount[]> {\n const where = params.publicAt\n ? postPublicCondition({ companyId: params.companyId, now: params.publicAt })\n : postAdminListCondition({ companyId: params.companyId, now: new Date() })\n // Subconsulta em vez de `group by unnest(...)`: o Postgres não aceita função que devolve\n // conjunto no GROUP BY.\n const postTags = this.db\n .select({ tag: sql<string>`unnest(${posts.tags})`.as('tag') })\n .from(posts)\n .where(where)\n .as('post_tags')\n const rows = await this.db\n .select({ tag: postTags.tag, count: sql<number>`count(*)::int` })\n .from(postTags)\n .groupBy(postTags.tag)\n .orderBy(sql`count(*) desc`, asc(postTags.tag))\n .limit(TAG_LIST_LIMIT)\n return rows\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { index, integer, pgSchema, text, timestamp, uniqueIndex, uuid, varchar } from 'drizzle-orm/pg-core'\n\n// Schema Postgres dedicado — o módulo nunca escreve no `public` do host.\nexport const contentSchema = pgSchema('content')\n\n// `status` em varchar e não ENUM nativo; os valores espelham `POST_STATUS` do contracts.\nexport const posts = contentSchema.table(\n 'posts',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n slug: varchar('slug', { length: 120 }).notNull(),\n title: varchar('title', { length: 200 }).notNull(),\n excerpt: varchar('excerpt', { length: 500 }),\n body: text('body').notNull().default(''),\n coverImageUrl: varchar('cover_image_url', { length: 2048 }),\n coverImageAlt: varchar('cover_image_alt', { length: 300 }),\n tags: text('tags').array().notNull().default([]),\n status: varchar('status', { length: 12 }).notNull().default('draft'),\n publishedAt: timestamp('published_at', { withTimezone: true }),\n authorName: varchar('author_name', { length: 120 }),\n seoTitle: varchar('seo_title', { length: 200 }),\n seoDescription: varchar('seo_description', { length: 320 }),\n canonicalUrl: varchar('canonical_url', { length: 2048 }),\n readingTimeMinutes: integer('reading_time_minutes').notNull().default(1),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n // Sem `where deleted_at`: excluir é arquivar, e o slug arquivado continua reservado — reusá-lo\n // faria um link antigo (já compartilhado) abrir outro post.\n uniqueIndex('idx_posts_company_slug').on(table.companyId, table.slug),\n // Serve a listagem pública: empresa + status + ordem por data.\n index('idx_posts_company_status_published').on(table.companyId, table.status, table.publishedAt),\n index('idx_posts_tags').using('gin', table.tags),\n ],\n)\n\nexport type PostRow = typeof posts.$inferSelect\nexport type NewPostRow = typeof posts.$inferInsert\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Toda condição alcançável por uma requisição vive aqui como função pura exportada — a mesma que o\n * repositório chama e que `isolation.test.ts` renderiza em SQL. Um refactor que esqueça o filtro\n * de empresa quebra o teste na hora.\n */\n\nimport { and, arrayContains, eq, gt, inArray, lte, or, sql, type SQL } from 'drizzle-orm'\nimport { POST_STATUS, type PostStatus } from '@adatechnology/content-contracts'\n\nimport { posts } from '../schema/schema'\n\nexport function postOwnedByCondition(params: { companyId: string; id: string }): SQL {\n return and(eq(posts.companyId, params.companyId), eq(posts.id, params.id)) as SQL\n}\n\nexport function postSlugCondition(params: { companyId: string; slug: string }): SQL {\n return and(eq(posts.companyId, params.companyId), eq(posts.slug, params.slug)) as SQL\n}\n\nexport function postAdminListCondition(params: {\n companyId: string\n status?: PostStatus\n tag?: string\n search?: string\n now: Date\n}): SQL {\n const conditions: SQL[] = [eq(posts.companyId, params.companyId)]\n if (params.status) conditions.push(statusCondition(params.status, params.now))\n if (params.tag) conditions.push(arrayContains(posts.tags, [params.tag]))\n if (params.search) {\n const pattern = `%${params.search.replace(/[\\\\%_]/g, (character) => `\\\\${character}`)}%`\n conditions.push(sql`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`)\n }\n return and(...conditions) as SQL\n}\n\n/**\n * Filtra pelo status que o painel MOSTRA: agendado cuja hora passou aparece como publicado, então\n * o filtro \"publicados\" o inclui e o filtro \"agendados\" o exclui.\n */\nfunction statusCondition(status: PostStatus, now: Date): SQL {\n if (status === POST_STATUS.PUBLISHED) {\n return or(\n eq(posts.status, POST_STATUS.PUBLISHED),\n and(eq(posts.status, POST_STATUS.SCHEDULED), lte(posts.publishedAt, now)),\n ) as SQL\n }\n if (status === POST_STATUS.SCHEDULED) {\n return and(eq(posts.status, POST_STATUS.SCHEDULED), gt(posts.publishedAt, now)) as SQL\n }\n return eq(posts.status, status)\n}\n\n/**\n * Público = publicado ou agendado cuja hora chegou. `scheduled` entra na condição justamente para\n * que o agendamento valha sem cron: no instante de `published_at` o post passa a casar aqui.\n */\nexport function postPublicCondition(params: { companyId: string; now: Date; tag?: string }): SQL {\n const conditions: SQL[] = [\n eq(posts.companyId, params.companyId),\n inArray(posts.status, [POST_STATUS.PUBLISHED, POST_STATUS.SCHEDULED]),\n lte(posts.publishedAt, params.now),\n ]\n if (params.tag) conditions.push(arrayContains(posts.tags, [params.tag]))\n return and(...conditions) as SQL\n}\n\nexport function postPublicSlugCondition(params: { companyId: string; slug: string; now: Date }): SQL {\n return and(postPublicCondition(params), eq(posts.slug, params.slug)) as SQL\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * RSS, Atom e entradas de sitemap do site público, a partir de `config.feed`. Sem essa config os\n * use-cases nem são construídos e as rotas não sobem.\n */\n\nimport {\n buildAtomFeed,\n buildExcerpt,\n buildPostUrl,\n buildRssFeed,\n renderMarkdownToHtml,\n type ContentFeedConfig,\n type FeedChannel,\n type FeedItem,\n type SitemapEntry,\n} from '@adatechnology/content-contracts'\n\nimport type { PostRow } from '../schema/schema'\nimport type { ContentDependencies } from './contentModule.types'\n\nconst DEFAULT_ITEM_LIMIT = 20\n// O protocolo de sitemap aceita até 50 mil URLs por arquivo; blog real fica muito abaixo disso.\nconst SITEMAP_LIMIT = 50_000\n\nexport const FEED_FORMAT = { RSS: 'rss', ATOM: 'atom' } as const\nexport type FeedFormat = (typeof FEED_FORMAT)[keyof typeof FEED_FORMAT]\n\nexport class BuildFeedUseCase {\n constructor(\n private readonly dependencies: ContentDependencies,\n private readonly feed: ContentFeedConfig,\n ) {}\n\n async execute(params: {\n readonly companyId: string\n readonly format: FeedFormat\n readonly feedUrl?: string\n }): Promise<string> {\n const now = this.dependencies.clock.now()\n const page = await this.dependencies.posts.listPublic({\n companyId: params.companyId,\n now,\n page: 1,\n pageSize: this.feed.itemLimit ?? DEFAULT_ITEM_LIMIT,\n })\n const channel: FeedChannel = {\n siteUrl: this.feed.siteUrl,\n title: this.feed.title,\n ...(this.feed.description ? { description: this.feed.description } : {}),\n ...(this.feed.language ? { language: this.feed.language } : {}),\n ...(params.feedUrl ? { feedUrl: params.feedUrl } : {}),\n }\n const items = page.rows.map((row) => this.toItem(row))\n return params.format === FEED_FORMAT.ATOM\n ? buildAtomFeed({ channel, items, now })\n : buildRssFeed({ channel, items })\n }\n\n private toItem(row: PostRow): FeedItem {\n return {\n title: row.title,\n url: buildPostUrl({ siteUrl: this.feed.siteUrl, slug: row.slug, postPathTemplate: this.feed.postPathTemplate }),\n publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n summary: row.excerpt ?? buildExcerpt(row.body),\n ...((this.feed.includeContent ?? true)\n ? { contentHtml: renderMarkdownToHtml(row.body, { headingIds: false }) }\n : {}),\n ...(row.authorName ? { authorName: row.authorName } : {}),\n categories: row.tags,\n ...(row.coverImageUrl ? { imageUrl: row.coverImageUrl } : {}),\n }\n }\n}\n\nexport class ListSitemapEntriesUseCase {\n constructor(\n private readonly dependencies: ContentDependencies,\n private readonly feed: ContentFeedConfig,\n ) {}\n\n /** Entradas para o host juntar ao sitemap dele — o módulo não é dono do sitemap do site. */\n async execute(params: { readonly companyId: string }): Promise<readonly SitemapEntry[]> {\n const page = await this.dependencies.posts.listPublic({\n companyId: params.companyId,\n now: this.dependencies.clock.now(),\n page: 1,\n pageSize: SITEMAP_LIMIT,\n })\n return page.rows.map((row) => ({\n loc: buildPostUrl({ siteUrl: this.feed.siteUrl, slug: row.slug, postPathTemplate: this.feed.postPathTemplate }),\n lastmod: row.updatedAt.toISOString(),\n }))\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Casos de uso do painel: criar, editar, arquivar, publicar/agendar, despublicar, ler e listar.\n * Todos validam a entrada com o schema do contracts de novo — o host pode chamar o use-case sem\n * passar pela rota, e a regra não pode depender de quem chamou.\n */\n\nimport {\n createPostSchema,\n DuplicateSlugError,\n estimateReadingTimeMinutes,\n listPostsQuerySchema,\n normalizeTags,\n POST_EVENT,\n POST_STATUS,\n PostNotFoundError,\n publishPostSchema,\n slugify,\n updatePostSchema,\n withSlugSuffix,\n type CreatePostInput,\n type ListPostsQuery,\n type Paginated,\n type Post,\n type PostEventType,\n type PostSummary,\n type PublishPostInput,\n type UpdatePostInput,\n} from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../schema/schema'\nimport { isUniqueViolation } from '../shared/isUniqueViolation'\nimport { notifyPostChanged } from '../shared/notifyPostChanged'\nimport { toPagination, toPost, toPostSummary } from '../shared/toContract'\nimport type { ContentDependencies } from './contentModule.types'\n\nconst MAX_SLUG_ATTEMPTS = 50\nconst FALLBACK_SLUG = 'post'\n\nexport type PostReference = { readonly companyId: string; readonly id: string }\n\nabstract class PostUseCaseBase {\n constructor(protected readonly dependencies: ContentDependencies) {}\n\n protected now(): Date {\n return this.dependencies.clock.now()\n }\n\n protected async findOrFail(reference: PostReference): Promise<PostRow> {\n const row = await this.dependencies.posts.findById(reference)\n if (!row) throw new PostNotFoundError(reference.id)\n return row\n }\n\n protected async save(reference: PostReference, values: Partial<NewPostRow>, event: PostEventType): Promise<Post> {\n const row = await this.dependencies.posts.update({ ...reference, values }).catch((error: unknown) => {\n if (isUniqueViolation(error) && values.slug) throw new DuplicateSlugError(values.slug)\n throw error\n })\n if (!row) throw new PostNotFoundError(reference.id)\n const post = toPost(row, this.now())\n await notifyPostChanged(this.dependencies, event, post)\n return post\n }\n\n protected readingTime(body: string): number {\n return estimateReadingTimeMinutes(body, this.dependencies.config.wordsPerMinute)\n }\n\n protected async assertSlugAvailable(companyId: string, slug: string, ownId?: string): Promise<void> {\n const existing = await this.dependencies.posts.findBySlug({ companyId, slug })\n if (existing && existing.id !== ownId) throw new DuplicateSlugError(slug)\n }\n\n /** `titulo`, `titulo-2`, `titulo-3`… Sequencial de propósito: cada tentativa depende da anterior. */\n protected async generateSlug(companyId: string, title: string): Promise<string> {\n const base = slugify(title) || FALLBACK_SLUG\n for (let attempt = 1; attempt <= MAX_SLUG_ATTEMPTS; attempt += 1) {\n const candidate = withSlugSuffix(base, attempt)\n if (!(await this.dependencies.posts.findBySlug({ companyId, slug: candidate }))) return candidate\n }\n return withSlugSuffix(base, Date.now())\n }\n}\n\nfunction optionalFields(input: Omit<UpdatePostInput, 'slug' | 'title' | 'body' | 'tags'>): Partial<NewPostRow> {\n const values: Partial<NewPostRow> = {}\n if (input.excerpt !== undefined) values.excerpt = input.excerpt || null\n if (input.coverImageUrl !== undefined) values.coverImageUrl = input.coverImageUrl || null\n if (input.coverImageAlt !== undefined) values.coverImageAlt = input.coverImageAlt || null\n if (input.authorName !== undefined) values.authorName = input.authorName || null\n if (input.seoTitle !== undefined) values.seoTitle = input.seoTitle || null\n if (input.seoDescription !== undefined) values.seoDescription = input.seoDescription || null\n if (input.canonicalUrl !== undefined) values.canonicalUrl = input.canonicalUrl || null\n return values\n}\n\nexport class CreatePostUseCase extends PostUseCaseBase {\n async execute(params: { readonly companyId: string; readonly input: CreatePostInput }): Promise<Post> {\n const input = createPostSchema.parse(params.input)\n const { companyId } = params\n if (input.slug) await this.assertSlugAvailable(companyId, input.slug)\n const slug = input.slug ?? (await this.generateSlug(companyId, input.title))\n\n const row = await this.dependencies.posts\n .create({\n companyId,\n slug,\n title: input.title,\n body: input.body,\n tags: normalizeTags(input.tags ?? []),\n status: POST_STATUS.DRAFT,\n readingTimeMinutes: this.readingTime(input.body),\n ...optionalFields(input),\n })\n .catch((error: unknown) => {\n if (isUniqueViolation(error)) throw new DuplicateSlugError(slug)\n throw error\n })\n\n const post = toPost(row, this.now())\n await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, post)\n return post\n }\n}\n\nexport class UpdatePostUseCase extends PostUseCaseBase {\n /** Trocar o título não muda o slug: o endereço já pode ter sido compartilhado. */\n async execute(params: PostReference & { readonly input: UpdatePostInput }): Promise<Post> {\n const input = updatePostSchema.parse(params.input)\n const existing = await this.findOrFail(params)\n\n const values: Partial<NewPostRow> = optionalFields(input)\n if (input.title !== undefined) values.title = input.title\n if (input.body !== undefined) {\n values.body = input.body\n values.readingTimeMinutes = this.readingTime(input.body)\n }\n if (input.tags !== undefined) values.tags = normalizeTags(input.tags)\n if (input.slug !== undefined && input.slug !== existing.slug) {\n await this.assertSlugAvailable(params.companyId, input.slug, existing.id)\n values.slug = input.slug\n }\n return this.save(params, values, POST_EVENT.UPDATED)\n }\n}\n\nexport class PublishPostUseCase extends PostUseCaseBase {\n /** Sem data: publica agora. Data futura: agenda. Data passada: publica com a data informada. */\n async execute(params: PostReference & { readonly input?: PublishPostInput }): Promise<Post> {\n const input = publishPostSchema.parse(params.input ?? {})\n await this.findOrFail(params)\n const now = this.now()\n const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now\n const status = publishedAt > now ? POST_STATUS.SCHEDULED : POST_STATUS.PUBLISHED\n return this.save(params, { status, publishedAt }, POST_EVENT.PUBLISHED)\n }\n}\n\nexport class UnpublishPostUseCase extends PostUseCaseBase {\n /** Volta a rascunho e tira do ar na hora, inclusive cancelando um agendamento. */\n async execute(params: PostReference): Promise<Post> {\n await this.findOrFail(params)\n return this.save(params, { status: POST_STATUS.DRAFT, publishedAt: null }, POST_EVENT.UNPUBLISHED)\n }\n}\n\nexport class ArchivePostUseCase extends PostUseCaseBase {\n /** \"Excluir\" no painel é arquivar: some do site, mas o conteúdo e o slug continuam guardados. */\n async execute(params: PostReference): Promise<Post> {\n await this.findOrFail(params)\n return this.save(params, { status: POST_STATUS.ARCHIVED }, POST_EVENT.ARCHIVED)\n }\n}\n\nexport class GetPostUseCase extends PostUseCaseBase {\n async execute(params: PostReference): Promise<Post> {\n return toPost(await this.findOrFail(params), this.now())\n }\n}\n\nexport class ListPostsUseCase extends PostUseCaseBase {\n async execute(params: { readonly companyId: string } & Partial<ListPostsQuery>): Promise<Paginated<PostSummary>> {\n const { companyId, ...rawQuery } = params\n const query = listPostsQuerySchema.parse(rawQuery)\n const tag = query.tag ? normalizeTags([query.tag])[0] : undefined\n const now = this.now()\n const page = await this.dependencies.posts.listForAdmin({ companyId, ...query, now, ...(tag ? { tag } : {}) })\n return {\n data: page.rows.map((row) => toPostSummary(row, now)),\n pagination: toPagination({ total: page.total, page: query.page, pageSize: query.pageSize }),\n }\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nconst UNIQUE_VIOLATION = '23505'\n\n/**\n * Cada driver embrulha o erro do Postgres de um jeito (`code` direto, ou em `cause`). A checagem\n * prévia de slug não fecha a corrida entre dois saves simultâneos; o índice único fecha, e isto\n * traduz a violação para o 409 do domínio.\n */\nexport function isUniqueViolation(error: unknown): boolean {\n let current: unknown = error\n for (let depth = 0; depth < 3 && typeof current === 'object' && current !== null; depth += 1) {\n if ((current as { code?: unknown }).code === UNIQUE_VIOLATION) return true\n current = (current as { cause?: unknown }).cause\n }\n return false\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { Post, PostEventType } from '@adatechnology/content-contracts'\n\nimport type { ContentDependencies } from '../use-cases/contentModule.types'\n\n/**\n * O gancho do host roda depois da escrita, e falha nele não desfaz o que já foi gravado: o post\n * publicado continua publicado mesmo que a purga de cache do host caia. Por isso o catch local.\n */\nexport async function notifyPostChanged(\n dependencies: ContentDependencies,\n type: PostEventType,\n post: Post,\n): Promise<void> {\n const hook = dependencies.hooks?.onPostChanged\n if (!hook) return\n try {\n await hook({ type, post })\n } catch (error) {\n dependencies.logger?.error('content-module: hook onPostChanged falhou', {\n postId: post.id,\n type,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport {\n POST_STATUS,\n type Pagination,\n type Post,\n type PostStatus,\n type PostSummary,\n type PublicPost,\n type PublicPostSummary,\n} from '@adatechnology/content-contracts'\n\nimport type { PostRow } from '../schema/schema'\n\n/** Agendado cuja hora já passou é publicado: o painel mostra o estado que o leitor vê. */\nexport function effectiveStatus(row: PostRow, now: Date): PostStatus {\n if (row.status === POST_STATUS.SCHEDULED && row.publishedAt && row.publishedAt <= now) return POST_STATUS.PUBLISHED\n return row.status as PostStatus\n}\n\nexport function toPostSummary(row: PostRow, now: Date): PostSummary {\n return {\n id: row.id,\n companyId: row.companyId,\n slug: row.slug,\n title: row.title,\n excerpt: row.excerpt,\n coverImageUrl: row.coverImageUrl,\n coverImageAlt: row.coverImageAlt,\n tags: row.tags,\n status: effectiveStatus(row, now),\n publishedAt: row.publishedAt?.toISOString() ?? null,\n authorName: row.authorName,\n seoTitle: row.seoTitle,\n seoDescription: row.seoDescription,\n canonicalUrl: row.canonicalUrl,\n readingTimeMinutes: row.readingTimeMinutes,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n }\n}\n\nexport function toPost(row: PostRow, now: Date): Post {\n return { ...toPostSummary(row, now), body: row.body }\n}\n\n/** Só chamado sobre linha que passou pela condição pública — `publishedAt` existe. */\nexport function toPublicPostSummary(row: PostRow): PublicPostSummary {\n return {\n id: row.id,\n slug: row.slug,\n title: row.title,\n excerpt: row.excerpt,\n coverImageUrl: row.coverImageUrl,\n coverImageAlt: row.coverImageAlt,\n tags: row.tags,\n publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n authorName: row.authorName,\n seoTitle: row.seoTitle,\n seoDescription: row.seoDescription,\n canonicalUrl: row.canonicalUrl,\n readingTimeMinutes: row.readingTimeMinutes,\n }\n}\n\nexport function toPublicPost(row: PostRow): PublicPost {\n return { ...toPublicPostSummary(row), body: row.body }\n}\n\nexport function toPagination(params: { total: number; page: number; pageSize: number }): Pagination {\n return { ...params, totalPages: Math.max(1, Math.ceil(params.total / params.pageSize)) }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Leitura do site público. Só enxerga post publicado (ou agendado cuja hora chegou) da empresa\n * resolvida pelo host — rascunho, arquivado e agendado futuro respondem 404, igual a inexistente.\n */\n\nimport {\n listPublishedPostsQuerySchema,\n normalizeTag,\n PostNotFoundError,\n type ListPublishedPostsQuery,\n type Paginated,\n type PublicPost,\n type PublicPostSummary,\n type TagCount,\n} from '@adatechnology/content-contracts'\n\nimport { toPagination, toPublicPost, toPublicPostSummary } from '../shared/toContract'\nimport type { ContentDependencies } from './contentModule.types'\n\nexport class GetPublishedPostBySlugUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n async execute(params: { readonly companyId: string; readonly slug: string }): Promise<PublicPost> {\n const slug = params.slug.trim().toLowerCase()\n const row = await this.dependencies.posts.findPublicBySlug({\n companyId: params.companyId,\n slug,\n now: this.dependencies.clock.now(),\n })\n if (!row) throw new PostNotFoundError(slug)\n return toPublicPost(row)\n }\n}\n\nexport class ListPublishedPostsUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n async execute(\n params: { readonly companyId: string } & Partial<ListPublishedPostsQuery>,\n ): Promise<Paginated<PublicPostSummary>> {\n const { companyId, ...rawQuery } = params\n const query = listPublishedPostsQuerySchema.parse(rawQuery)\n const tag = query.tag ? normalizeTag(query.tag) : undefined\n const page = await this.dependencies.posts.listPublic({\n companyId,\n now: this.dependencies.clock.now(),\n page: query.page,\n pageSize: query.pageSize,\n ...(tag ? { tag } : {}),\n })\n return {\n data: page.rows.map(toPublicPostSummary),\n pagination: toPagination({ total: page.total, page: query.page, pageSize: query.pageSize }),\n }\n }\n}\n\nexport const TAG_SCOPE = { PUBLIC: 'public', ADMIN: 'admin' } as const\nexport type TagScope = (typeof TAG_SCOPE)[keyof typeof TAG_SCOPE]\n\nexport class ListTagsUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n /** `public` conta só posts no ar; `admin` conta todos, para o autor reaproveitar a tag. */\n async execute(params: { readonly companyId: string; readonly scope: TagScope }): Promise<readonly TagCount[]> {\n return this.dependencies.posts.listTags({\n companyId: params.companyId,\n ...(params.scope === TAG_SCOPE.PUBLIC ? { publicAt: this.dependencies.clock.now() } : {}),\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Upload da capa. O bucket é do host (`ContentImageStoragePort`); aqui ficam as decisões que não\n * variam por instalação: formatos aceitos, teto de tamanho e forma da chave.\n */\n\nimport { ImageStorageDisabledError, InvalidCoverImageError } from '@adatechnology/content-contracts'\n\nimport { COVER_IMAGE } from '../shared/coverImage.constant'\nimport type { ContentDependencies } from './contentModule.types'\n\nexport type UploadCoverImageParams = {\n readonly companyId: string\n readonly bytes: Uint8Array\n readonly mimeType: string\n}\n\nexport type UploadCoverImageResult = { readonly url: string; readonly key: string }\n\nexport class UploadCoverImageUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n async execute(params: UploadCoverImageParams): Promise<UploadCoverImageResult> {\n const storage = this.dependencies.imageStorage\n if (!storage) throw new ImageStorageDisabledError()\n\n const mimeType = (params.mimeType.split(';')[0] ?? '').trim().toLowerCase()\n // Lista fechada, não \"começa com image/\": SVG é imagem e carrega script.\n const extension = COVER_IMAGE.EXTENSION_BY_MIME[mimeType]\n if (!extension) throw new InvalidCoverImageError('unsupported_type')\n if (params.bytes.byteLength === 0) throw new InvalidCoverImageError('empty')\n if (params.bytes.byteLength > COVER_IMAGE.MAX_BYTES) throw new InvalidCoverImageError('too_large')\n\n // A chave nunca carrega nome de arquivo: é entrada de usuário e vai parar numa URL pública.\n const key = `${COVER_IMAGE.KEY_PREFIX}/${params.companyId}/${crypto.randomUUID()}.${extension}`\n return storage.upload({ buffer: params.bytes, mimeType, key })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * 1 MiB é o teto de corpo do `module-http`: um limite maior aqui seria promessa que a rota não\n * cumpre. O `content-ui` avisa antes de enviar; o servidor recusa de novo porque o cliente não é\n * fonte de verdade.\n */\nexport const COVER_IMAGE = {\n MAX_BYTES: 1024 * 1024,\n KEY_PREFIX: 'content/posts',\n EXTENSION_BY_MIME: {\n 'image/jpeg': 'jpg',\n 'image/png': 'png',\n 'image/webp': 'webp',\n } as Readonly<Record<string, string | undefined>>,\n} as const\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport {\n createPostSchema,\n DEFAULT_ADMIN_SCOPES,\n listPostsQuerySchema,\n publishPostSchema,\n updatePostSchema,\n type CreatePostInput,\n type ListPostsQuery,\n type PublishPostInput,\n type UpdatePostInput,\n} from '@adatechnology/content-contracts'\nimport type { ModuleRoute, RequestContext } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { TAG_SCOPE } from '../use-cases/PublicPost.use-cases'\nimport { requireCompany } from './requireCompany'\n\nfunction reference(context: RequestContext): { companyId: string; id: string } {\n return { companyId: requireCompany(context), id: context.params.id ?? '' }\n}\n\nconst json = (status: number, data: unknown) => ({ kind: 'json' as const, status, body: { data } })\n\nexport function buildAdminRoutes(module: ContentModule): ModuleRoute[] {\n const { useCases } = module\n const requiredScopes = module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES\n const admin = { scope: 'admin' as const, requiredScopes }\n\n const uploadRoutes: ModuleRoute[] = useCases.uploadCoverImage\n ? [\n {\n ...admin,\n method: 'POST',\n path: '/posts/cover-images',\n operationId: 'uploadPostCoverImage',\n summary: 'Envia a imagem de capa (bytes crus, Content-Type jpeg/png/webp) e devolve a URL',\n async handler(context) {\n const upload = useCases.uploadCoverImage\n if (!upload) return { kind: 'empty', status: 404 }\n const result = await upload.execute({\n companyId: requireCompany(context),\n bytes: context.rawBody ?? new Uint8Array(),\n mimeType: context.headers['content-type'] ?? '',\n })\n return json(201, result)\n },\n },\n ]\n : []\n\n return [\n {\n ...admin,\n method: 'GET',\n path: '/posts',\n querySchema: listPostsQuerySchema,\n operationId: 'listPosts',\n summary: 'Lista posts da empresa (todos os status), com filtro por status, tag e busca',\n async handler(context) {\n const result = await useCases.listPosts.execute({\n companyId: requireCompany(context),\n ...(context.query as unknown as ListPostsQuery),\n })\n return { kind: 'json', status: 200, body: result }\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts',\n bodySchema: createPostSchema,\n operationId: 'createPost',\n summary: 'Cria um post como rascunho; sem slug, gera a partir do título',\n async handler(context) {\n const post = await useCases.createPost.execute({\n companyId: requireCompany(context),\n input: context.body as CreatePostInput,\n })\n return json(201, post)\n },\n },\n // Antes de `/posts/:id`: `findRoute` para na primeira rota que casa, e `:id` casaria \"tags\".\n {\n ...admin,\n method: 'GET',\n path: '/posts/tags',\n operationId: 'listPostTags',\n summary: 'Tags usadas em qualquer post da empresa, com contagem',\n async handler(context) {\n return json(\n 200,\n await useCases.listTags.execute({ companyId: requireCompany(context), scope: TAG_SCOPE.ADMIN }),\n )\n },\n },\n ...uploadRoutes,\n {\n ...admin,\n method: 'GET',\n path: '/posts/:id',\n operationId: 'getPost',\n summary: 'Lê um post da empresa (qualquer status)',\n async handler(context) {\n return json(200, await useCases.getPost.execute(reference(context)))\n },\n },\n {\n ...admin,\n method: 'PATCH',\n path: '/posts/:id',\n bodySchema: updatePostSchema,\n operationId: 'updatePost',\n summary: 'Atualiza campos de um post; trocar o título não troca o slug',\n async handler(context) {\n return json(\n 200,\n await useCases.updatePost.execute({ ...reference(context), input: context.body as UpdatePostInput }),\n )\n },\n },\n {\n ...admin,\n method: 'DELETE',\n path: '/posts/:id',\n operationId: 'archivePost',\n summary: 'Arquiva o post: sai do site, conteúdo e slug continuam guardados',\n async handler(context) {\n await useCases.archivePost.execute(reference(context))\n return { kind: 'empty', status: 204 }\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/publish',\n // Opcional: `POST /publish` sem corpo publica agora.\n bodySchema: publishPostSchema.optional(),\n operationId: 'publishPost',\n summary: 'Publica agora, ou agenda quando `publishedAt` é futuro',\n async handler(context) {\n return json(\n 200,\n await useCases.publishPost.execute({\n ...reference(context),\n input: (context.body ?? {}) as PublishPostInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/unpublish',\n operationId: 'unpublishPost',\n summary: 'Tira do ar (ou cancela o agendamento) e volta a rascunho',\n async handler(context) {\n return json(200, await useCases.unpublishPost.execute(reference(context)))\n },\n },\n ]\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { CONTENT_ERROR_CODES, ContentError } from '@adatechnology/content-contracts'\nimport type { RequestContext } from '@adatechnology/module-http'\n\n/** `dispatchRoute` já recusa rota de admin sem identidade; isto só garante o tipo para o handler. */\nexport function requireCompany(context: RequestContext): string {\n if (!context.auth?.companyId) {\n throw new ContentError('Rota exige contexto autenticado.', 401, CONTENT_ERROR_CODES.CONFIG_MISSING)\n }\n return context.auth.companyId\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Rotas do site público. Sem identidade: a empresa vem do `PublicCompanyResolverPort` do host\n * (domínio, cabeçalho, empresa fixa…). Resolver sem resposta = 404, igual a post inexistente.\n */\n\nimport {\n DEFAULT_PUBLIC_CACHE_CONTROL,\n listPublishedPostsQuerySchema,\n PostNotFoundError,\n type ListPublishedPostsQuery,\n} from '@adatechnology/content-contracts'\nimport type { HttpResult, ModuleRoute, RequestContext } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { FEED_FORMAT } from '../use-cases/Feed.use-cases'\nimport { TAG_SCOPE } from '../use-cases/PublicPost.use-cases'\n\nexport interface PublicCompanyResolverPort {\n resolve(params: {\n readonly headers: Readonly<Record<string, string>>\n readonly query: Readonly<Record<string, string>>\n }): Promise<string | undefined>\n}\n\nconst PUBLIC = { scope: 'public' as const }\n\nexport function buildPublicRoutes(params: {\n module: ContentModule\n companyResolver: PublicCompanyResolverPort\n}): ModuleRoute[] {\n const { useCases } = params.module\n const cacheControl = params.module.config.publicCacheControl ?? DEFAULT_PUBLIC_CACHE_CONTROL\n const cached = (data: unknown): HttpResult => ({\n kind: 'json',\n status: 200,\n body: data,\n headers: { 'Cache-Control': cacheControl },\n })\n\n async function resolveCompany(context: RequestContext): Promise<string> {\n const companyId = await params.companyResolver.resolve({ headers: context.headers, query: context.query })\n if (!companyId) throw new PostNotFoundError('company')\n return companyId\n }\n\n const routes: ModuleRoute[] = [\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/posts',\n querySchema: listPublishedPostsQuerySchema,\n operationId: 'listPublishedPosts',\n summary: 'Posts publicados, mais recentes primeiro, com filtro por tag',\n async handler(context) {\n const result = await useCases.listPublishedPosts.execute({\n companyId: await resolveCompany(context),\n ...(context.query as unknown as ListPublishedPostsQuery),\n })\n return cached(result)\n },\n },\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/posts/:slug',\n operationId: 'getPublishedPost',\n summary: 'Post publicado pelo slug; rascunho, agendado futuro e arquivado respondem 404',\n async handler(context) {\n const post = await useCases.getPublishedPostBySlug.execute({\n companyId: await resolveCompany(context),\n slug: context.params.slug ?? '',\n })\n return cached({ data: post })\n },\n },\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/tags',\n operationId: 'listPublishedTags',\n summary: 'Tags dos posts publicados, com contagem',\n async handler(context) {\n const tags = await useCases.listTags.execute({\n companyId: await resolveCompany(context),\n scope: TAG_SCOPE.PUBLIC,\n })\n return cached({ data: tags })\n },\n },\n ]\n\n const { buildFeed, listSitemapEntries } = useCases\n if (!buildFeed || !listSitemapEntries) return routes\n\n const feedRoute = (path: string, format: 'rss' | 'atom', contentType: string, operationId: string): ModuleRoute => ({\n ...PUBLIC,\n method: 'GET',\n path,\n operationId,\n summary: `Feed ${format.toUpperCase()} dos posts publicados`,\n async handler(context) {\n const body = await buildFeed.execute({ companyId: await resolveCompany(context), format })\n return {\n kind: 'text',\n status: 200,\n body,\n headers: { 'Content-Type': contentType, 'Cache-Control': cacheControl },\n }\n },\n })\n\n return [\n ...routes,\n feedRoute('/public/feed.xml', FEED_FORMAT.RSS, 'application/rss+xml; charset=utf-8', 'getRssFeed'),\n feedRoute('/public/atom.xml', FEED_FORMAT.ATOM, 'application/atom+xml; charset=utf-8', 'getAtomFeed'),\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/sitemap-entries',\n operationId: 'listSitemapEntries',\n summary: 'Entradas de sitemap (loc, lastmod) dos posts publicados, para o host juntar ao sitemap dele',\n async handler(context) {\n return cached({ data: await listSitemapEntries.execute({ companyId: await resolveCompany(context) }) })\n },\n },\n ]\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { ModuleRouteTable } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { buildAdminRoutes } from './adminRoutes'\nimport { buildPublicRoutes, type PublicCompanyResolverPort } from './publicRoutes'\n\nexport type CreateContentRoutesParams = {\n readonly module: ContentModule\n /**\n * Como o site público diz de qual empresa é o blog (domínio, cabeçalho, valor fixo…). Ausente,\n * as rotas `/public/*` não sobem: o host que só tem painel não expõe leitura anônima.\n */\n readonly publicCompanyResolver?: PublicCompanyResolverPort\n}\n\nexport function createContentRoutes(params: CreateContentRoutesParams): ModuleRouteTable {\n const admin = buildAdminRoutes(params.module)\n if (!params.publicCompanyResolver) return admin\n return [...admin, ...buildPublicRoutes({ module: params.module, companyResolver: params.publicCompanyResolver })]\n}\n\nexport type { PublicCompanyResolverPort }\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { join } from 'node:path'\n\nimport type { ContentDatabase, DrizzleMigrateFunction } from './database.types'\n\n// Journal próprio, fora do pgSchema `content`: a primeira migration é quem cria esse schema\n// (mesmo raciocínio de `catalog-module/runMigrations.ts`).\nexport const CONTENT_MIGRATIONS_TABLE = 'content_migrations'\n\n/** Pasta no formato clássico (`meta/_journal.json`), lida pelos migrators do drizzle 0.x e 1.x. */\nexport function contentMigrationsFolder(): string {\n return join(__dirname, 'migrations')\n}\n\nexport type RunContentMigrationsParams = {\n readonly db: ContentDatabase\n /** O `migrate` do driver do host (`drizzle-orm/node-postgres/migrator`, `.../bun-sql/migrator`…). */\n readonly migrate: DrizzleMigrateFunction\n}\n\nexport async function runContentMigrations(params: RunContentMigrationsParams): Promise<void> {\n await params.migrate(params.db as never, {\n migrationsFolder: contentMigrationsFolder(),\n migrationsTable: CONTENT_MIGRATIONS_TABLE,\n })\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Dublê em memória do `PostStorePort`, para a suíte de comportamento do módulo e para o teste do\n * host. O isolamento real (cláusula SQL) é provado em `repositories/isolation.test.ts`; aqui as\n * mesmas regras são reproduzidas em JavaScript, inclusive a violação de índice único do slug.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { POST_STATUS, type TagCount } from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../schema/schema'\nimport { effectiveStatus } from '../shared/toContract'\nimport type { PostAdminListQuery, PostPage, PostPublicListQuery, PostStorePort } from '../use-cases/contentModule.types'\n\nfunction isPublic(row: PostRow, now: Date): boolean {\n const live = row.status === POST_STATUS.PUBLISHED || row.status === POST_STATUS.SCHEDULED\n return live && row.publishedAt !== null && row.publishedAt <= now\n}\n\nfunction paginate(rows: PostRow[], page: number, pageSize: number): PostPage {\n return { rows: rows.slice((page - 1) * pageSize, page * pageSize).map((row) => ({ ...row })), total: rows.length }\n}\n\nclass UniqueViolation extends Error {\n readonly code = '23505'\n}\n\nexport function createInMemoryPostStore(seed: PostRow[] = []): PostStorePort & { readonly rows: PostRow[] } {\n const rows: PostRow[] = [...seed]\n\n const assertUniqueSlug = (companyId: string, slug: string, ownId?: string): void => {\n if (rows.some((row) => row.companyId === companyId && row.slug === slug && row.id !== ownId)) {\n throw new UniqueViolation('duplicate key value violates unique constraint \"idx_posts_company_slug\"')\n }\n }\n\n return {\n rows,\n\n async create(values: NewPostRow): Promise<PostRow> {\n assertUniqueSlug(values.companyId, values.slug)\n const now = new Date()\n const row: PostRow = {\n id: randomUUID(),\n excerpt: null,\n body: '',\n coverImageUrl: null,\n coverImageAlt: null,\n tags: [],\n status: POST_STATUS.DRAFT,\n publishedAt: null,\n authorName: null,\n seoTitle: null,\n seoDescription: null,\n canonicalUrl: null,\n readingTimeMinutes: 1,\n createdAt: now,\n updatedAt: now,\n ...values,\n } as PostRow\n rows.push(row)\n return { ...row }\n },\n\n async findById({ companyId, id }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id)\n return row ? { ...row } : undefined\n },\n\n async findBySlug({ companyId, slug }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.slug === slug)\n return row ? { ...row } : undefined\n },\n\n async findPublicBySlug({ companyId, slug, now }) {\n const row = rows.find(\n (candidate) => candidate.companyId === companyId && candidate.slug === slug && isPublic(candidate, now),\n )\n return row ? { ...row } : undefined\n },\n\n async update({ companyId, id, values }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id)\n if (!row) return undefined\n if (values.slug !== undefined) assertUniqueSlug(companyId, values.slug, id)\n Object.assign(row, values, { updatedAt: new Date(Math.max(Date.now(), row.updatedAt.getTime() + 1)) })\n return { ...row }\n },\n\n async listForAdmin(query: PostAdminListQuery) {\n const search = query.search?.toLowerCase()\n const matched = rows\n .filter((row) => row.companyId === query.companyId)\n .filter((row) => !query.status || effectiveStatus(row, query.now) === query.status)\n .filter((row) => !query.tag || row.tags.includes(query.tag))\n .filter((row) => !search || row.title.toLowerCase().includes(search) || row.slug.includes(search))\n .sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime())\n return paginate(matched, query.page, query.pageSize)\n },\n\n async listPublic(query: PostPublicListQuery) {\n const matched = rows\n .filter((row) => row.companyId === query.companyId && isPublic(row, query.now))\n .filter((row) => !query.tag || row.tags.includes(query.tag))\n .sort((left, right) => (right.publishedAt?.getTime() ?? 0) - (left.publishedAt?.getTime() ?? 0))\n return paginate(matched, query.page, query.pageSize)\n },\n\n async listTags({ companyId, publicAt }): Promise<readonly TagCount[]> {\n const counts = new Map<string, number>()\n for (const row of rows) {\n if (row.companyId !== companyId || (publicAt && !isPublic(row, publicAt))) continue\n for (const tag of row.tags) counts.set(tag, (counts.get(tag) ?? 0) + 1)\n }\n return [...counts.entries()]\n .map(([tag, count]) => ({ tag, count }))\n .sort((left, right) => right.count - left.count || left.tag.localeCompare(right.tag))\n },\n }\n}\n"],"mappings":";;;;AACA,OAAOA,UAAU;AACjB,SAASC,qBAAqB;AAE9B,IAAMC,cAAc,6BAAMC,cAAc,YAAYC,GAAG,GAAnC;AACpB,IAAMC,aAAa,6BAAMC,KAAKC,QAAQL,YAAAA,CAAAA,GAAnB;AAEZ,IAAMM,YAA4BH,2BAAAA;;;ACAzC,SAASI,0BAA0B;;;ACHnC,SAASC,KAAKC,MAAMC,OAAAA,YAAW;;;ACA/B,SAASC,OAAOC,SAASC,UAAUC,MAAMC,WAAWC,aAAaC,MAAMC,eAAe;AAG/E,IAAMC,gBAA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IS,OAAOI,QAAO;QACtBhE,IAAI,CAAC,CAACmD,KAAKc,KAAAA,OAAY;QAAEd;QAAKc;MAAM,EAAA,EACpCX,KAAK,CAACC,MAAMC,UAAUA,MAAMS,QAAQV,KAAKU,SAASV,KAAKJ,IAAIe,cAAcV,MAAML,GAAG,CAAA;IACvF;EACF;AACF;AA5FgB7C;","names":["path","fileURLToPath","getFilename","fileURLToPath","url","getDirname","path","dirname","__dirname","ConfigMissingError","asc","desc","sql","index","integer","pgSchema","text","timestamp","uniqueIndex","uuid","varchar","contentSchema","posts","table","id","primaryKey","defaultRandom","companyId","notNull","slug","length","title","excerpt","body","default","coverImageUrl","coverImageAlt","tags","array","status","publishedAt","withTimezone","authorName","seoTitle","seoDescription","canonicalUrl","readingTimeMinutes","createdAt","defaultNow","updatedAt","on","using","and","arrayContains","eq","gt","inArray","lte","or","sql","POST_STATUS","postOwnedByCondition","params","and","eq","posts","companyId","id","postSlugCondition","slug","postAdminListCondition","conditions","status","push","statusCondition","now","tag","arrayContains","tags","search","pattern","replace","character","sql","title","POST_STATUS","PUBLISHED","or","SCHEDULED","lte","publishedAt","gt","postPublicCondition","inArray","postPublicSlugCondition","TAG_LIST_LIMIT","PostRepository","db","create","values","row","insert","posts","returning","Error","findById","params","select","from","where","postOwnedByCondition","limit","findBySlug","postSlugCondition","findPublicBySlug","postPublicSlugCondition","update","set","updatedAt","Date","listForAdmin","query","postAdminListCondition","rows","counted","Promise","all","orderBy","desc","asc","id","pageSize","offset","page","value","sql","total","listPublic","postPublicCondition","publishedAt","listTags","publicAt","companyId","now","postTags","tag","tags","as","count","groupBy","buildAtomFeed","buildExcerpt","buildPostUrl","buildRssFeed","renderMarkdownToHtml","DEFAULT_ITEM_LIMIT","SITEMAP_LIMIT","FEED_FORMAT","RSS","ATOM","BuildFeedUseCase","dependencies","feed","execute","params","now","clock","page","posts","listPublic","companyId","pageSize","itemLimit","channel","siteUrl","title","description","language","feedUrl","items","rows","map","row","toItem","format","buildAtomFeed","buildRssFeed","url","buildPostUrl","slug","postPathTemplate","publishedAt","createdAt","toISOString","updatedAt","summary","excerpt","buildExcerpt","body","includeContent","contentHtml","renderMarkdownToHtml","headingIds","authorName","categories","tags","coverImageUrl","imageUrl","ListSitemapEntriesUseCase","loc","lastmod","createPostSchema","DuplicateSlugError","estimateReadingTimeMinutes","listPostsQuerySchema","normalizeTags","POST_EVENT","POST_STATUS","PostNotFoundError","publishPostSchema","slugify","updatePostSchema","withSlugSuffix","UNIQUE_VIOLATION","isUniqueViolation","error","current","depth","code","cause","notifyPostChanged","dependencies","type","post","hook","hooks","onPostChanged","error","logger","postId","id","Error","message","String","POST_STATUS","effectiveStatus","row","now","status","POST_STATUS","SCHEDULED","publishedAt","PUBLISHED","toPostSummary","id","companyId","slug","title","excerpt","coverImageUrl","coverImageAlt","tags","toISOString","authorName","seoTitle","seoDescription","canonicalUrl","readingTimeMinutes","createdAt","updatedAt","toPost","body","toPublicPostSummary","toPublicPost","toPagination","params","totalPages","Math","max","ceil","total","pageSize","MAX_SLUG_ATTEMPTS","FALLBACK_SLUG","PostUseCaseBase","dependencies","now","clock","findOrFail","reference","row","posts","findById","PostNotFoundError","id","save","values","event","update","catch","error","isUniqueViolation","slug","DuplicateSlugError","post","toPost","notifyPostChanged","readingTime","body","estimateReadingTimeMinutes","config","wordsPerMinute","assertSlugAvailable","companyId","ownId","existing","findBySlug","generateSlug","title","base","slugify","attempt","candidate","withSlugSuffix","Date","optionalFields","input","excerpt","undefined","coverImageUrl","coverImageAlt","authorName","seoTitle","seoDescription","canonicalUrl","CreatePostUseCase","execute","params","createPostSchema","parse","create","tags","normalizeTags","status","POST_STATUS","DRAFT","readingTimeMinutes","POST_EVENT","CREATED","UpdatePostUseCase","updatePostSchema","UPDATED","PublishPostUseCase","publishPostSchema","publishedAt","SCHEDULED","PUBLISHED","UnpublishPostUseCase","UNPUBLISHED","ArchivePostUseCase","ARCHIVED","GetPostUseCase","ListPostsUseCase","rawQuery","query","listPostsQuerySchema","tag","page","listForAdmin","data","rows","map","toPostSummary","pagination","toPagination","total","pageSize","listPublishedPostsQuerySchema","normalizeTag","PostNotFoundError","GetPublishedPostBySlugUseCase","dependencies","execute","params","slug","trim","toLowerCase","row","posts","findPublicBySlug","companyId","now","clock","PostNotFoundError","toPublicPost","ListPublishedPostsUseCase","rawQuery","query","listPublishedPostsQuerySchema","parse","tag","normalizeTag","undefined","page","listPublic","pageSize","data","rows","map","toPublicPostSummary","pagination","toPagination","total","TAG_SCOPE","PUBLIC","ADMIN","ListTagsUseCase","listTags","scope","publicAt","ImageStorageDisabledError","InvalidCoverImageError","COVER_IMAGE","MAX_BYTES","KEY_PREFIX","EXTENSION_BY_MIME","UploadCoverImageUseCase","dependencies","execute","params","storage","imageStorage","ImageStorageDisabledError","mimeType","split","trim","toLowerCase","extension","COVER_IMAGE","EXTENSION_BY_MIME","InvalidCoverImageError","bytes","byteLength","MAX_BYTES","key","KEY_PREFIX","companyId","crypto","randomUUID","upload","buffer","SYSTEM_CLOCK","now","Date","assertValidConfig","config","feed","test","siteUrl","ConfigMissingError","title","trim","postPathTemplate","includes","wordsPerMinute","undefined","createContentModule","params","posts","providers","postStore","db","PostRepository","dependencies","clock","hooks","imageStorage","logger","useCases","createPost","CreatePostUseCase","updatePost","UpdatePostUseCase","archivePost","ArchivePostUseCase","publishPost","PublishPostUseCase","unpublishPost","UnpublishPostUseCase","getPost","GetPostUseCase","listPosts","ListPostsUseCase","getPublishedPostBySlug","GetPublishedPostBySlugUseCase","listPublishedPosts","ListPublishedPostsUseCase","listTags","ListTagsUseCase","uploadCoverImage","UploadCoverImageUseCase","buildFeed","BuildFeedUseCase","listSitemapEntries","ListSitemapEntriesUseCase","createPostSchema","DEFAULT_ADMIN_SCOPES","listPostsQuerySchema","publishPostSchema","updatePostSchema","CONTENT_ERROR_CODES","ContentError","requireCompany","context","auth","companyId","ContentError","CONTENT_ERROR_CODES","CONFIG_MISSING","reference","context","companyId","requireCompany","id","params","json","status","data","kind","body","buildAdminRoutes","module","useCases","requiredScopes","config","adminScopes","DEFAULT_ADMIN_SCOPES","admin","scope","uploadRoutes","uploadCoverImage","method","path","operationId","summary","handler","upload","result","execute","bytes","rawBody","Uint8Array","mimeType","headers","querySchema","listPostsQuerySchema","listPosts","query","bodySchema","createPostSchema","post","createPost","input","listTags","TAG_SCOPE","ADMIN","getPost","updatePostSchema","updatePost","archivePost","publishPostSchema","optional","publishPost","unpublishPost","DEFAULT_PUBLIC_CACHE_CONTROL","listPublishedPostsQuerySchema","PostNotFoundError","PUBLIC","scope","buildPublicRoutes","params","useCases","module","cacheControl","config","publicCacheControl","DEFAULT_PUBLIC_CACHE_CONTROL","cached","data","kind","status","body","headers","resolveCompany","context","companyId","companyResolver","resolve","query","PostNotFoundError","routes","method","path","querySchema","listPublishedPostsQuerySchema","operationId","summary","handler","result","listPublishedPosts","execute","post","getPublishedPostBySlug","slug","tags","listTags","TAG_SCOPE","buildFeed","listSitemapEntries","feedRoute","format","contentType","toUpperCase","FEED_FORMAT","RSS","ATOM","createContentRoutes","params","admin","buildAdminRoutes","module","publicCompanyResolver","buildPublicRoutes","companyResolver","join","CONTENT_MIGRATIONS_TABLE","contentMigrationsFolder","join","__dirname","runContentMigrations","params","migrate","db","migrationsFolder","migrationsTable","randomUUID","POST_STATUS","isPublic","row","now","live","status","POST_STATUS","PUBLISHED","SCHEDULED","publishedAt","paginate","rows","page","pageSize","slice","map","total","length","UniqueViolation","Error","code","createInMemoryPostStore","seed","assertUniqueSlug","companyId","slug","ownId","some","id","create","values","Date","randomUUID","excerpt","body","coverImageUrl","coverImageAlt","tags","DRAFT","authorName","seoTitle","seoDescription","canonicalUrl","readingTimeMinutes","createdAt","updatedAt","push","findById","find","candidate","undefined","findBySlug","findPublicBySlug","update","Object","assign","Math","max","getTime","listForAdmin","query","search","toLowerCase","matched","filter","effectiveStatus","tag","includes","title","sort","left","right","listPublic","listTags","publicAt","counts","Map","set","get","entries","count","localeCompare"]}
|
|
1
|
+
{"version":3,"sources":["../../../../node_modules/.pnpm/tsup@8.5.1_@swc+core@1.16.2_@swc+helpers@0.5.23__jiti@2.7.0_postcss@8.5.28_tsx@4.23.13_typescript@5.9.3_yaml@2.9.1/node_modules/tsup/assets/esm_shims.js","../src/ContentModule.ts","../src/repositories/PostRepository.ts","../src/schema/schema.ts","../src/repositories/conditions.ts","../src/repositories/RecurrenceRepository.ts","../src/use-cases/Feed.use-cases.ts","../src/use-cases/Post.use-cases.ts","../src/shared/shortId.ts","../src/shared/isUniqueViolation.ts","../src/shared/notifyPostChanged.ts","../src/shared/toContract.ts","../src/use-cases/PublicPost.use-cases.ts","../src/use-cases/Recurrence.use-cases.ts","../src/use-cases/Scheduling.use-cases.ts","../src/shared/recurrence.ts","../src/use-cases/Template.use-cases.ts","../src/use-cases/UploadCoverImage.use-case.ts","../src/shared/coverImage.constant.ts","../src/http/adminRoutes.ts","../src/http/requireCompany.ts","../src/http/publicRoutes.ts","../src/http/routes.ts","../src/runMigrations.ts","../src/testing/inMemoryPostStore.ts","../src/scheduler.ts","../src/testing/inMemoryRecurrenceStore.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Composição raiz do módulo de conteúdo (blog, novidades, notícias). Recebe a conexão Drizzle do\n * host e devolve os use-cases; as rotas saem de `createContentRoutes` sobre este objeto.\n */\n\nimport { ConfigMissingError } from '@adatechnology/content-contracts'\nimport type {\n ClockPort,\n ContentHooks,\n ContentImageStoragePort,\n ContentModuleConfig,\n LoggerPort,\n} from '@adatechnology/content-contracts'\n\nimport type { ContentDatabase } from './database.types'\nimport { PostRepository } from './repositories/PostRepository'\nimport { RecurrenceRepository } from './repositories/RecurrenceRepository'\nimport type { ContentDependencies, PostStorePort, RecurrenceStorePort } from './use-cases/contentModule.types'\nimport { BuildFeedUseCase, ListSitemapEntriesUseCase } from './use-cases/Feed.use-cases'\nimport {\n ArchivePostUseCase,\n CreatePostUseCase,\n GetPostUseCase,\n ListPostsUseCase,\n PublishPostUseCase,\n UnpublishPostUseCase,\n UpdatePostUseCase,\n} from './use-cases/Post.use-cases'\nimport {\n GetPublishedPostBySlugUseCase,\n ListPublishedPostsUseCase,\n ListTagsUseCase,\n} from './use-cases/PublicPost.use-cases'\nimport {\n CreateRecurrenceUseCase,\n ListRecurrencesUseCase,\n RemoveRecurrenceUseCase,\n UpdateRecurrenceUseCase,\n} from './use-cases/Recurrence.use-cases'\nimport { PublishDueUseCase, RepublishPostUseCase } from './use-cases/Scheduling.use-cases'\nimport { CountPostsUseCase, CreateFromTemplateUseCase, SaveAsTemplateUseCase } from './use-cases/Template.use-cases'\nimport { UploadCoverImageUseCase } from './use-cases/UploadCoverImage.use-case'\n\nexport type ContentModuleProviders = {\n /** Sem storage, a capa é só por URL e a rota de upload não sobe. */\n readonly imageStorage?: ContentImageStoragePort\n /** Padrão: relógio do sistema. Os testes injetam um fixo para provar o agendamento. */\n readonly clock?: ClockPort\n readonly logger?: LoggerPort\n /** Troca a persistência (ex.: dublê em memória num teste do host). Padrão: Drizzle sobre `db`. */\n readonly postStore?: PostStorePort\n readonly recurrenceStore?: RecurrenceStorePort\n}\n\nexport type CreateContentModuleParams = {\n readonly db?: ContentDatabase\n readonly config?: ContentModuleConfig\n readonly providers?: ContentModuleProviders\n readonly hooks?: ContentHooks\n}\n\nexport type ContentModule = {\n readonly useCases: {\n readonly createPost: CreatePostUseCase\n readonly updatePost: UpdatePostUseCase\n readonly archivePost: ArchivePostUseCase\n readonly publishPost: PublishPostUseCase\n readonly unpublishPost: UnpublishPostUseCase\n readonly getPost: GetPostUseCase\n readonly listPosts: ListPostsUseCase\n readonly getPublishedPostBySlug: GetPublishedPostBySlugUseCase\n readonly listPublishedPosts: ListPublishedPostsUseCase\n readonly listTags: ListTagsUseCase\n readonly countPosts: CountPostsUseCase\n readonly saveAsTemplate: SaveAsTemplateUseCase\n readonly createFromTemplate: CreateFromTemplateUseCase\n readonly republishPost: RepublishPostUseCase\n readonly createRecurrence: CreateRecurrenceUseCase\n readonly listRecurrences: ListRecurrencesUseCase\n readonly updateRecurrence: UpdateRecurrenceUseCase\n readonly removeRecurrence: RemoveRecurrenceUseCase\n /** O host chama num intervalo (ver `startContentScheduler`): publica o agendado vencido e as recorrências. */\n readonly publishDue: PublishDueUseCase\n /** Capacidade por ausência: sem `providers.imageStorage`, não existe. */\n readonly uploadCoverImage?: UploadCoverImageUseCase\n /** Sem `config.feed`, feed e sitemap não existem. */\n readonly buildFeed?: BuildFeedUseCase\n readonly listSitemapEntries?: ListSitemapEntriesUseCase\n }\n readonly config: ContentModuleConfig\n}\n\nconst SYSTEM_CLOCK: ClockPort = { now: () => new Date() }\n\nfunction assertValidConfig(config: ContentModuleConfig): void {\n // Feed com endereço relativo geraria links quebrados em todo leitor de RSS — falha no boot.\n if (config.feed && !/^https?:\\/\\/[^/]/i.test(config.feed.siteUrl)) throw new ConfigMissingError('feed.siteUrl')\n if (config.feed && !config.feed.title.trim()) throw new ConfigMissingError('feed.title')\n if (config.feed?.postPathTemplate && !config.feed.postPathTemplate.includes('{slug}')) {\n throw new ConfigMissingError('feed.postPathTemplate')\n }\n if (config.wordsPerMinute !== undefined && !(config.wordsPerMinute > 0))\n throw new ConfigMissingError('wordsPerMinute')\n}\n\nexport function createContentModule(params: CreateContentModuleParams): ContentModule {\n const config = params.config ?? {}\n assertValidConfig(config)\n\n const posts = params.providers?.postStore ?? (params.db ? new PostRepository(params.db) : undefined)\n if (!posts) throw new ConfigMissingError('db')\n const recurrences = params.providers?.recurrenceStore ?? (params.db ? new RecurrenceRepository(params.db) : undefined)\n if (!recurrences) throw new ConfigMissingError('db')\n\n const dependencies: ContentDependencies = {\n posts,\n recurrences,\n config,\n clock: params.providers?.clock ?? SYSTEM_CLOCK,\n ...(params.hooks ? { hooks: params.hooks } : {}),\n ...(params.providers?.imageStorage ? { imageStorage: params.providers.imageStorage } : {}),\n ...(params.providers?.logger ? { logger: params.providers.logger } : {}),\n }\n\n return {\n useCases: {\n createPost: new CreatePostUseCase(dependencies),\n updatePost: new UpdatePostUseCase(dependencies),\n archivePost: new ArchivePostUseCase(dependencies),\n publishPost: new PublishPostUseCase(dependencies),\n unpublishPost: new UnpublishPostUseCase(dependencies),\n getPost: new GetPostUseCase(dependencies),\n listPosts: new ListPostsUseCase(dependencies),\n getPublishedPostBySlug: new GetPublishedPostBySlugUseCase(dependencies),\n listPublishedPosts: new ListPublishedPostsUseCase(dependencies),\n listTags: new ListTagsUseCase(dependencies),\n countPosts: new CountPostsUseCase(dependencies),\n saveAsTemplate: new SaveAsTemplateUseCase(dependencies),\n createFromTemplate: new CreateFromTemplateUseCase(dependencies),\n republishPost: new RepublishPostUseCase(dependencies),\n createRecurrence: new CreateRecurrenceUseCase(dependencies),\n listRecurrences: new ListRecurrencesUseCase(dependencies),\n updateRecurrence: new UpdateRecurrenceUseCase(dependencies),\n removeRecurrence: new RemoveRecurrenceUseCase(dependencies),\n publishDue: new PublishDueUseCase(dependencies),\n ...(dependencies.imageStorage ? { uploadCoverImage: new UploadCoverImageUseCase(dependencies) } : {}),\n ...(config.feed\n ? {\n buildFeed: new BuildFeedUseCase(dependencies, config.feed),\n listSitemapEntries: new ListSitemapEntriesUseCase(dependencies, config.feed),\n }\n : {}),\n },\n config,\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { and, asc, desc, eq, inArray, sql } from 'drizzle-orm'\nimport { POST_STATUS, type PostCounts, type TagCount } from '@adatechnology/content-contracts'\n\nimport type { ContentDatabase } from '../database.types'\nimport { postFormerSlugs, posts, type NewPostRow, type PostRow } from '../schema/schema'\nimport type { PostAdminListQuery, PostPage, PostPublicListQuery, PostStorePort } from '../use-cases/contentModule.types'\nimport {\n postAdminListCondition,\n postDueCondition,\n postOwnedByCondition,\n postPublicCondition,\n postPublicShortIdCondition,\n postShortIdCondition,\n postPublicSlugCondition,\n postSlugCondition,\n} from './conditions'\n\nconst TAG_LIST_LIMIT = 200\n\nconst SORT_COLUMNS = {\n title: posts.title,\n status: posts.status,\n publishedAt: posts.publishedAt,\n updatedAt: posts.updatedAt,\n} as const\n\n// Padrão: a última edição primeiro, que é o que o painel está mexendo agora. `id` desempata para\n// a paginação não repetir nem pular linha. Data ausente (rascunho) vai sempre para o fim.\nfunction adminOrder(query: PostAdminListQuery) {\n const column = SORT_COLUMNS[query.sort ?? 'updatedAt']\n const direction = (query.order ?? 'desc') === 'asc' ? asc : desc\n const primary =\n query.sort === 'publishedAt'\n ? sql`${column} ${sql.raw(query.order === 'asc' ? 'asc' : 'desc')} nulls last`\n : direction(column)\n return [primary, asc(posts.id)]\n}\n\nexport class PostRepository implements PostStorePort {\n constructor(private readonly db: ContentDatabase) {}\n\n async create(values: NewPostRow): Promise<PostRow> {\n const [row] = await this.db.insert(posts).values(values).returning()\n if (!row) throw new Error('content-module: insert em posts não retornou linha')\n return row\n }\n\n async findById(params: { companyId: string; id: string }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postOwnedByCondition(params)).limit(1)\n return row\n }\n\n async findBySlug(params: { companyId: string; slug: string }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postSlugCondition(params)).limit(1)\n return row\n }\n\n async findPublicBySlug(params: { companyId: string; slug: string; now: Date }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postPublicSlugCondition(params)).limit(1)\n return row\n }\n\n async findByShortId(params: { companyId: string; shortId: string }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postShortIdCondition(params)).limit(1)\n return row\n }\n\n async findPublicByShortId(params: { companyId: string; shortId: string; now: Date }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postPublicShortIdCondition(params)).limit(1)\n return row\n }\n\n async findPublicByFormerSlug(params: { companyId: string; slug: string; now: Date }): Promise<PostRow | undefined> {\n const [former] = await this.db\n .select({ postId: postFormerSlugs.postId })\n .from(postFormerSlugs)\n .where(and(eq(postFormerSlugs.companyId, params.companyId), eq(postFormerSlugs.slug, params.slug)))\n .limit(1)\n if (!former) return undefined\n const [row] = await this.db\n .select()\n .from(posts)\n .where(and(postPublicCondition(params), eq(posts.id, former.postId)))\n .limit(1)\n return row\n }\n\n async recordFormerSlug(params: { companyId: string; postId: string; slug: string }): Promise<void> {\n await this.db.insert(postFormerSlugs).values(params).onConflictDoNothing()\n }\n\n async update(params: { companyId: string; id: string; values: Partial<NewPostRow> }): Promise<PostRow | undefined> {\n const [row] = await this.db\n .update(posts)\n .set({ ...params.values, updatedAt: new Date() })\n .where(postOwnedByCondition(params))\n .returning()\n return row\n }\n\n async listForAdmin(query: PostAdminListQuery): Promise<PostPage> {\n const where = postAdminListCondition(query)\n const [rows, [counted]] = await Promise.all([\n this.db\n .select()\n .from(posts)\n .where(where)\n .orderBy(...adminOrder(query))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n this.db\n .select({ value: sql<number>`count(*)::int` })\n .from(posts)\n .where(where),\n ])\n return { rows, total: counted?.value ?? 0 }\n }\n\n async listPublic(query: PostPublicListQuery): Promise<PostPage> {\n const where = postPublicCondition(query)\n const [rows, [counted]] = await Promise.all([\n this.db\n .select()\n .from(posts)\n .where(where)\n .orderBy(desc(posts.publishedAt), asc(posts.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n this.db\n .select({ value: sql<number>`count(*)::int` })\n .from(posts)\n .where(where),\n ])\n return { rows, total: counted?.value ?? 0 }\n }\n\n async countByStatus(params: { companyId: string; now: Date }): Promise<PostCounts> {\n // Instante como texto com cast: o driver não serializa `Date` solto dentro de `sql` cru.\n const now = sql`${params.now.toISOString()}::timestamptz`\n const counted = (condition: ReturnType<typeof sql>) => sql<number>`count(*) filter (where ${condition})::int`\n const livePublished = sql`(${posts.status} = ${POST_STATUS.PUBLISHED} or (${posts.status} = ${POST_STATUS.SCHEDULED} and ${posts.publishedAt} <= ${now}))`\n const [row] = await this.db\n .select({\n published: counted(sql`not ${posts.isTemplate} and ${livePublished}`),\n scheduled: counted(\n sql`not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS.SCHEDULED} and ${posts.publishedAt} > ${now}`,\n ),\n draft: counted(sql`not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS.DRAFT}`),\n archived: counted(sql`not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS.ARCHIVED}`),\n templates: counted(sql`${posts.isTemplate} and ${posts.status} <> ${POST_STATUS.ARCHIVED}`),\n })\n .from(posts)\n .where(eq(posts.companyId, params.companyId))\n return row ?? { published: 0, scheduled: 0, draft: 0, archived: 0, templates: 0 }\n }\n\n async claimDueScheduled(params: { now: Date; limit: number }): Promise<readonly PostRow[]> {\n // Um único UPDATE com a seleção travada por dentro: quem chega depois pula as linhas já travadas\n // e não as enxerga mais como agendadas — nenhum post é marcado nem notificado duas vezes.\n const due = this.db\n .select({ id: posts.id })\n .from(posts)\n .where(postDueCondition({ now: params.now }))\n .orderBy(asc(posts.publishedAt), asc(posts.id))\n .limit(params.limit)\n .for('update', { skipLocked: true })\n return this.db.update(posts).set({ status: POST_STATUS.PUBLISHED }).where(inArray(posts.id, due)).returning()\n }\n\n async listTags(params: { companyId: string; publicAt?: Date }): Promise<readonly TagCount[]> {\n const where = params.publicAt\n ? postPublicCondition({ companyId: params.companyId, now: params.publicAt })\n : postAdminListCondition({ companyId: params.companyId, now: new Date() })\n // Subconsulta em vez de `group by unnest(...)`: o Postgres não aceita função que devolve\n // conjunto no GROUP BY.\n const postTags = this.db\n .select({ tag: sql<string>`unnest(${posts.tags})`.as('tag') })\n .from(posts)\n .where(where)\n .as('post_tags')\n const rows = await this.db\n .select({ tag: postTags.tag, count: sql<number>`count(*)::int` })\n .from(postTags)\n .groupBy(postTags.tag)\n .orderBy(sql`count(*) desc`, asc(postTags.tag))\n .limit(TAG_LIST_LIMIT)\n return rows\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { sql } from 'drizzle-orm'\nimport {\n boolean,\n index,\n integer,\n jsonb,\n primaryKey,\n pgSchema,\n text,\n timestamp,\n uniqueIndex,\n uuid,\n varchar,\n} from 'drizzle-orm/pg-core'\n\n// Schema Postgres dedicado — o módulo nunca escreve no `public` do host.\nexport const contentSchema = pgSchema('content')\n\n// `status` em varchar e não ENUM nativo; os valores espelham `POST_STATUS` do contracts.\nexport const posts = contentSchema.table(\n 'posts',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n slug: varchar('slug', { length: 120 }).notNull(),\n shortId: varchar('short_id', { length: 6 }).notNull(),\n title: varchar('title', { length: 200 }).notNull(),\n excerpt: varchar('excerpt', { length: 500 }),\n body: text('body').notNull().default(''),\n coverImageUrl: varchar('cover_image_url', { length: 2048 }),\n coverImageAlt: varchar('cover_image_alt', { length: 300 }),\n tags: text('tags').array().notNull().default([]),\n tagLabels: jsonb('tag_labels').$type<Record<string, string>>().notNull().default({}),\n status: varchar('status', { length: 12 }).notNull().default('draft'),\n isTemplate: boolean('is_template').notNull().default(false),\n publishedAt: timestamp('published_at', { withTimezone: true }),\n authorName: varchar('author_name', { length: 120 }),\n seoTitle: varchar('seo_title', { length: 200 }),\n seoDescription: varchar('seo_description', { length: 320 }),\n canonicalUrl: varchar('canonical_url', { length: 2048 }),\n readingTimeMinutes: integer('reading_time_minutes').notNull().default(1),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n // Sem `where deleted_at`: excluir é arquivar, e o slug arquivado continua reservado — reusá-lo\n // faria um link antigo (já compartilhado) abrir outro post.\n uniqueIndex('idx_posts_company_slug').on(table.companyId, table.slug),\n uniqueIndex('idx_posts_company_short_id').on(table.companyId, table.shortId),\n // Serve a listagem pública: empresa + status + ordem por data.\n index('idx_posts_company_status_published').on(table.companyId, table.status, table.publishedAt),\n index('idx_posts_tags').using('gin', table.tags),\n // Serve o `publishDue`: só linha agendada entra, então o índice fica minúsculo.\n index('idx_posts_due')\n .on(table.publishedAt)\n .where(sql`\"status\" = 'scheduled'`),\n ],\n)\n\nexport type PostRow = typeof posts.$inferSelect\nexport type NewPostRow = typeof posts.$inferInsert\n\n// `frequency` em varchar (weekly | monthly), sem ENUM nativo. Posts nunca são apagados, então a\n// chave estrangeira para o modelo não precisa de ON DELETE.\nexport const recurrenceRules = contentSchema.table(\n 'recurrence_rules',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n templateId: uuid('template_id')\n .notNull()\n .references(() => posts.id),\n frequency: varchar('frequency', { length: 10 }).notNull(),\n // Dia do mês da primeira execução: mensal em 31 cai no último dia dos meses curtos e volta ao 31.\n anchorDay: integer('anchor_day').notNull(),\n isActive: boolean('is_active').notNull().default(true),\n nextRunAt: timestamp('next_run_at', { withTimezone: true }).notNull(),\n lastRunAt: timestamp('last_run_at', { withTimezone: true }),\n lastPostId: uuid('last_post_id'),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n index('idx_recurrence_company').on(table.companyId),\n index('idx_recurrence_due')\n .on(table.nextRunAt)\n .where(sql`\"is_active\"`),\n ],\n)\n\nexport type RecurrenceRow = typeof recurrenceRules.$inferSelect\nexport type NewRecurrenceRow = typeof recurrenceRules.$inferInsert\n\n// Slugs que o post já teve: o link antigo continua abrindo o post (e o host o redireciona ao canônico).\nexport const postFormerSlugs = contentSchema.table(\n 'post_former_slugs',\n {\n companyId: uuid('company_id').notNull(),\n slug: varchar('slug', { length: 120 }).notNull(),\n postId: uuid('post_id')\n .notNull()\n .references(() => posts.id),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [primaryKey({ columns: [table.companyId, table.slug] })],\n)\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Toda condição alcançável por uma requisição vive aqui como função pura exportada — a mesma que o\n * repositório chama e que `isolation.test.ts` renderiza em SQL. Um refactor que esqueça o filtro\n * de empresa quebra o teste na hora.\n */\n\nimport { and, arrayContains, arrayOverlaps, eq, gt, inArray, lte, ne, or, sql, type SQL } from 'drizzle-orm'\nimport { POST_STATUS, type PostStatus } from '@adatechnology/content-contracts'\n\nimport { posts } from '../schema/schema'\n\nexport function postOwnedByCondition(params: { companyId: string; id: string }): SQL {\n return and(eq(posts.companyId, params.companyId), eq(posts.id, params.id)) as SQL\n}\n\nexport function postSlugCondition(params: { companyId: string; slug: string }): SQL {\n return and(eq(posts.companyId, params.companyId), eq(posts.slug, params.slug)) as SQL\n}\n\nexport function postAdminListCondition(params: {\n companyId: string\n status?: PostStatus\n tags?: readonly string[]\n search?: string\n /** `true`: só modelos (menos os arquivados). Ausente/`false`: só posts — modelo nunca aparece misturado. */\n isTemplate?: boolean\n now: Date\n}): SQL {\n const conditions: SQL[] = [eq(posts.companyId, params.companyId), templateCondition(params.isTemplate)]\n if (params.status) conditions.push(statusCondition(params.status, params.now))\n if (params.tags?.length) conditions.push(arrayOverlaps(posts.tags, [...params.tags]))\n if (params.search) {\n const pattern = `%${params.search.replace(/[\\\\%_]/g, (character) => `\\\\${character}`)}%`\n conditions.push(sql`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`)\n }\n return and(...conditions) as SQL\n}\n\nfunction templateCondition(isTemplate: boolean | undefined): SQL {\n if (isTemplate) return and(eq(posts.isTemplate, true), ne(posts.status, POST_STATUS.ARCHIVED)) as SQL\n return eq(posts.isTemplate, false)\n}\n\n/**\n * Filtra pelo status que o painel MOSTRA: agendado cuja hora passou aparece como publicado, então\n * o filtro \"publicados\" o inclui e o filtro \"agendados\" o exclui.\n */\nfunction statusCondition(status: PostStatus, now: Date): SQL {\n if (status === POST_STATUS.PUBLISHED) {\n return or(\n eq(posts.status, POST_STATUS.PUBLISHED),\n and(eq(posts.status, POST_STATUS.SCHEDULED), lte(posts.publishedAt, now)),\n ) as SQL\n }\n if (status === POST_STATUS.SCHEDULED) {\n return and(eq(posts.status, POST_STATUS.SCHEDULED), gt(posts.publishedAt, now)) as SQL\n }\n return eq(posts.status, status)\n}\n\n/**\n * Público = publicado ou agendado cuja hora chegou. `scheduled` entra na condição justamente para\n * que o agendamento valha sem cron: no instante de `published_at` o post passa a casar aqui.\n */\nexport function postPublicCondition(params: { companyId: string; now: Date; tag?: string }): SQL {\n const conditions: SQL[] = [\n eq(posts.companyId, params.companyId),\n inArray(posts.status, [POST_STATUS.PUBLISHED, POST_STATUS.SCHEDULED]),\n lte(posts.publishedAt, params.now),\n ]\n if (params.tag) conditions.push(arrayContains(posts.tags, [params.tag]))\n return and(...conditions) as SQL\n}\n\nexport function postPublicSlugCondition(params: { companyId: string; slug: string; now: Date }): SQL {\n return and(postPublicCondition(params), eq(posts.slug, params.slug)) as SQL\n}\n\n/**\n * Agendado cuja hora chegou, de qualquer empresa: é a única condição sem `company_id`, de propósito —\n * o `publishDue` é tarefa do sistema e varre todas as empresas. Modelo nunca entra.\n */\nexport function postDueCondition(params: { now: Date }): SQL {\n return and(\n eq(posts.status, POST_STATUS.SCHEDULED),\n eq(posts.isTemplate, false),\n lte(posts.publishedAt, params.now),\n ) as SQL\n}\n\nexport function postShortIdCondition(params: { companyId: string; shortId: string }): SQL {\n return and(eq(posts.companyId, params.companyId), eq(posts.shortId, params.shortId)) as SQL\n}\n\nexport function postPublicShortIdCondition(params: { companyId: string; shortId: string; now: Date }): SQL {\n return and(postPublicCondition(params), eq(posts.shortId, params.shortId)) as SQL\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { and, asc, eq, lte } from 'drizzle-orm'\n\nimport type { ContentDatabase } from '../database.types'\nimport { recurrenceRules, type NewRecurrenceRow, type RecurrenceRow } from '../schema/schema'\nimport type { RecurrenceStorePort } from '../use-cases/contentModule.types'\n\nexport function recurrenceOwnedByCondition(params: { companyId: string; id: string }) {\n return and(eq(recurrenceRules.companyId, params.companyId), eq(recurrenceRules.id, params.id))\n}\n\nexport class RecurrenceRepository implements RecurrenceStorePort {\n constructor(private readonly db: ContentDatabase) {}\n\n async create(values: NewRecurrenceRow): Promise<RecurrenceRow> {\n const [row] = await this.db.insert(recurrenceRules).values(values).returning()\n if (!row) throw new Error('content-module: insert em recurrence_rules não retornou linha')\n return row\n }\n\n async findById(params: { companyId: string; id: string }): Promise<RecurrenceRow | undefined> {\n const [row] = await this.db.select().from(recurrenceRules).where(recurrenceOwnedByCondition(params)).limit(1)\n return row\n }\n\n async list(params: { companyId: string }): Promise<readonly RecurrenceRow[]> {\n return this.db\n .select()\n .from(recurrenceRules)\n .where(eq(recurrenceRules.companyId, params.companyId))\n .orderBy(asc(recurrenceRules.nextRunAt), asc(recurrenceRules.id))\n }\n\n async update(params: {\n companyId: string\n id: string\n values: Partial<NewRecurrenceRow>\n }): Promise<RecurrenceRow | undefined> {\n const [row] = await this.db\n .update(recurrenceRules)\n .set(params.values)\n .where(recurrenceOwnedByCondition(params))\n .returning()\n return row\n }\n\n async remove(params: { companyId: string; id: string }): Promise<boolean> {\n const removed = await this.db\n .delete(recurrenceRules)\n .where(recurrenceOwnedByCondition(params))\n .returning({ id: recurrenceRules.id })\n return removed.length > 0\n }\n\n async processDue(params: {\n now: Date\n limit: number\n handle: (rule: RecurrenceRow) => Promise<Partial<NewRecurrenceRow>>\n }): Promise<number> {\n return this.db.transaction(async (transaction) => {\n const due = await transaction\n .select()\n .from(recurrenceRules)\n .where(and(eq(recurrenceRules.isActive, true), lte(recurrenceRules.nextRunAt, params.now)))\n .orderBy(asc(recurrenceRules.nextRunAt), asc(recurrenceRules.id))\n .limit(params.limit)\n .for('update', { skipLocked: true })\n let processed = 0\n // Sequencial de propósito: a transação é uma conexão só, e a ordem é a da data de vencimento.\n for (const rule of due) {\n const values = await params.handle(rule)\n await transaction.update(recurrenceRules).set(values).where(eq(recurrenceRules.id, rule.id))\n processed += 1\n }\n return processed\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * RSS, Atom e entradas de sitemap do site público, a partir de `config.feed`. Sem essa config os\n * use-cases nem são construídos e as rotas não sobem.\n */\n\nimport {\n buildAtomFeed,\n buildExcerpt,\n buildPostUrl,\n buildRssFeed,\n renderMarkdownToHtml,\n type ContentFeedConfig,\n type FeedChannel,\n type FeedItem,\n type SitemapEntry,\n} from '@adatechnology/content-contracts'\n\nimport type { PostRow } from '../schema/schema'\nimport type { ContentDependencies } from './contentModule.types'\n\nconst DEFAULT_ITEM_LIMIT = 20\n// O protocolo de sitemap aceita até 50 mil URLs por arquivo; blog real fica muito abaixo disso.\nconst SITEMAP_LIMIT = 50_000\n\nexport const FEED_FORMAT = { RSS: 'rss', ATOM: 'atom' } as const\nexport type FeedFormat = (typeof FEED_FORMAT)[keyof typeof FEED_FORMAT]\n\nexport class BuildFeedUseCase {\n constructor(\n private readonly dependencies: ContentDependencies,\n private readonly feed: ContentFeedConfig,\n ) {}\n\n async execute(params: {\n readonly companyId: string\n readonly format: FeedFormat\n readonly feedUrl?: string\n }): Promise<string> {\n const now = this.dependencies.clock.now()\n const page = await this.dependencies.posts.listPublic({\n companyId: params.companyId,\n now,\n page: 1,\n pageSize: this.feed.itemLimit ?? DEFAULT_ITEM_LIMIT,\n })\n const channel: FeedChannel = {\n siteUrl: this.feed.siteUrl,\n title: this.feed.title,\n ...(this.feed.description ? { description: this.feed.description } : {}),\n ...(this.feed.language ? { language: this.feed.language } : {}),\n ...(params.feedUrl ? { feedUrl: params.feedUrl } : {}),\n }\n const items = page.rows.map((row) => this.toItem(row))\n return params.format === FEED_FORMAT.ATOM\n ? buildAtomFeed({ channel, items, now })\n : buildRssFeed({ channel, items })\n }\n\n private toItem(row: PostRow): FeedItem {\n return {\n title: row.title,\n url: buildPostUrl({\n siteUrl: this.feed.siteUrl,\n slug: row.slug,\n shortId: row.shortId,\n postPathTemplate: this.feed.postPathTemplate,\n }),\n publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n summary: row.excerpt ?? buildExcerpt(row.body),\n ...((this.feed.includeContent ?? true)\n ? { contentHtml: renderMarkdownToHtml(row.body, { headingIds: false }) }\n : {}),\n ...(row.authorName ? { authorName: row.authorName } : {}),\n categories: row.tags,\n ...(row.coverImageUrl ? { imageUrl: row.coverImageUrl } : {}),\n }\n }\n}\n\nexport class ListSitemapEntriesUseCase {\n constructor(\n private readonly dependencies: ContentDependencies,\n private readonly feed: ContentFeedConfig,\n ) {}\n\n /** Entradas para o host juntar ao sitemap dele — o módulo não é dono do sitemap do site. */\n async execute(params: { readonly companyId: string }): Promise<readonly SitemapEntry[]> {\n const page = await this.dependencies.posts.listPublic({\n companyId: params.companyId,\n now: this.dependencies.clock.now(),\n page: 1,\n pageSize: SITEMAP_LIMIT,\n })\n return page.rows.map((row) => ({\n loc: buildPostUrl({\n siteUrl: this.feed.siteUrl,\n slug: row.slug,\n shortId: row.shortId,\n postPathTemplate: this.feed.postPathTemplate,\n }),\n lastmod: row.updatedAt.toISOString(),\n }))\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Casos de uso do painel: criar, editar, arquivar, publicar/agendar, despublicar, ler e listar.\n * Todos validam a entrada com o schema do contracts de novo — o host pode chamar o use-case sem\n * passar pela rota, e a regra não pode depender de quem chamou.\n */\n\nimport {\n buildTagLabels,\n createPostSchema,\n DuplicateSlugError,\n estimateReadingTimeMinutes,\n listPostsQuerySchema,\n normalizeTags,\n POST_EVENT,\n POST_STATUS,\n PostNotFoundError,\n TemplateNotPublishableError,\n publishPostSchema,\n buildShortSlug,\n updatePostSchema,\n withSlugSuffix,\n type CreatePostInput,\n type ListPostsQuery,\n type Paginated,\n type Post,\n type PostEventType,\n type PostSummary,\n type PublishPostInput,\n type UpdatePostInput,\n} from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../schema/schema'\nimport { generateShortId } from '../shared/shortId'\nimport { isUniqueViolation } from '../shared/isUniqueViolation'\nimport { notifyPostChanged } from '../shared/notifyPostChanged'\nimport { toPagination, toPost, toPostSummary } from '../shared/toContract'\nimport type { ContentDependencies } from './contentModule.types'\n\nconst MAX_SLUG_ATTEMPTS = 50\nconst FALLBACK_SLUG = 'post'\n\nexport type PostReference = { readonly companyId: string; readonly id: string }\n\nexport abstract class PostUseCaseBase {\n constructor(protected readonly dependencies: ContentDependencies) {}\n\n protected now(): Date {\n return this.dependencies.clock.now()\n }\n\n protected async findOrFail(reference: PostReference): Promise<PostRow> {\n const row = await this.dependencies.posts.findById(reference)\n if (!row) throw new PostNotFoundError(reference.id)\n return row\n }\n\n protected async save(reference: PostReference, values: Partial<NewPostRow>, event: PostEventType): Promise<Post> {\n const row = await this.dependencies.posts.update({ ...reference, values }).catch((error: unknown) => {\n if (isUniqueViolation(error) && values.slug) throw new DuplicateSlugError(values.slug)\n throw error\n })\n if (!row) throw new PostNotFoundError(reference.id)\n const post = toPost(row, this.now())\n await notifyPostChanged(this.dependencies, event, post)\n return post\n }\n\n /** Id curto livre na empresa; a colisão (~1 em 2 bilhões) só repete o sorteio. */\n protected async generateShortId(companyId: string): Promise<string> {\n for (let attempt = 0; attempt < MAX_SLUG_ATTEMPTS; attempt += 1) {\n const candidate = generateShortId()\n if (!(await this.dependencies.posts.findByShortId({ companyId, shortId: candidate }))) return candidate\n }\n throw new Error('content-module: sem id curto livre')\n }\n\n protected readingTime(body: string): number {\n return estimateReadingTimeMinutes(body, this.dependencies.config.wordsPerMinute)\n }\n\n protected async assertSlugAvailable(companyId: string, slug: string, ownId?: string): Promise<void> {\n const existing = await this.dependencies.posts.findBySlug({ companyId, slug })\n if (existing && existing.id !== ownId) throw new DuplicateSlugError(slug)\n }\n\n /** `titulo`, `titulo-2`, `titulo-3`… Sequencial de propósito: cada tentativa depende da anterior. */\n protected async generateSlug(companyId: string, title: string): Promise<string> {\n return this.uniqueSlug(companyId, buildShortSlug(title, this.dependencies.config.slug) || FALLBACK_SLUG)\n }\n\n protected async uniqueSlug(companyId: string, base: string): Promise<string> {\n for (let attempt = 1; attempt <= MAX_SLUG_ATTEMPTS; attempt += 1) {\n const candidate = withSlugSuffix(base, attempt)\n if (!(await this.dependencies.posts.findBySlug({ companyId, slug: candidate }))) return candidate\n }\n return withSlugSuffix(base, Date.now())\n }\n}\n\nfunction optionalFields(\n input: Omit<UpdatePostInput, 'slug' | 'title' | 'body' | 'tags' | 'tagLabels'>,\n): Partial<NewPostRow> {\n const values: Partial<NewPostRow> = {}\n if (input.excerpt !== undefined) values.excerpt = input.excerpt || null\n if (input.coverImageUrl !== undefined) values.coverImageUrl = input.coverImageUrl || null\n if (input.coverImageAlt !== undefined) values.coverImageAlt = input.coverImageAlt || null\n if (input.authorName !== undefined) values.authorName = input.authorName || null\n if (input.seoTitle !== undefined) values.seoTitle = input.seoTitle || null\n if (input.seoDescription !== undefined) values.seoDescription = input.seoDescription || null\n if (input.canonicalUrl !== undefined) values.canonicalUrl = input.canonicalUrl || null\n return values\n}\n\nexport class CreatePostUseCase extends PostUseCaseBase {\n async execute(params: { readonly companyId: string; readonly input: CreatePostInput }): Promise<Post> {\n const input = createPostSchema.parse(params.input)\n const { companyId } = params\n if (input.slug) await this.assertSlugAvailable(companyId, input.slug)\n const slug = input.slug ?? (await this.generateSlug(companyId, input.title))\n\n const row = await this.dependencies.posts\n .create({\n companyId,\n slug,\n shortId: await this.generateShortId(companyId),\n title: input.title,\n body: input.body,\n tags: normalizeTags(input.tags ?? []),\n tagLabels: buildTagLabels({ typed: input.tags ?? [], explicit: input.tagLabels }),\n status: POST_STATUS.DRAFT,\n readingTimeMinutes: this.readingTime(input.body),\n ...optionalFields(input),\n })\n .catch((error: unknown) => {\n if (isUniqueViolation(error)) throw new DuplicateSlugError(slug)\n throw error\n })\n\n const post = toPost(row, this.now())\n await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, post)\n return post\n }\n}\n\nexport class UpdatePostUseCase extends PostUseCaseBase {\n /** Trocar o título não muda o slug: o endereço já pode ter sido compartilhado. */\n async execute(params: PostReference & { readonly input: UpdatePostInput }): Promise<Post> {\n const input = updatePostSchema.parse(params.input)\n const existing = await this.findOrFail(params)\n\n const values: Partial<NewPostRow> = optionalFields(input)\n if (input.title !== undefined) values.title = input.title\n if (input.body !== undefined) {\n values.body = input.body\n values.readingTimeMinutes = this.readingTime(input.body)\n }\n if (input.tags !== undefined || input.tagLabels !== undefined) {\n const tags = normalizeTags(input.tags ?? existing.tags)\n values.tags = tags\n values.tagLabels = buildTagLabels({\n typed: input.tags ?? tags,\n explicit: input.tagLabels,\n previous: existing.tagLabels,\n })\n }\n if (input.slug !== undefined && input.slug !== existing.slug) {\n await this.assertSlugAvailable(params.companyId, input.slug, existing.id)\n values.slug = input.slug\n // O endereço antigo continua abrindo o post: o host o redireciona ao canônico.\n await this.dependencies.posts.recordFormerSlug({\n companyId: params.companyId,\n postId: existing.id,\n slug: existing.slug,\n })\n }\n return this.save(params, values, POST_EVENT.UPDATED)\n }\n}\n\nexport class PublishPostUseCase extends PostUseCaseBase {\n /** Sem data: publica agora. Data futura: agenda. Data passada: publica com a data informada. */\n async execute(params: PostReference & { readonly input?: PublishPostInput }): Promise<Post> {\n const input = publishPostSchema.parse(params.input ?? {})\n const existing = await this.findOrFail(params)\n if (existing.isTemplate) throw new TemplateNotPublishableError(params.id)\n const now = this.now()\n const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now\n const status = publishedAt > now ? POST_STATUS.SCHEDULED : POST_STATUS.PUBLISHED\n return this.save(params, { status, publishedAt }, POST_EVENT.PUBLISHED)\n }\n}\n\nexport class UnpublishPostUseCase extends PostUseCaseBase {\n /** Volta a rascunho e tira do ar na hora, inclusive cancelando um agendamento. */\n async execute(params: PostReference): Promise<Post> {\n await this.findOrFail(params)\n return this.save(params, { status: POST_STATUS.DRAFT, publishedAt: null }, POST_EVENT.UNPUBLISHED)\n }\n}\n\nexport class ArchivePostUseCase extends PostUseCaseBase {\n /** \"Excluir\" no painel é arquivar: some do site, mas o conteúdo e o slug continuam guardados. */\n async execute(params: PostReference): Promise<Post> {\n await this.findOrFail(params)\n return this.save(params, { status: POST_STATUS.ARCHIVED }, POST_EVENT.ARCHIVED)\n }\n}\n\nexport class GetPostUseCase extends PostUseCaseBase {\n async execute(params: PostReference): Promise<Post> {\n return toPost(await this.findOrFail(params), this.now())\n }\n}\n\nexport class ListPostsUseCase extends PostUseCaseBase {\n async execute(params: { readonly companyId: string } & Partial<ListPostsQuery>): Promise<Paginated<PostSummary>> {\n const { companyId, ...rawQuery } = params\n const query = listPostsQuerySchema.parse(rawQuery)\n const { tag: rawTag, ...rest } = query\n const tags = rawTag ? normalizeTags(rawTag.split(',')) : []\n const now = this.now()\n const page = await this.dependencies.posts.listForAdmin({\n companyId,\n ...rest,\n isTemplate: query.isTemplate ?? false,\n now,\n ...(tags.length > 0 ? { tags } : {}),\n })\n return {\n data: page.rows.map((row) => toPostSummary(row, now)),\n pagination: toPagination({ total: page.total, page: query.page, pageSize: query.pageSize }),\n }\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { randomInt } from 'node:crypto'\nimport { SHORT_ID_LENGTH } from '@adatechnology/content-contracts'\n\nconst ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'\n\n/** 6 caracteres base36 (~2 bilhões): a colisão é checada contra a empresa antes de gravar. */\nexport function generateShortId(): string {\n let value = ''\n for (let index = 0; index < SHORT_ID_LENGTH; index += 1) value += ALPHABET[randomInt(ALPHABET.length)]\n return value\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nconst UNIQUE_VIOLATION = '23505'\n\n/**\n * Cada driver embrulha o erro do Postgres de um jeito (`code` direto, ou em `cause`). A checagem\n * prévia de slug não fecha a corrida entre dois saves simultâneos; o índice único fecha, e isto\n * traduz a violação para o 409 do domínio.\n */\nexport function isUniqueViolation(error: unknown): boolean {\n let current: unknown = error\n for (let depth = 0; depth < 3 && typeof current === 'object' && current !== null; depth += 1) {\n if ((current as { code?: unknown }).code === UNIQUE_VIOLATION) return true\n current = (current as { cause?: unknown }).cause\n }\n return false\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { Post, PostEventType } from '@adatechnology/content-contracts'\n\nimport type { ContentDependencies } from '../use-cases/contentModule.types'\n\n/**\n * O gancho do host roda depois da escrita, e falha nele não desfaz o que já foi gravado: o post\n * publicado continua publicado mesmo que a purga de cache do host caia. Por isso o catch local.\n */\nexport async function notifyPostChanged(\n dependencies: ContentDependencies,\n type: PostEventType,\n post: Post,\n): Promise<void> {\n const hook = dependencies.hooks?.onPostChanged\n if (!hook) return\n try {\n await hook({ type, post })\n } catch (error) {\n dependencies.logger?.error('content-module: hook onPostChanged falhou', {\n postId: post.id,\n type,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport {\n POST_STATUS,\n type Pagination,\n type Post,\n type PostStatus,\n type PostSummary,\n type PublicPost,\n type PublicPostSummary,\n} from '@adatechnology/content-contracts'\n\nimport type { PostRow } from '../schema/schema'\n\n/** Agendado cuja hora já passou é publicado: o painel mostra o estado que o leitor vê. */\nexport function effectiveStatus(row: PostRow, now: Date): PostStatus {\n if (row.status === POST_STATUS.SCHEDULED && row.publishedAt && row.publishedAt <= now) return POST_STATUS.PUBLISHED\n return row.status as PostStatus\n}\n\nexport function toPostSummary(row: PostRow, now: Date): PostSummary {\n return {\n id: row.id,\n companyId: row.companyId,\n slug: row.slug,\n shortId: row.shortId,\n title: row.title,\n excerpt: row.excerpt,\n coverImageUrl: row.coverImageUrl,\n coverImageAlt: row.coverImageAlt,\n tags: row.tags,\n tagLabels: row.tagLabels,\n status: effectiveStatus(row, now),\n isTemplate: row.isTemplate,\n publishedAt: row.publishedAt?.toISOString() ?? null,\n authorName: row.authorName,\n seoTitle: row.seoTitle,\n seoDescription: row.seoDescription,\n canonicalUrl: row.canonicalUrl,\n readingTimeMinutes: row.readingTimeMinutes,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n }\n}\n\nexport function toPost(row: PostRow, now: Date): Post {\n return { ...toPostSummary(row, now), body: row.body }\n}\n\n/** Só chamado sobre linha que passou pela condição pública — `publishedAt` existe. */\nexport function toPublicPostSummary(row: PostRow): PublicPostSummary {\n return {\n id: row.id,\n slug: row.slug,\n shortId: row.shortId,\n title: row.title,\n excerpt: row.excerpt,\n coverImageUrl: row.coverImageUrl,\n coverImageAlt: row.coverImageAlt,\n tags: row.tags,\n tagLabels: row.tagLabels,\n publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n authorName: row.authorName,\n seoTitle: row.seoTitle,\n seoDescription: row.seoDescription,\n canonicalUrl: row.canonicalUrl,\n readingTimeMinutes: row.readingTimeMinutes,\n }\n}\n\nexport function toPublicPost(row: PostRow): PublicPost {\n return { ...toPublicPostSummary(row), body: row.body }\n}\n\nexport function toPagination(params: { total: number; page: number; pageSize: number }): Pagination {\n return { ...params, totalPages: Math.max(1, Math.ceil(params.total / params.pageSize)) }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Leitura do site público. Só enxerga post publicado (ou agendado cuja hora chegou) da empresa\n * resolvida pelo host — rascunho, arquivado e agendado futuro respondem 404, igual a inexistente.\n */\n\nimport {\n listPublishedPostsQuerySchema,\n normalizeTag,\n parsePostRef,\n PostNotFoundError,\n type ListPublishedPostsQuery,\n type Paginated,\n type PublicPost,\n type PublicPostSummary,\n type TagCount,\n} from '@adatechnology/content-contracts'\n\nimport { toPagination, toPublicPost, toPublicPostSummary } from '../shared/toContract'\nimport type { ContentDependencies } from './contentModule.types'\n\nexport class GetPublishedPostBySlugUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n /**\n * `slug` aceita o endereço canônico `<shortId>-<slug>`, o slug atual e slug antigo. O id curto\n * manda: título/slug editado depois não quebra link compartilhado. O host compara `buildPostRef`\n * do resultado com o pedido e redireciona (301) quando forem diferentes.\n */\n async execute(params: { readonly companyId: string; readonly slug: string }): Promise<PublicPost> {\n const { posts, clock } = this.dependencies\n const parsed = parsePostRef(params.slug)\n const query = { companyId: params.companyId, now: clock.now() }\n const row =\n (parsed.shortId ? await posts.findPublicByShortId({ ...query, shortId: parsed.shortId }) : undefined) ??\n (await posts.findPublicBySlug({ ...query, slug: parsed.slug })) ??\n (await posts.findPublicByFormerSlug({ ...query, slug: parsed.slug }))\n if (!row) throw new PostNotFoundError(parsed.slug)\n return toPublicPost(row)\n }\n}\n\nexport class ListPublishedPostsUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n async execute(\n params: { readonly companyId: string } & Partial<ListPublishedPostsQuery>,\n ): Promise<Paginated<PublicPostSummary>> {\n const { companyId, ...rawQuery } = params\n const query = listPublishedPostsQuerySchema.parse(rawQuery)\n const tag = query.tag ? normalizeTag(query.tag) : undefined\n const page = await this.dependencies.posts.listPublic({\n companyId,\n now: this.dependencies.clock.now(),\n page: query.page,\n pageSize: query.pageSize,\n ...(tag ? { tag } : {}),\n })\n return {\n data: page.rows.map(toPublicPostSummary),\n pagination: toPagination({ total: page.total, page: query.page, pageSize: query.pageSize }),\n }\n }\n}\n\nexport const TAG_SCOPE = { PUBLIC: 'public', ADMIN: 'admin' } as const\nexport type TagScope = (typeof TAG_SCOPE)[keyof typeof TAG_SCOPE]\n\nexport class ListTagsUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n /** `public` conta só posts no ar; `admin` conta todos, para o autor reaproveitar a tag. */\n async execute(params: { readonly companyId: string; readonly scope: TagScope }): Promise<readonly TagCount[]> {\n return this.dependencies.posts.listTags({\n companyId: params.companyId,\n ...(params.scope === TAG_SCOPE.PUBLIC ? { publicAt: this.dependencies.clock.now() } : {}),\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Regras de recorrência do painel: cada regra publica, na frequência escolhida, um post novo copiado\n * de um modelo. Quem executa é o `publishDue`.\n */\n\nimport {\n createRecurrenceSchema,\n NotATemplateError,\n PostNotFoundError,\n RecurrenceNotFoundError,\n updateRecurrenceSchema,\n type CreateRecurrenceInput,\n type RecurrenceFrequency,\n type RecurrenceRule,\n type UpdateRecurrenceInput,\n} from '@adatechnology/content-contracts'\n\nimport type { NewRecurrenceRow, RecurrenceRow } from '../schema/schema'\nimport type { ContentDependencies } from './contentModule.types'\n\nabstract class RecurrenceUseCaseBase {\n constructor(protected readonly dependencies: ContentDependencies) {}\n\n protected async toRule(row: RecurrenceRow): Promise<RecurrenceRule> {\n const template = await this.dependencies.posts.findById({ companyId: row.companyId, id: row.templateId })\n return {\n id: row.id,\n companyId: row.companyId,\n templateId: row.templateId,\n templateTitle: template?.title ?? '',\n frequency: row.frequency as RecurrenceFrequency,\n isActive: row.isActive,\n nextRunAt: row.nextRunAt.toISOString(),\n lastRunAt: row.lastRunAt?.toISOString() ?? null,\n lastPostId: row.lastPostId,\n createdAt: row.createdAt.toISOString(),\n }\n }\n\n protected async findOrFail(params: { companyId: string; id: string }): Promise<RecurrenceRow> {\n const row = await this.dependencies.recurrences.findById(params)\n if (!row) throw new RecurrenceNotFoundError(params.id)\n return row\n }\n}\n\nexport class CreateRecurrenceUseCase extends RecurrenceUseCaseBase {\n async execute(params: {\n readonly companyId: string\n readonly input: CreateRecurrenceInput\n }): Promise<RecurrenceRule> {\n const input = createRecurrenceSchema.parse(params.input)\n const template = await this.dependencies.posts.findById({ companyId: params.companyId, id: input.templateId })\n if (!template) throw new PostNotFoundError(input.templateId)\n if (!template.isTemplate) throw new NotATemplateError(input.templateId)\n const startsAt = new Date(input.startsAt)\n const values: NewRecurrenceRow = {\n companyId: params.companyId,\n templateId: input.templateId,\n frequency: input.frequency,\n anchorDay: startsAt.getUTCDate(),\n nextRunAt: startsAt,\n }\n return this.toRule(await this.dependencies.recurrences.create(values))\n }\n}\n\nexport class ListRecurrencesUseCase extends RecurrenceUseCaseBase {\n async execute(params: { readonly companyId: string }): Promise<readonly RecurrenceRule[]> {\n const rows = await this.dependencies.recurrences.list(params)\n return Promise.all(rows.map((row) => this.toRule(row)))\n }\n}\n\nexport class UpdateRecurrenceUseCase extends RecurrenceUseCaseBase {\n /** Pausar/retomar e remarcar a próxima execução. */\n async execute(params: {\n readonly companyId: string\n readonly id: string\n readonly input: UpdateRecurrenceInput\n }): Promise<RecurrenceRule> {\n const input = updateRecurrenceSchema.parse(params.input)\n await this.findOrFail(params)\n const values: Partial<NewRecurrenceRow> = {}\n if (input.isActive !== undefined) values.isActive = input.isActive\n if (input.nextRunAt !== undefined) {\n values.nextRunAt = new Date(input.nextRunAt)\n values.anchorDay = values.nextRunAt.getUTCDate()\n }\n const row = await this.dependencies.recurrences.update({ companyId: params.companyId, id: params.id, values })\n if (!row) throw new RecurrenceNotFoundError(params.id)\n return this.toRule(row)\n }\n}\n\nexport class RemoveRecurrenceUseCase extends RecurrenceUseCaseBase {\n /** Apaga só a regra: os posts que ela já publicou continuam no ar. */\n async execute(params: { readonly companyId: string; readonly id: string }): Promise<void> {\n if (!(await this.dependencies.recurrences.remove(params))) throw new RecurrenceNotFoundError(params.id)\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Republicar e publicar no horário. `publishDue` é o que o host chama num intervalo: marca como\n * publicado o que estava agendado e já venceu, e materializa as recorrências vencidas.\n */\n\nimport {\n POST_EVENT,\n POST_STATUS,\n PostNotPublishedError,\n republishPostSchema,\n RepublishDateInFutureError,\n SLUG_MAX_LENGTH,\n slugify,\n type Post,\n type RepublishPostInput,\n} from '@adatechnology/content-contracts'\n\nimport { notifyPostChanged } from '../shared/notifyPostChanged'\nimport { nextOccurrenceAfter, toDateStamp } from '../shared/recurrence'\nimport { effectiveStatus, toPost } from '../shared/toContract'\nimport type { RecurrenceRow } from '../schema/schema'\nimport { PostUseCaseBase, type PostReference } from './Post.use-cases'\nimport { copiableFields } from './Template.use-cases'\n\nconst DEFAULT_BATCH_LIMIT = 100\nconst DATE_SUFFIX_LENGTH = 11\nconst FALLBACK_SLUG = 'post'\n\nexport class RepublishPostUseCase extends PostUseCaseBase {\n /**\n * Muda a data de um post JÁ publicado, mantendo o MESMO endereço. É a opção segura para SEO: o\n * link antigo (compartilhado, indexado, com backlinks) continua valendo e não nasce conteúdo\n * duplicado. Data futura é recusada — o post sairia do ar até lá e o leitor veria 404.\n */\n async execute(params: PostReference & { readonly input?: RepublishPostInput }): Promise<Post> {\n const input = republishPostSchema.parse(params.input ?? {})\n const existing = await this.findOrFail(params)\n const now = this.now()\n if (existing.isTemplate || effectiveStatus(existing, now) !== POST_STATUS.PUBLISHED) {\n throw new PostNotPublishedError(params.id)\n }\n const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now\n if (publishedAt > now) throw new RepublishDateInFutureError()\n return this.save(params, { status: POST_STATUS.PUBLISHED, publishedAt }, POST_EVENT.REPUBLISHED)\n }\n}\n\nexport type PublishDueResult = { readonly published: number; readonly materialized: number }\n\nexport class PublishDueUseCase extends PostUseCaseBase {\n /**\n * Idempotente e seguro com várias instâncias chamando ao mesmo tempo: cada post/regra é reclamado\n * por uma só execução. Sem trabalho vencido, não faz nada. `now` existe para teste e reprocesso.\n */\n async execute(params: { readonly now?: Date; readonly limit?: number } = {}): Promise<PublishDueResult> {\n const now = params.now ?? this.now()\n const limit = params.limit ?? DEFAULT_BATCH_LIMIT\n const materialized = await this.materializeRecurrences({ now, limit })\n const rows = await this.dependencies.posts.claimDueScheduled({ now, limit })\n for (const row of rows) {\n await notifyPostChanged(this.dependencies, POST_EVENT.PUBLISHED, toPost(row, now))\n }\n if (rows.length > 0 || materialized > 0) {\n this.dependencies.logger?.info('content-module: publishDue', { published: rows.length, materialized })\n }\n return { published: rows.length, materialized }\n }\n\n private materializeRecurrences(params: { now: Date; limit: number }): Promise<number> {\n return this.dependencies.recurrences.processDue({\n ...params,\n handle: (rule) => this.materialize(rule, params.now),\n })\n }\n\n /** Um post publicado agora a partir do modelo; a regra avança para a próxima data futura. */\n private async materialize(rule: RecurrenceRow, now: Date): Promise<Partial<RecurrenceRow>> {\n const advance = {\n nextRunAt: nextOccurrenceAfter({\n frequency: rule.frequency as 'weekly' | 'monthly',\n from: rule.nextRunAt,\n anchorDay: rule.anchorDay,\n now,\n }),\n }\n const template = await this.dependencies.posts.findById({ companyId: rule.companyId, id: rule.templateId })\n if (!template || !template.isTemplate || template.status === POST_STATUS.ARCHIVED) {\n // Modelo apagado: a regra para de rodar em vez de falhar a cada ciclo.\n this.dependencies.logger?.warn('content-module: modelo da recorrência indisponível', { ruleId: rule.id })\n return { isActive: false }\n }\n const base = (slugify(template.title) || FALLBACK_SLUG).slice(0, SLUG_MAX_LENGTH - DATE_SUFFIX_LENGTH)\n const slug = await this.uniqueSlug(rule.companyId, `${base.replace(/-+$/g, '')}-${toDateStamp(now)}`)\n const row = await this.dependencies.posts.create({\n ...copiableFields(template),\n companyId: rule.companyId,\n slug,\n shortId: await this.generateShortId(rule.companyId),\n title: template.title,\n isTemplate: false,\n status: POST_STATUS.PUBLISHED,\n publishedAt: now,\n })\n const post = toPost(row, now)\n await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, post)\n await notifyPostChanged(this.dependencies, POST_EVENT.PUBLISHED, post)\n return { ...advance, lastRunAt: now, lastPostId: row.id }\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Datas da recorrência, sempre em UTC: o instante de cada execução não depende do fuso do servidor.\n */\n\nimport { RECURRENCE_FREQUENCY, type RecurrenceFrequency } from '@adatechnology/content-contracts'\n\nconst WEEK_MS = 7 * 24 * 60 * 60 * 1000\n\nfunction daysInMonth(year: number, monthIndex: number): number {\n return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate()\n}\n\n/** Mensal no dia 31 cai em 28/29/30 nos meses curtos e VOLTA ao 31 depois (o âncora não deriva). */\nfunction addMonths(from: Date, anchorDay: number, months: number): Date {\n const target = new Date(Date.UTC(from.getUTCFullYear(), from.getUTCMonth() + months, 1))\n const day = Math.min(anchorDay, daysInMonth(target.getUTCFullYear(), target.getUTCMonth()))\n return new Date(\n Date.UTC(\n target.getUTCFullYear(),\n target.getUTCMonth(),\n day,\n from.getUTCHours(),\n from.getUTCMinutes(),\n from.getUTCSeconds(),\n from.getUTCMilliseconds(),\n ),\n )\n}\n\nexport function nextOccurrence(params: { frequency: RecurrenceFrequency; from: Date; anchorDay: number }): Date {\n if (params.frequency === RECURRENCE_FREQUENCY.WEEKLY) return new Date(params.from.getTime() + WEEK_MS)\n return addMonths(params.from, params.anchorDay, 1)\n}\n\n/**\n * Primeira ocorrência estritamente depois de `now`. Servidor parado três semanas publica UM post ao\n * voltar, não três: as ocorrências perdidas são puladas, nunca emitidas em rajada.\n */\nexport function nextOccurrenceAfter(params: {\n frequency: RecurrenceFrequency\n from: Date\n anchorDay: number\n now: Date\n}): Date {\n let candidate = nextOccurrence(params)\n while (candidate <= params.now) candidate = nextOccurrence({ ...params, from: candidate })\n return candidate\n}\n\nexport function toDateStamp(date: Date): string {\n return date.toISOString().slice(0, 10)\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Modelos de post: salvar um post como modelo e criar um post novo a partir de um modelo. Modelo é\n * post com `isTemplate`: nunca vai ao ar, não aparece na lista de posts e não tem endereço público.\n */\n\nimport {\n createFromTemplateSchema,\n DuplicateSlugError,\n normalizeTags,\n NotATemplateError,\n POST_EVENT,\n POST_STATUS,\n saveAsTemplateSchema,\n type CreateFromTemplateInput,\n type Post,\n type PostCounts,\n type SaveAsTemplateInput,\n} from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../schema/schema'\nimport { isUniqueViolation } from '../shared/isUniqueViolation'\nimport { notifyPostChanged } from '../shared/notifyPostChanged'\nimport { toPost } from '../shared/toContract'\nimport { PostUseCaseBase, type PostReference } from './Post.use-cases'\n\nconst TEMPLATE_SLUG_PREFIX = 'modelo'\n\n/**\n * Conteúdo reaproveitável de um post. `canonicalUrl` NÃO é copiado: o canonical do original apontaria\n * o buscador para outra página e esconderia o post novo.\n */\nexport function copiableFields(row: PostRow): Partial<NewPostRow> {\n return {\n excerpt: row.excerpt,\n body: row.body,\n coverImageUrl: row.coverImageUrl,\n coverImageAlt: row.coverImageAlt,\n tags: normalizeTags(row.tags),\n tagLabels: row.tagLabels,\n authorName: row.authorName,\n seoTitle: row.seoTitle,\n seoDescription: row.seoDescription,\n readingTimeMinutes: row.readingTimeMinutes,\n }\n}\n\nabstract class TemplateUseCaseBase extends PostUseCaseBase {\n protected async insertCopy(params: {\n readonly companyId: string\n readonly slug: string\n readonly title: string\n readonly source: PostRow\n readonly isTemplate: boolean\n readonly status?: string\n readonly publishedAt?: Date\n }): Promise<Post> {\n const row = await this.dependencies.posts\n .create({\n ...copiableFields(params.source),\n companyId: params.companyId,\n slug: params.slug,\n shortId: await this.generateShortId(params.companyId),\n title: params.title,\n isTemplate: params.isTemplate,\n status: params.status ?? POST_STATUS.DRAFT,\n ...(params.publishedAt ? { publishedAt: params.publishedAt } : {}),\n })\n .catch((error: unknown) => {\n if (isUniqueViolation(error)) throw new DuplicateSlugError(params.slug)\n throw error\n })\n const post = toPost(row, this.now())\n await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, post)\n return post\n }\n}\n\nexport class SaveAsTemplateUseCase extends TemplateUseCaseBase {\n /** Copia o post (qualquer status) para um modelo. O original não muda. */\n async execute(params: PostReference & { readonly input?: SaveAsTemplateInput }): Promise<Post> {\n const input = saveAsTemplateSchema.parse(params.input ?? {})\n const source = await this.findOrFail(params)\n const title = input.title ?? source.title\n const slug = await this.generateSlug(params.companyId, `${TEMPLATE_SLUG_PREFIX} ${title}`)\n return this.insertCopy({ companyId: params.companyId, slug, title, source, isTemplate: true })\n }\n}\n\nexport class CreateFromTemplateUseCase extends TemplateUseCaseBase {\n /** Cria um RASCUNHO novo com o conteúdo do modelo, pronto para editar e publicar. */\n async execute(params: PostReference & { readonly input?: CreateFromTemplateInput }): Promise<Post> {\n const input = createFromTemplateSchema.parse(params.input ?? {})\n const template = await this.findOrFail(params)\n if (!template.isTemplate) throw new NotATemplateError(params.id)\n const title = input.title ?? template.title\n if (input.slug) await this.assertSlugAvailable(params.companyId, input.slug)\n const slug = input.slug ?? (await this.generateSlug(params.companyId, title))\n return this.insertCopy({ companyId: params.companyId, slug, title, source: template, isTemplate: false })\n }\n}\n\nexport class CountPostsUseCase extends PostUseCaseBase {\n /** Números das abas do painel, numa consulta só. */\n async execute(params: { readonly companyId: string }): Promise<PostCounts> {\n return this.dependencies.posts.countByStatus({ companyId: params.companyId, now: this.now() })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Upload da capa. O bucket é do host (`ContentImageStoragePort`); aqui ficam as decisões que não\n * variam por instalação: formatos aceitos, teto de tamanho e forma da chave.\n */\n\nimport { ImageStorageDisabledError, InvalidCoverImageError } from '@adatechnology/content-contracts'\n\nimport { COVER_IMAGE } from '../shared/coverImage.constant'\nimport type { ContentDependencies } from './contentModule.types'\n\nexport type UploadCoverImageParams = {\n readonly companyId: string\n readonly bytes: Uint8Array\n readonly mimeType: string\n}\n\nexport type UploadCoverImageResult = { readonly url: string; readonly key: string }\n\nexport class UploadCoverImageUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n async execute(params: UploadCoverImageParams): Promise<UploadCoverImageResult> {\n const storage = this.dependencies.imageStorage\n if (!storage) throw new ImageStorageDisabledError()\n\n const mimeType = (params.mimeType.split(';')[0] ?? '').trim().toLowerCase()\n // Lista fechada, não \"começa com image/\": SVG é imagem e carrega script.\n const extension = COVER_IMAGE.EXTENSION_BY_MIME[mimeType]\n if (!extension) throw new InvalidCoverImageError('unsupported_type')\n if (params.bytes.byteLength === 0) throw new InvalidCoverImageError('empty')\n if (params.bytes.byteLength > COVER_IMAGE.MAX_BYTES) throw new InvalidCoverImageError('too_large')\n\n // A chave nunca carrega nome de arquivo: é entrada de usuário e vai parar numa URL pública.\n const key = `${COVER_IMAGE.KEY_PREFIX}/${params.companyId}/${crypto.randomUUID()}.${extension}`\n return storage.upload({ buffer: params.bytes, mimeType, key })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * 1 MiB é o teto de corpo do `module-http`: um limite maior aqui seria promessa que a rota não\n * cumpre. O `content-ui` avisa antes de enviar; o servidor recusa de novo porque o cliente não é\n * fonte de verdade.\n */\nexport const COVER_IMAGE = {\n MAX_BYTES: 1024 * 1024,\n KEY_PREFIX: 'content/posts',\n EXTENSION_BY_MIME: {\n 'image/jpeg': 'jpg',\n 'image/png': 'png',\n 'image/webp': 'webp',\n } as Readonly<Record<string, string | undefined>>,\n} as const\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport {\n createFromTemplateSchema,\n createPostSchema,\n createRecurrenceSchema,\n DEFAULT_ADMIN_SCOPES,\n listPostsQuerySchema,\n publishPostSchema,\n republishPostSchema,\n saveAsTemplateSchema,\n updatePostSchema,\n updateRecurrenceSchema,\n type CreateFromTemplateInput,\n type CreatePostInput,\n type CreateRecurrenceInput,\n type ListPostsQuery,\n type PublishPostInput,\n type RepublishPostInput,\n type SaveAsTemplateInput,\n type UpdatePostInput,\n type UpdateRecurrenceInput,\n} from '@adatechnology/content-contracts'\nimport type { ModuleRoute, RequestContext } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { TAG_SCOPE } from '../use-cases/PublicPost.use-cases'\nimport { requireCompany } from './requireCompany'\n\nfunction reference(context: RequestContext): { companyId: string; id: string } {\n return { companyId: requireCompany(context), id: context.params.id ?? '' }\n}\n\nconst json = (status: number, data: unknown) => ({ kind: 'json' as const, status, body: { data } })\n\nexport function buildAdminRoutes(module: ContentModule): ModuleRoute[] {\n const { useCases } = module\n const requiredScopes = module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES\n const admin = { scope: 'admin' as const, requiredScopes }\n\n const uploadRoutes: ModuleRoute[] = useCases.uploadCoverImage\n ? [\n {\n ...admin,\n method: 'POST',\n path: '/posts/cover-images',\n operationId: 'uploadPostCoverImage',\n summary: 'Envia a imagem de capa (bytes crus, Content-Type jpeg/png/webp) e devolve a URL',\n async handler(context) {\n const upload = useCases.uploadCoverImage\n if (!upload) return { kind: 'empty', status: 404 }\n const result = await upload.execute({\n companyId: requireCompany(context),\n bytes: context.rawBody ?? new Uint8Array(),\n mimeType: context.headers['content-type'] ?? '',\n })\n return json(201, result)\n },\n },\n ]\n : []\n\n return [\n {\n ...admin,\n method: 'GET',\n path: '/posts',\n querySchema: listPostsQuerySchema,\n operationId: 'listPosts',\n summary: 'Lista posts da empresa (todos os status), com filtro por status, tag e busca',\n async handler(context) {\n const result = await useCases.listPosts.execute({\n companyId: requireCompany(context),\n ...(context.query as unknown as ListPostsQuery),\n })\n return { kind: 'json', status: 200, body: result }\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts',\n bodySchema: createPostSchema,\n operationId: 'createPost',\n summary: 'Cria um post como rascunho; sem slug, gera a partir do título',\n async handler(context) {\n const post = await useCases.createPost.execute({\n companyId: requireCompany(context),\n input: context.body as CreatePostInput,\n })\n return json(201, post)\n },\n },\n // Antes de `/posts/:id`: `findRoute` para na primeira rota que casa, e `:id` casaria \"tags\".\n {\n ...admin,\n method: 'GET',\n path: '/posts/tags',\n operationId: 'listPostTags',\n summary: 'Tags usadas em qualquer post da empresa, com contagem',\n async handler(context) {\n return json(\n 200,\n await useCases.listTags.execute({ companyId: requireCompany(context), scope: TAG_SCOPE.ADMIN }),\n )\n },\n },\n {\n ...admin,\n method: 'GET',\n path: '/posts/counts',\n operationId: 'countPosts',\n summary: 'Contagem de posts por aba: publicados, agendados, rascunhos, arquivados e modelos',\n async handler(context) {\n return json(200, await useCases.countPosts.execute({ companyId: requireCompany(context) }))\n },\n },\n ...recurrenceRoutes(module),\n ...uploadRoutes,\n {\n ...admin,\n method: 'GET',\n path: '/posts/:id',\n operationId: 'getPost',\n summary: 'Lê um post da empresa (qualquer status)',\n async handler(context) {\n return json(200, await useCases.getPost.execute(reference(context)))\n },\n },\n {\n ...admin,\n method: 'PATCH',\n path: '/posts/:id',\n bodySchema: updatePostSchema,\n operationId: 'updatePost',\n summary: 'Atualiza campos de um post; trocar o título não troca o slug',\n async handler(context) {\n return json(\n 200,\n await useCases.updatePost.execute({ ...reference(context), input: context.body as UpdatePostInput }),\n )\n },\n },\n {\n ...admin,\n method: 'DELETE',\n path: '/posts/:id',\n operationId: 'archivePost',\n summary: 'Arquiva o post: sai do site, conteúdo e slug continuam guardados',\n async handler(context) {\n await useCases.archivePost.execute(reference(context))\n return { kind: 'empty', status: 204 }\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/publish',\n // Opcional: `POST /publish` sem corpo publica agora.\n bodySchema: publishPostSchema.optional(),\n operationId: 'publishPost',\n summary: 'Publica agora, ou agenda quando `publishedAt` é futuro',\n async handler(context) {\n return json(\n 200,\n await useCases.publishPost.execute({\n ...reference(context),\n input: (context.body ?? {}) as PublishPostInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/unpublish',\n operationId: 'unpublishPost',\n summary: 'Tira do ar (ou cancela o agendamento) e volta a rascunho',\n async handler(context) {\n return json(200, await useCases.unpublishPost.execute(reference(context)))\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/republish',\n bodySchema: republishPostSchema.optional(),\n operationId: 'republishPost',\n summary: 'Republica um post no ar com nova data, mantendo o mesmo endereço (SEO); data futura é recusada',\n async handler(context) {\n return json(\n 200,\n await useCases.republishPost.execute({\n ...reference(context),\n input: (context.body ?? {}) as RepublishPostInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/save-as-template',\n bodySchema: saveAsTemplateSchema.optional(),\n operationId: 'savePostAsTemplate',\n summary: 'Copia o post para um modelo (o original não muda)',\n async handler(context) {\n return json(\n 201,\n await useCases.saveAsTemplate.execute({\n ...reference(context),\n input: (context.body ?? {}) as SaveAsTemplateInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/from-template',\n bodySchema: createFromTemplateSchema.optional(),\n operationId: 'createPostFromTemplate',\n summary: 'Cria um rascunho novo a partir do modelo `:id`',\n async handler(context) {\n return json(\n 201,\n await useCases.createFromTemplate.execute({\n ...reference(context),\n input: (context.body ?? {}) as CreateFromTemplateInput,\n }),\n )\n },\n },\n ]\n}\n\nfunction recurrenceRoutes(module: ContentModule): ModuleRoute[] {\n const { useCases } = module\n const admin = { scope: 'admin' as const, requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES }\n return [\n {\n ...admin,\n method: 'GET',\n path: '/recurrences',\n operationId: 'listRecurrences',\n summary: 'Regras de recorrência da empresa',\n async handler(context) {\n return json(200, await useCases.listRecurrences.execute({ companyId: requireCompany(context) }))\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/recurrences',\n bodySchema: createRecurrenceSchema,\n operationId: 'createRecurrence',\n summary: 'Cria regra: publica um post novo, copiado do modelo, toda semana ou todo mês',\n async handler(context) {\n return json(\n 201,\n await useCases.createRecurrence.execute({\n companyId: requireCompany(context),\n input: context.body as CreateRecurrenceInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'PATCH',\n path: '/recurrences/:id',\n bodySchema: updateRecurrenceSchema,\n operationId: 'updateRecurrence',\n summary: 'Pausa, retoma ou remarca a próxima execução',\n async handler(context) {\n return json(\n 200,\n await useCases.updateRecurrence.execute({\n ...reference(context),\n input: context.body as UpdateRecurrenceInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'DELETE',\n path: '/recurrences/:id',\n operationId: 'removeRecurrence',\n summary: 'Apaga a regra; os posts já publicados por ela continuam no ar',\n async handler(context) {\n await useCases.removeRecurrence.execute(reference(context))\n return { kind: 'empty', status: 204 }\n },\n },\n ]\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { CONTENT_ERROR_CODES, ContentError } from '@adatechnology/content-contracts'\nimport type { RequestContext } from '@adatechnology/module-http'\n\n/** `dispatchRoute` já recusa rota de admin sem identidade; isto só garante o tipo para o handler. */\nexport function requireCompany(context: RequestContext): string {\n if (!context.auth?.companyId) {\n throw new ContentError('Rota exige contexto autenticado.', 401, CONTENT_ERROR_CODES.CONFIG_MISSING)\n }\n return context.auth.companyId\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Rotas do site público. Sem identidade: a empresa vem do `PublicCompanyResolverPort` do host\n * (domínio, cabeçalho, empresa fixa…). Resolver sem resposta = 404, igual a post inexistente.\n */\n\nimport {\n DEFAULT_PUBLIC_CACHE_CONTROL,\n listPublishedPostsQuerySchema,\n PostNotFoundError,\n type ListPublishedPostsQuery,\n} from '@adatechnology/content-contracts'\nimport type { HttpResult, ModuleRoute, RequestContext } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { FEED_FORMAT } from '../use-cases/Feed.use-cases'\nimport { TAG_SCOPE } from '../use-cases/PublicPost.use-cases'\n\nexport interface PublicCompanyResolverPort {\n resolve(params: {\n readonly headers: Readonly<Record<string, string>>\n readonly query: Readonly<Record<string, string>>\n }): Promise<string | undefined>\n}\n\nconst PUBLIC = { scope: 'public' as const }\n\nexport function buildPublicRoutes(params: {\n module: ContentModule\n companyResolver: PublicCompanyResolverPort\n}): ModuleRoute[] {\n const { useCases } = params.module\n const cacheControl = params.module.config.publicCacheControl ?? DEFAULT_PUBLIC_CACHE_CONTROL\n const cached = (data: unknown): HttpResult => ({\n kind: 'json',\n status: 200,\n body: data,\n headers: { 'Cache-Control': cacheControl },\n })\n\n async function resolveCompany(context: RequestContext): Promise<string> {\n const companyId = await params.companyResolver.resolve({ headers: context.headers, query: context.query })\n if (!companyId) throw new PostNotFoundError('company')\n return companyId\n }\n\n const routes: ModuleRoute[] = [\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/posts',\n querySchema: listPublishedPostsQuerySchema,\n operationId: 'listPublishedPosts',\n summary: 'Posts publicados, mais recentes primeiro, com filtro por tag',\n async handler(context) {\n const result = await useCases.listPublishedPosts.execute({\n companyId: await resolveCompany(context),\n ...(context.query as unknown as ListPublishedPostsQuery),\n })\n return cached(result)\n },\n },\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/posts/:slug',\n operationId: 'getPublishedPost',\n summary: 'Post publicado pelo slug; rascunho, agendado futuro e arquivado respondem 404',\n async handler(context) {\n const post = await useCases.getPublishedPostBySlug.execute({\n companyId: await resolveCompany(context),\n slug: context.params.slug ?? '',\n })\n return cached({ data: post })\n },\n },\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/tags',\n operationId: 'listPublishedTags',\n summary: 'Tags dos posts publicados, com contagem',\n async handler(context) {\n const tags = await useCases.listTags.execute({\n companyId: await resolveCompany(context),\n scope: TAG_SCOPE.PUBLIC,\n })\n return cached({ data: tags })\n },\n },\n ]\n\n const { buildFeed, listSitemapEntries } = useCases\n if (!buildFeed || !listSitemapEntries) return routes\n\n const feedRoute = (path: string, format: 'rss' | 'atom', contentType: string, operationId: string): ModuleRoute => ({\n ...PUBLIC,\n method: 'GET',\n path,\n operationId,\n summary: `Feed ${format.toUpperCase()} dos posts publicados`,\n async handler(context) {\n const body = await buildFeed.execute({ companyId: await resolveCompany(context), format })\n return {\n kind: 'text',\n status: 200,\n body,\n headers: { 'Content-Type': contentType, 'Cache-Control': cacheControl },\n }\n },\n })\n\n return [\n ...routes,\n feedRoute('/public/feed.xml', FEED_FORMAT.RSS, 'application/rss+xml; charset=utf-8', 'getRssFeed'),\n feedRoute('/public/atom.xml', FEED_FORMAT.ATOM, 'application/atom+xml; charset=utf-8', 'getAtomFeed'),\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/sitemap-entries',\n operationId: 'listSitemapEntries',\n summary: 'Entradas de sitemap (loc, lastmod) dos posts publicados, para o host juntar ao sitemap dele',\n async handler(context) {\n return cached({ data: await listSitemapEntries.execute({ companyId: await resolveCompany(context) }) })\n },\n },\n ]\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { ModuleRouteTable } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { buildAdminRoutes } from './adminRoutes'\nimport { buildPublicRoutes, type PublicCompanyResolverPort } from './publicRoutes'\n\nexport type CreateContentRoutesParams = {\n readonly module: ContentModule\n /**\n * Como o site público diz de qual empresa é o blog (domínio, cabeçalho, valor fixo…). Ausente,\n * as rotas `/public/*` não sobem: o host que só tem painel não expõe leitura anônima.\n */\n readonly publicCompanyResolver?: PublicCompanyResolverPort\n}\n\nexport function createContentRoutes(params: CreateContentRoutesParams): ModuleRouteTable {\n const admin = buildAdminRoutes(params.module)\n if (!params.publicCompanyResolver) return admin\n return [...admin, ...buildPublicRoutes({ module: params.module, companyResolver: params.publicCompanyResolver })]\n}\n\nexport type { PublicCompanyResolverPort }\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { join } from 'node:path'\n\nimport type { ContentDatabase, DrizzleMigrateFunction } from './database.types'\n\n// Journal próprio, fora do pgSchema `content`: a primeira migration é quem cria esse schema\n// (mesmo raciocínio de `catalog-module/runMigrations.ts`).\nexport const CONTENT_MIGRATIONS_TABLE = 'content_migrations'\n\n/** Pasta no formato clássico (`meta/_journal.json`), lida pelos migrators do drizzle 0.x e 1.x. */\nexport function contentMigrationsFolder(): string {\n return join(__dirname, 'migrations')\n}\n\nexport type RunContentMigrationsParams = {\n readonly db: ContentDatabase\n /** O `migrate` do driver do host (`drizzle-orm/node-postgres/migrator`, `.../bun-sql/migrator`…). */\n readonly migrate: DrizzleMigrateFunction\n}\n\nexport async function runContentMigrations(params: RunContentMigrationsParams): Promise<void> {\n await params.migrate(params.db as never, {\n migrationsFolder: contentMigrationsFolder(),\n migrationsTable: CONTENT_MIGRATIONS_TABLE,\n })\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Dublê em memória do `PostStorePort`, para a suíte de comportamento do módulo e para o teste do\n * host. O isolamento real (cláusula SQL) é provado em `repositories/isolation.test.ts`; aqui as\n * mesmas regras são reproduzidas em JavaScript, inclusive a violação de índice único do slug.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { POST_STATUS, type TagCount } from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../schema/schema'\nimport { effectiveStatus } from '../shared/toContract'\nimport type { PostAdminListQuery, PostPage, PostPublicListQuery, PostStorePort } from '../use-cases/contentModule.types'\n\nfunction isPublic(row: PostRow, now: Date): boolean {\n const live = row.status === POST_STATUS.PUBLISHED || row.status === POST_STATUS.SCHEDULED\n return live && row.publishedAt !== null && row.publishedAt <= now\n}\n\nfunction adminComparator(query: PostAdminListQuery) {\n const sign = query.order === 'asc' ? 1 : -1\n const value = (row: PostRow): number | string => {\n if (query.sort === 'title') return row.title.toLowerCase()\n if (query.sort === 'status') return row.status\n if (query.sort === 'publishedAt') return row.publishedAt?.getTime() ?? sign * Number.POSITIVE_INFINITY\n return row.updatedAt.getTime()\n }\n return (left: PostRow, right: PostRow): number => {\n const a = value(left)\n const b = value(right)\n return (a < b ? -1 : a > b ? 1 : 0) * sign || left.id.localeCompare(right.id)\n }\n}\n\nfunction paginate(rows: PostRow[], page: number, pageSize: number): PostPage {\n return { rows: rows.slice((page - 1) * pageSize, page * pageSize).map((row) => ({ ...row })), total: rows.length }\n}\n\nclass UniqueViolation extends Error {\n readonly code = '23505'\n}\n\nexport function createInMemoryPostStore(seed: PostRow[] = []): PostStorePort & { readonly rows: PostRow[] } {\n const rows: PostRow[] = [...seed]\n const formerSlugs: { companyId: string; slug: string; postId: string }[] = []\n\n const assertUniqueSlug = (companyId: string, slug: string, ownId?: string): void => {\n if (rows.some((row) => row.companyId === companyId && row.slug === slug && row.id !== ownId)) {\n throw new UniqueViolation('duplicate key value violates unique constraint \"idx_posts_company_slug\"')\n }\n }\n\n return {\n rows,\n\n async findByShortId({ companyId, shortId }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.shortId === shortId)\n return row ? { ...row } : undefined\n },\n\n async findPublicByShortId({ companyId, shortId, now }) {\n const row = rows.find(\n (candidate) => candidate.companyId === companyId && candidate.shortId === shortId && isPublic(candidate, now),\n )\n return row ? { ...row } : undefined\n },\n\n async findPublicByFormerSlug({ companyId, slug, now }) {\n const former = formerSlugs.find((entry) => entry.companyId === companyId && entry.slug === slug)\n const row = rows.find((candidate) => candidate.id === former?.postId && isPublic(candidate, now))\n return row ? { ...row } : undefined\n },\n\n async recordFormerSlug(params) {\n if (!formerSlugs.some((entry) => entry.companyId === params.companyId && entry.slug === params.slug)) {\n formerSlugs.push({ ...params })\n }\n },\n\n async create(values: NewPostRow): Promise<PostRow> {\n assertUniqueSlug(values.companyId, values.slug)\n const now = new Date()\n const row: PostRow = {\n id: randomUUID(),\n excerpt: null,\n body: '',\n coverImageUrl: null,\n coverImageAlt: null,\n tags: [],\n tagLabels: {},\n status: POST_STATUS.DRAFT,\n isTemplate: false,\n publishedAt: null,\n authorName: null,\n seoTitle: null,\n seoDescription: null,\n canonicalUrl: null,\n readingTimeMinutes: 1,\n createdAt: now,\n updatedAt: now,\n ...values,\n } as PostRow\n rows.push(row)\n return { ...row }\n },\n\n async findById({ companyId, id }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id)\n return row ? { ...row } : undefined\n },\n\n async findBySlug({ companyId, slug }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.slug === slug)\n return row ? { ...row } : undefined\n },\n\n async findPublicBySlug({ companyId, slug, now }) {\n const row = rows.find(\n (candidate) => candidate.companyId === companyId && candidate.slug === slug && isPublic(candidate, now),\n )\n return row ? { ...row } : undefined\n },\n\n async update({ companyId, id, values }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id)\n if (!row) return undefined\n if (values.slug !== undefined) assertUniqueSlug(companyId, values.slug, id)\n Object.assign(row, values, { updatedAt: new Date(Math.max(Date.now(), row.updatedAt.getTime() + 1)) })\n return { ...row }\n },\n\n async listForAdmin(query: PostAdminListQuery) {\n const search = query.search?.toLowerCase()\n const matched = rows\n .filter((row) => row.companyId === query.companyId)\n .filter((row) => (query.isTemplate ? row.isTemplate && row.status !== POST_STATUS.ARCHIVED : !row.isTemplate))\n .filter((row) => !query.status || effectiveStatus(row, query.now) === query.status)\n .filter((row) => !query.tags?.length || query.tags.some((tag) => row.tags.includes(tag)))\n .filter((row) => !search || row.title.toLowerCase().includes(search) || row.slug.includes(search))\n .sort(adminComparator(query))\n return paginate(matched, query.page, query.pageSize)\n },\n\n async countByStatus({ companyId, now }) {\n const counts = { published: 0, scheduled: 0, draft: 0, archived: 0, templates: 0 }\n for (const row of rows) {\n if (row.companyId !== companyId) continue\n if (row.isTemplate) {\n if (row.status !== POST_STATUS.ARCHIVED) counts.templates += 1\n continue\n }\n counts[effectiveStatus(row, now) as keyof typeof counts] += 1\n }\n return counts\n },\n\n async claimDueScheduled({ now, limit }) {\n const due = rows\n .filter(\n (row) => row.status === POST_STATUS.SCHEDULED && !row.isTemplate && row.publishedAt && row.publishedAt <= now,\n )\n .sort((left, right) => (left.publishedAt?.getTime() ?? 0) - (right.publishedAt?.getTime() ?? 0))\n .slice(0, limit)\n for (const row of due) row.status = POST_STATUS.PUBLISHED\n return due.map((row) => ({ ...row }))\n },\n\n async listPublic(query: PostPublicListQuery) {\n const matched = rows\n .filter((row) => row.companyId === query.companyId && isPublic(row, query.now))\n .filter((row) => !query.tag || row.tags.includes(query.tag))\n .sort((left, right) => (right.publishedAt?.getTime() ?? 0) - (left.publishedAt?.getTime() ?? 0))\n return paginate(matched, query.page, query.pageSize)\n },\n\n async listTags({ companyId, publicAt }): Promise<readonly TagCount[]> {\n const counts = new Map<string, number>()\n for (const row of rows) {\n if (row.companyId !== companyId || (publicAt && !isPublic(row, publicAt))) continue\n for (const tag of row.tags) counts.set(tag, (counts.get(tag) ?? 0) + 1)\n }\n return [...counts.entries()]\n .map(([tag, count]) => ({ tag, count }))\n .sort((left, right) => right.count - left.count || left.tag.localeCompare(right.tag))\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { LoggerPort } from '@adatechnology/content-contracts'\n\nimport type { ContentModule } from './ContentModule'\n\nexport const DEFAULT_SCHEDULER_INTERVAL_MS = 60_000\n\nexport type StartContentSchedulerParams = {\n readonly module: ContentModule\n /** Padrão: 1 minuto. */\n readonly intervalMs?: number\n readonly logger?: LoggerPort\n}\n\n/**\n * Chama `publishDue` num intervalo, com guarda de execução única neste processo: se um ciclo ainda\n * está rodando, o próximo tick é pulado em vez de empilhar. Entre instâncias, quem garante é o\n * `FOR UPDATE SKIP LOCKED` do store. Erro de um ciclo é logado e o seguinte tenta de novo.\n * Devolve a função que para o agendador (chame no desligamento).\n */\nexport function startContentScheduler(params: StartContentSchedulerParams): () => void {\n let isRunning = false\n const tick = async (): Promise<void> => {\n if (isRunning) return\n isRunning = true\n try {\n await params.module.useCases.publishDue.execute()\n } catch (error) {\n params.logger?.error('content-module: ciclo do agendador falhou', {\n error: error instanceof Error ? error.message : String(error),\n })\n } finally {\n isRunning = false\n }\n }\n const timer = setInterval(() => void tick(), params.intervalMs ?? DEFAULT_SCHEDULER_INTERVAL_MS)\n timer.unref?.()\n void tick()\n return () => clearInterval(timer)\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Dublê em memória do `RecurrenceStorePort`: mesmas regras, sem transação (o teste é de um processo só).\n */\n\nimport { randomUUID } from 'node:crypto'\n\nimport type { NewRecurrenceRow, RecurrenceRow } from '../schema/schema'\nimport type { RecurrenceStorePort } from '../use-cases/contentModule.types'\n\nexport function createInMemoryRecurrenceStore(): RecurrenceStorePort & { readonly rows: RecurrenceRow[] } {\n const rows: RecurrenceRow[] = []\n const owned = (companyId: string, id: string) => rows.find((row) => row.companyId === companyId && row.id === id)\n\n return {\n rows,\n async create(values: NewRecurrenceRow) {\n const row = {\n id: randomUUID(),\n isActive: true,\n lastRunAt: null,\n lastPostId: null,\n createdAt: new Date(),\n ...values,\n } as RecurrenceRow\n rows.push(row)\n return { ...row }\n },\n async findById({ companyId, id }) {\n const row = owned(companyId, id)\n return row ? { ...row } : undefined\n },\n async list({ companyId }) {\n return rows\n .filter((row) => row.companyId === companyId)\n .sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime())\n .map((row) => ({ ...row }))\n },\n async update({ companyId, id, values }) {\n const row = owned(companyId, id)\n if (!row) return undefined\n Object.assign(row, values)\n return { ...row }\n },\n async remove({ companyId, id }) {\n const index = rows.findIndex((row) => row.companyId === companyId && row.id === id)\n if (index < 0) return false\n rows.splice(index, 1)\n return true\n },\n async processDue({ now, limit, handle }) {\n const due = rows\n .filter((row) => row.isActive && row.nextRunAt <= now)\n .sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime())\n .slice(0, limit)\n for (const row of due) Object.assign(row, await handle({ ...row }))\n return due.length\n },\n }\n}\n"],"mappings":";;;;AACA,OAAOA,UAAU;AACjB,SAASC,qBAAqB;AAE9B,IAAMC,cAAc,6BAAMC,cAAc,YAAYC,GAAG,GAAnC;AACpB,IAAMC,aAAa,6BAAMC,KAAKC,QAAQL,YAAAA,CAAAA,GAAnB;AAEZ,IAAMM,YAA4BH,2BAAAA;;;ACAzC,SAASI,0BAA0B;;;ACHnC,SAASC,OAAAA,MAAKC,KAAKC,MAAMC,MAAAA,KAAIC,WAAAA,UAASC,OAAAA,YAAW;AACjD,SAASC,eAAAA,oBAAmD;;;ACD5D,SAASC,WAAW;AACpB,SACEC,SACAC,OACAC,SACAC,OACAC,YACAC,UACAC,MACAC,WACAC,aACAC,MACAC,eACK;AAGA,IAAMC,gBAAgBN,SAAS,SAAA;AAG/B,IAAMO,QAAQD,cAAcE,MACjC,SACA;EACEC,IAAIL,KAAK,IAAA,EAAML,WAAU,EAAGW,cAAa;EACzCC,WAAWP,KAAK,YAAA,EAAc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,OAAM,GAAE;AACpC,YAAMF,MAAMJ,MAAMC,WAAWC,EAAAA;AAC7B,UAAI,CAACE,IAAK,QAAOW;AACjBU,aAAOC,OAAOtB,KAAKE,MAAAA;AACnB,aAAO;QAAE,GAAGF;MAAI;IAClB;IACA,MAAMuB,OAAO,EAAE1B,WAAWC,GAAE,GAAE;AAC5B,YAAM0B,SAAQ7B,KAAK8B,UAAU,CAACzB,QAAQA,IAAIH,cAAcA,aAAaG,IAAIF,OAAOA,EAAAA;AAChF,UAAI0B,SAAQ,EAAG,QAAO;AACtB7B,WAAK+B,OAAOF,QAAO,CAAA;AACnB,aAAO;IACT;IACA,MAAMG,WAAW,EAAEC,KAAKC,OAAOC,OAAM,GAAE;AACrC,YAAMC,MAAMpC,KACTkB,OAAO,CAACb,QAAQA,IAAII,YAAYJ,IAAIiB,aAAaW,GAAAA,EACjDd,KAAK,CAACC,MAAMC,UAAUD,KAAKE,UAAUC,QAAO,IAAKF,MAAMC,UAAUC,QAAO,CAAA,EACxEc,MAAM,GAAGH,KAAAA;AACZ,iBAAW7B,OAAO+B,IAAKV,QAAOC,OAAOtB,KAAK,MAAM8B,OAAO;QAAE,GAAG9B;MAAI,CAAA,CAAA;AAChE,aAAO+B,IAAIE;IACb;EACF;AACF;AAjDgBvC;","names":["path","fileURLToPath","getFilename","fileURLToPath","url","getDirname","path","dirname","__dirname","ConfigMissingError","and","asc","desc","eq","inArray","sql","POST_STATUS","sql","boolean","index","integer","jsonb","primaryKey","pgSchema","text","timestamp","uniqueIndex","uuid","varchar","contentSchema","posts","table","id","defaultRandom","companyId","notNull","slug","length","shortId","title","excerpt","body","default","coverImageUrl","coverImageAlt","tags","array","tagLabels","$type","status","isTemplate","publishedAt","withTimezone","authorName","seoTitle","seoDescription","canonicalUrl","readingTimeMinutes","createdAt","defaultNow","updatedAt","on","using","where","recurrenceRules","templateId","references","frequency","anchorDay","isActive","nextRunAt","lastRunAt","lastPostId","postFormerSlugs","postId","columns","and","arrayContains","arrayOverlaps","eq","gt","inArray","lte","ne","or","sql","POST_STATUS","postOwnedByCondition","params","and","eq","posts","companyId","id","postSlugCondition","slug","postAdminListCondition","conditions","templateCondition","isTemplate","status","push","statusCondition","now","tags","length","arrayOverlaps","search","pattern","replace","character","sql","title","ne","POST_STATUS","ARCHIVED","PUBLISHED","or","SCHEDULED","lte","publishedAt","gt","postPublicCondition","inArray","tag","arrayContains","postPublicSlugCondition","postDueCondition","postShortIdCondition","shortId","postPublicShortIdCondition","TAG_LIST_LIMIT","SORT_COLUMNS","title","posts","status","publishedAt","updatedAt","adminOrder","query","column","sort","direction","order","asc","desc","primary","sql","raw","id","PostRepository","db","create","values","row","insert","returning","Error","findById","params","select","from","where","postOwnedByCondition","limit","findBySlug","postSlugCondition","findPublicBySlug","postPublicSlugCondition","findByShortId","postShortIdCondition","findPublicByShortId","postPublicShortIdCondition","findPublicByFormerSlug","former","postId","postFormerSlugs","and","eq","companyId","slug","undefined","postPublicCondition","recordFormerSlug","onConflictDoNothing","update","set","Date","listForAdmin","postAdminListCondition","rows","counted","Promise","all","orderBy","pageSize","offset","page","value","total","listPublic","countByStatus","now","toISOString","condition","livePublished","POST_STATUS","PUBLISHED","SCHEDULED","published","isTemplate","scheduled","draft","DRAFT","archived","ARCHIVED","templates","claimDueScheduled","due","postDueCondition","for","skipLocked","inArray","listTags","publicAt","postTags","tag","tags","as","count","groupBy","and","asc","eq","lte","recurrenceOwnedByCondition","params","and","eq","recurrenceRules","companyId","id","RecurrenceRepository","db","create","values","row","insert","returning","Error","findById","select","from","where","limit","list","orderBy","asc","nextRunAt","update","set","remove","removed","delete","length","processDue","transaction","due","isActive","lte","now","for","skipLocked","processed","rule","handle","buildAtomFeed","buildExcerpt","buildPostUrl","buildRssFeed","renderMarkdownToHtml","DEFAULT_ITEM_LIMIT","SITEMAP_LIMIT","FEED_FORMAT","RSS","ATOM","BuildFeedUseCase","dependencies","feed","execute","params","now","clock","page","posts","listPublic","companyId","pageSize","itemLimit","channel","siteUrl","title","description","language","feedUrl","items","rows","map","row","toItem","format","buildAtomFeed","buildRssFeed","url","buildPostUrl","slug","shortId","postPathTemplate","publishedAt","createdAt","toISOString","updatedAt","summary","excerpt","buildExcerpt","body","includeContent","contentHtml","renderMarkdownToHtml","headingIds","authorName","categories","tags","coverImageUrl","imageUrl","ListSitemapEntriesUseCase","loc","lastmod","buildTagLabels","createPostSchema","DuplicateSlugError","estimateReadingTimeMinutes","listPostsQuerySchema","normalizeTags","POST_EVENT","POST_STATUS","PostNotFoundError","TemplateNotPublishableError","publishPostSchema","buildShortSlug","updatePostSchema","withSlugSuffix","randomInt","SHORT_ID_LENGTH","ALPHABET","generateShortId","value","index","SHORT_ID_LENGTH","randomInt","length","UNIQUE_VIOLATION","isUniqueViolation","error","current","depth","code","cause","notifyPostChanged","dependencies","type","post","hook","hooks","onPostChanged","error","logger","postId","id","Error","message","String","POST_STATUS","effectiveStatus","row","now","status","POST_STATUS","SCHEDULED","publishedAt","PUBLISHED","toPostSummary","id","companyId","slug","shortId","title","excerpt","coverImageUrl","coverImageAlt","tags","tagLabels","isTemplate","toISOString","authorName","seoTitle","seoDescription","canonicalUrl","readingTimeMinutes","createdAt","updatedAt","toPost","body","toPublicPostSummary","toPublicPost","toPagination","params","totalPages","Math","max","ceil","total","pageSize","MAX_SLUG_ATTEMPTS","FALLBACK_SLUG","PostUseCaseBase","dependencies","now","clock","findOrFail","reference","row","posts","findById","PostNotFoundError","id","save","values","event","update","catch","error","isUniqueViolation","slug","DuplicateSlugError","post","toPost","notifyPostChanged","generateShortId","companyId","attempt","candidate","findByShortId","shortId","Error","readingTime","body","estimateReadingTimeMinutes","config","wordsPerMinute","assertSlugAvailable","ownId","existing","findBySlug","generateSlug","title","uniqueSlug","buildShortSlug","base","withSlugSuffix","Date","optionalFields","input","excerpt","undefined","coverImageUrl","coverImageAlt","authorName","seoTitle","seoDescription","canonicalUrl","CreatePostUseCase","execute","params","createPostSchema","parse","create","tags","normalizeTags","tagLabels","buildTagLabels","typed","explicit","status","POST_STATUS","DRAFT","readingTimeMinutes","POST_EVENT","CREATED","UpdatePostUseCase","updatePostSchema","previous","recordFormerSlug","postId","UPDATED","PublishPostUseCase","publishPostSchema","isTemplate","TemplateNotPublishableError","publishedAt","SCHEDULED","PUBLISHED","UnpublishPostUseCase","UNPUBLISHED","ArchivePostUseCase","ARCHIVED","GetPostUseCase","ListPostsUseCase","rawQuery","query","listPostsQuerySchema","tag","rawTag","rest","split","page","listForAdmin","length","data","rows","map","toPostSummary","pagination","toPagination","total","pageSize","listPublishedPostsQuerySchema","normalizeTag","parsePostRef","PostNotFoundError","GetPublishedPostBySlugUseCase","dependencies","execute","params","posts","clock","parsed","parsePostRef","slug","query","companyId","now","row","shortId","findPublicByShortId","undefined","findPublicBySlug","findPublicByFormerSlug","PostNotFoundError","toPublicPost","ListPublishedPostsUseCase","rawQuery","listPublishedPostsQuerySchema","parse","tag","normalizeTag","page","listPublic","pageSize","data","rows","map","toPublicPostSummary","pagination","toPagination","total","TAG_SCOPE","PUBLIC","ADMIN","ListTagsUseCase","listTags","scope","publicAt","createRecurrenceSchema","NotATemplateError","PostNotFoundError","RecurrenceNotFoundError","updateRecurrenceSchema","RecurrenceUseCaseBase","dependencies","toRule","row","template","posts","findById","companyId","id","templateId","templateTitle","title","frequency","isActive","nextRunAt","toISOString","lastRunAt","lastPostId","createdAt","findOrFail","params","recurrences","RecurrenceNotFoundError","CreateRecurrenceUseCase","execute","input","createRecurrenceSchema","parse","PostNotFoundError","isTemplate","NotATemplateError","startsAt","Date","values","anchorDay","getUTCDate","create","ListRecurrencesUseCase","rows","list","Promise","all","map","UpdateRecurrenceUseCase","updateRecurrenceSchema","undefined","update","RemoveRecurrenceUseCase","remove","POST_EVENT","POST_STATUS","PostNotPublishedError","republishPostSchema","RepublishDateInFutureError","SLUG_MAX_LENGTH","slugify","RECURRENCE_FREQUENCY","WEEK_MS","daysInMonth","year","monthIndex","Date","UTC","getUTCDate","addMonths","from","anchorDay","months","target","getUTCFullYear","getUTCMonth","day","Math","min","getUTCHours","getUTCMinutes","getUTCSeconds","getUTCMilliseconds","nextOccurrence","params","frequency","RECURRENCE_FREQUENCY","WEEKLY","getTime","nextOccurrenceAfter","candidate","now","toDateStamp","date","toISOString","slice","createFromTemplateSchema","DuplicateSlugError","normalizeTags","NotATemplateError","POST_EVENT","POST_STATUS","saveAsTemplateSchema","TEMPLATE_SLUG_PREFIX","copiableFields","row","excerpt","body","coverImageUrl","coverImageAlt","tags","normalizeTags","tagLabels","authorName","seoTitle","seoDescription","readingTimeMinutes","TemplateUseCaseBase","PostUseCaseBase","insertCopy","params","dependencies","posts","create","source","companyId","slug","shortId","generateShortId","title","isTemplate","status","POST_STATUS","DRAFT","publishedAt","catch","error","isUniqueViolation","DuplicateSlugError","post","toPost","now","notifyPostChanged","POST_EVENT","CREATED","SaveAsTemplateUseCase","execute","input","saveAsTemplateSchema","parse","findOrFail","generateSlug","CreateFromTemplateUseCase","createFromTemplateSchema","template","NotATemplateError","id","assertSlugAvailable","CountPostsUseCase","countByStatus","DEFAULT_BATCH_LIMIT","DATE_SUFFIX_LENGTH","FALLBACK_SLUG","RepublishPostUseCase","PostUseCaseBase","execute","params","input","republishPostSchema","parse","existing","findOrFail","now","isTemplate","effectiveStatus","POST_STATUS","PUBLISHED","PostNotPublishedError","id","publishedAt","Date","RepublishDateInFutureError","save","status","POST_EVENT","REPUBLISHED","PublishDueUseCase","limit","materialized","materializeRecurrences","rows","dependencies","posts","claimDueScheduled","row","notifyPostChanged","toPost","length","logger","info","published","recurrences","processDue","handle","rule","materialize","advance","nextRunAt","nextOccurrenceAfter","frequency","from","anchorDay","template","findById","companyId","templateId","ARCHIVED","warn","ruleId","isActive","base","slugify","title","slice","SLUG_MAX_LENGTH","slug","uniqueSlug","replace","toDateStamp","create","copiableFields","shortId","generateShortId","post","CREATED","lastRunAt","lastPostId","ImageStorageDisabledError","InvalidCoverImageError","COVER_IMAGE","MAX_BYTES","KEY_PREFIX","EXTENSION_BY_MIME","UploadCoverImageUseCase","dependencies","execute","params","storage","imageStorage","ImageStorageDisabledError","mimeType","split","trim","toLowerCase","extension","COVER_IMAGE","EXTENSION_BY_MIME","InvalidCoverImageError","bytes","byteLength","MAX_BYTES","key","KEY_PREFIX","companyId","crypto","randomUUID","upload","buffer","SYSTEM_CLOCK","now","Date","assertValidConfig","config","feed","test","siteUrl","ConfigMissingError","title","trim","postPathTemplate","includes","wordsPerMinute","undefined","createContentModule","params","posts","providers","postStore","db","PostRepository","recurrences","recurrenceStore","RecurrenceRepository","dependencies","clock","hooks","imageStorage","logger","useCases","createPost","CreatePostUseCase","updatePost","UpdatePostUseCase","archivePost","ArchivePostUseCase","publishPost","PublishPostUseCase","unpublishPost","UnpublishPostUseCase","getPost","GetPostUseCase","listPosts","ListPostsUseCase","getPublishedPostBySlug","GetPublishedPostBySlugUseCase","listPublishedPosts","ListPublishedPostsUseCase","listTags","ListTagsUseCase","countPosts","CountPostsUseCase","saveAsTemplate","SaveAsTemplateUseCase","createFromTemplate","CreateFromTemplateUseCase","republishPost","RepublishPostUseCase","createRecurrence","CreateRecurrenceUseCase","listRecurrences","ListRecurrencesUseCase","updateRecurrence","UpdateRecurrenceUseCase","removeRecurrence","RemoveRecurrenceUseCase","publishDue","PublishDueUseCase","uploadCoverImage","UploadCoverImageUseCase","buildFeed","BuildFeedUseCase","listSitemapEntries","ListSitemapEntriesUseCase","createFromTemplateSchema","createPostSchema","createRecurrenceSchema","DEFAULT_ADMIN_SCOPES","listPostsQuerySchema","publishPostSchema","republishPostSchema","saveAsTemplateSchema","updatePostSchema","updateRecurrenceSchema","CONTENT_ERROR_CODES","ContentError","requireCompany","context","auth","companyId","ContentError","CONTENT_ERROR_CODES","CONFIG_MISSING","reference","context","companyId","requireCompany","id","params","json","status","data","kind","body","buildAdminRoutes","module","useCases","requiredScopes","config","adminScopes","DEFAULT_ADMIN_SCOPES","admin","scope","uploadRoutes","uploadCoverImage","method","path","operationId","summary","handler","upload","result","execute","bytes","rawBody","Uint8Array","mimeType","headers","querySchema","listPostsQuerySchema","listPosts","query","bodySchema","createPostSchema","post","createPost","input","listTags","TAG_SCOPE","ADMIN","countPosts","recurrenceRoutes","getPost","updatePostSchema","updatePost","archivePost","publishPostSchema","optional","publishPost","unpublishPost","republishPostSchema","republishPost","saveAsTemplateSchema","saveAsTemplate","createFromTemplateSchema","createFromTemplate","listRecurrences","createRecurrenceSchema","createRecurrence","updateRecurrenceSchema","updateRecurrence","removeRecurrence","DEFAULT_PUBLIC_CACHE_CONTROL","listPublishedPostsQuerySchema","PostNotFoundError","PUBLIC","scope","buildPublicRoutes","params","useCases","module","cacheControl","config","publicCacheControl","DEFAULT_PUBLIC_CACHE_CONTROL","cached","data","kind","status","body","headers","resolveCompany","context","companyId","companyResolver","resolve","query","PostNotFoundError","routes","method","path","querySchema","listPublishedPostsQuerySchema","operationId","summary","handler","result","listPublishedPosts","execute","post","getPublishedPostBySlug","slug","tags","listTags","TAG_SCOPE","buildFeed","listSitemapEntries","feedRoute","format","contentType","toUpperCase","FEED_FORMAT","RSS","ATOM","createContentRoutes","params","admin","buildAdminRoutes","module","publicCompanyResolver","buildPublicRoutes","companyResolver","join","CONTENT_MIGRATIONS_TABLE","contentMigrationsFolder","join","__dirname","runContentMigrations","params","migrate","db","migrationsFolder","migrationsTable","randomUUID","POST_STATUS","isPublic","row","now","live","status","POST_STATUS","PUBLISHED","SCHEDULED","publishedAt","adminComparator","query","sign","order","value","sort","title","toLowerCase","getTime","Number","POSITIVE_INFINITY","updatedAt","left","right","a","b","id","localeCompare","paginate","rows","page","pageSize","slice","map","total","length","UniqueViolation","Error","code","createInMemoryPostStore","seed","formerSlugs","assertUniqueSlug","companyId","slug","ownId","some","findByShortId","shortId","find","candidate","undefined","findPublicByShortId","findPublicByFormerSlug","former","entry","postId","recordFormerSlug","params","push","create","values","Date","randomUUID","excerpt","body","coverImageUrl","coverImageAlt","tags","tagLabels","DRAFT","isTemplate","authorName","seoTitle","seoDescription","canonicalUrl","readingTimeMinutes","createdAt","findById","findBySlug","findPublicBySlug","update","Object","assign","Math","max","listForAdmin","search","matched","filter","ARCHIVED","effectiveStatus","tag","includes","countByStatus","counts","published","scheduled","draft","archived","templates","claimDueScheduled","limit","due","listPublic","listTags","publicAt","Map","set","get","entries","count","DEFAULT_SCHEDULER_INTERVAL_MS","startContentScheduler","params","isRunning","tick","module","useCases","publishDue","execute","error","logger","Error","message","String","timer","setInterval","intervalMs","unref","clearInterval","randomUUID","createInMemoryRecurrenceStore","rows","owned","companyId","id","find","row","create","values","randomUUID","isActive","lastRunAt","lastPostId","createdAt","Date","push","findById","undefined","list","filter","sort","left","right","nextRunAt","getTime","map","update","Object","assign","remove","index","findIndex","splice","processDue","now","limit","handle","due","slice","length"]}
|