@adatechnology/content-module 0.0.0-stage → 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/dist/index.js ADDED
@@ -0,0 +1,2140 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // ../../../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
5
+ import path from "path";
6
+ import { fileURLToPath } from "url";
7
+ var getFilename = /* @__PURE__ */ __name(() => fileURLToPath(import.meta.url), "getFilename");
8
+ var getDirname = /* @__PURE__ */ __name(() => path.dirname(getFilename()), "getDirname");
9
+ var __dirname = /* @__PURE__ */ getDirname();
10
+
11
+ // src/ContentModule.ts
12
+ import { ConfigMissingError } from "@adatechnology/content-contracts";
13
+
14
+ // src/repositories/PostRepository.ts
15
+ import { and as and2, asc, desc, eq as eq2, inArray as inArray2, sql as sql3 } from "drizzle-orm";
16
+ import { POST_STATUS as POST_STATUS2 } from "@adatechnology/content-contracts";
17
+
18
+ // src/schema/schema.ts
19
+ import { sql } from "drizzle-orm";
20
+ import { boolean, index, integer, jsonb, primaryKey, pgSchema, text, timestamp, uniqueIndex, uuid, varchar } from "drizzle-orm/pg-core";
21
+ var contentSchema = pgSchema("content");
22
+ var posts = contentSchema.table("posts", {
23
+ id: uuid("id").primaryKey().defaultRandom(),
24
+ companyId: uuid("company_id").notNull(),
25
+ slug: varchar("slug", {
26
+ length: 120
27
+ }).notNull(),
28
+ shortId: varchar("short_id", {
29
+ length: 6
30
+ }).notNull(),
31
+ title: varchar("title", {
32
+ length: 200
33
+ }).notNull(),
34
+ excerpt: varchar("excerpt", {
35
+ length: 500
36
+ }),
37
+ body: text("body").notNull().default(""),
38
+ coverImageUrl: varchar("cover_image_url", {
39
+ length: 2048
40
+ }),
41
+ coverImageAlt: varchar("cover_image_alt", {
42
+ length: 300
43
+ }),
44
+ tags: text("tags").array().notNull().default([]),
45
+ tagLabels: jsonb("tag_labels").$type().notNull().default({}),
46
+ status: varchar("status", {
47
+ length: 12
48
+ }).notNull().default("draft"),
49
+ isTemplate: boolean("is_template").notNull().default(false),
50
+ publishedAt: timestamp("published_at", {
51
+ withTimezone: true
52
+ }),
53
+ authorName: varchar("author_name", {
54
+ length: 120
55
+ }),
56
+ seoTitle: varchar("seo_title", {
57
+ length: 200
58
+ }),
59
+ seoDescription: varchar("seo_description", {
60
+ length: 320
61
+ }),
62
+ canonicalUrl: varchar("canonical_url", {
63
+ length: 2048
64
+ }),
65
+ readingTimeMinutes: integer("reading_time_minutes").notNull().default(1),
66
+ createdAt: timestamp("created_at", {
67
+ withTimezone: true
68
+ }).notNull().defaultNow(),
69
+ updatedAt: timestamp("updated_at", {
70
+ withTimezone: true
71
+ }).notNull().defaultNow()
72
+ }, (table) => [
73
+ // Sem `where deleted_at`: excluir é arquivar, e o slug arquivado continua reservado — reusá-lo
74
+ // faria um link antigo (já compartilhado) abrir outro post.
75
+ uniqueIndex("idx_posts_company_slug").on(table.companyId, table.slug),
76
+ uniqueIndex("idx_posts_company_short_id").on(table.companyId, table.shortId),
77
+ // Serve a listagem pública: empresa + status + ordem por data.
78
+ index("idx_posts_company_status_published").on(table.companyId, table.status, table.publishedAt),
79
+ index("idx_posts_tags").using("gin", table.tags),
80
+ // Serve o `publishDue`: só linha agendada entra, então o índice fica minúsculo.
81
+ index("idx_posts_due").on(table.publishedAt).where(sql`"status" = 'scheduled'`)
82
+ ]);
83
+ var recurrenceRules = contentSchema.table("recurrence_rules", {
84
+ id: uuid("id").primaryKey().defaultRandom(),
85
+ companyId: uuid("company_id").notNull(),
86
+ templateId: uuid("template_id").notNull().references(() => posts.id),
87
+ frequency: varchar("frequency", {
88
+ length: 10
89
+ }).notNull(),
90
+ // Dia do mês da primeira execução: mensal em 31 cai no último dia dos meses curtos e volta ao 31.
91
+ anchorDay: integer("anchor_day").notNull(),
92
+ isActive: boolean("is_active").notNull().default(true),
93
+ nextRunAt: timestamp("next_run_at", {
94
+ withTimezone: true
95
+ }).notNull(),
96
+ lastRunAt: timestamp("last_run_at", {
97
+ withTimezone: true
98
+ }),
99
+ lastPostId: uuid("last_post_id"),
100
+ createdAt: timestamp("created_at", {
101
+ withTimezone: true
102
+ }).notNull().defaultNow()
103
+ }, (table) => [
104
+ index("idx_recurrence_company").on(table.companyId),
105
+ index("idx_recurrence_due").on(table.nextRunAt).where(sql`"is_active"`)
106
+ ]);
107
+ var postFormerSlugs = contentSchema.table("post_former_slugs", {
108
+ companyId: uuid("company_id").notNull(),
109
+ slug: varchar("slug", {
110
+ length: 120
111
+ }).notNull(),
112
+ postId: uuid("post_id").notNull().references(() => posts.id),
113
+ createdAt: timestamp("created_at", {
114
+ withTimezone: true
115
+ }).notNull().defaultNow()
116
+ }, (table) => [
117
+ primaryKey({
118
+ columns: [
119
+ table.companyId,
120
+ table.slug
121
+ ]
122
+ })
123
+ ]);
124
+
125
+ // src/repositories/conditions.ts
126
+ import { and, arrayContains, arrayOverlaps, eq, gt, inArray, lte, ne, or, sql as sql2 } from "drizzle-orm";
127
+ import { POST_STATUS } from "@adatechnology/content-contracts";
128
+ function postOwnedByCondition(params) {
129
+ return and(eq(posts.companyId, params.companyId), eq(posts.id, params.id));
130
+ }
131
+ __name(postOwnedByCondition, "postOwnedByCondition");
132
+ function postSlugCondition(params) {
133
+ return and(eq(posts.companyId, params.companyId), eq(posts.slug, params.slug));
134
+ }
135
+ __name(postSlugCondition, "postSlugCondition");
136
+ function postAdminListCondition(params) {
137
+ const conditions = [
138
+ eq(posts.companyId, params.companyId),
139
+ templateCondition(params.isTemplate)
140
+ ];
141
+ if (params.status) conditions.push(statusCondition(params.status, params.now));
142
+ if (params.tags?.length) conditions.push(arrayOverlaps(posts.tags, [
143
+ ...params.tags
144
+ ]));
145
+ if (params.search) {
146
+ const pattern = `%${params.search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`;
147
+ conditions.push(sql2`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`);
148
+ }
149
+ return and(...conditions);
150
+ }
151
+ __name(postAdminListCondition, "postAdminListCondition");
152
+ function templateCondition(isTemplate) {
153
+ if (isTemplate) return and(eq(posts.isTemplate, true), ne(posts.status, POST_STATUS.ARCHIVED));
154
+ return eq(posts.isTemplate, false);
155
+ }
156
+ __name(templateCondition, "templateCondition");
157
+ function statusCondition(status, now) {
158
+ if (status === POST_STATUS.PUBLISHED) {
159
+ return or(eq(posts.status, POST_STATUS.PUBLISHED), and(eq(posts.status, POST_STATUS.SCHEDULED), lte(posts.publishedAt, now)));
160
+ }
161
+ if (status === POST_STATUS.SCHEDULED) {
162
+ return and(eq(posts.status, POST_STATUS.SCHEDULED), gt(posts.publishedAt, now));
163
+ }
164
+ return eq(posts.status, status);
165
+ }
166
+ __name(statusCondition, "statusCondition");
167
+ function postPublicCondition(params) {
168
+ const conditions = [
169
+ eq(posts.companyId, params.companyId),
170
+ inArray(posts.status, [
171
+ POST_STATUS.PUBLISHED,
172
+ POST_STATUS.SCHEDULED
173
+ ]),
174
+ lte(posts.publishedAt, params.now)
175
+ ];
176
+ if (params.tag) conditions.push(arrayContains(posts.tags, [
177
+ params.tag
178
+ ]));
179
+ return and(...conditions);
180
+ }
181
+ __name(postPublicCondition, "postPublicCondition");
182
+ function postPublicSlugCondition(params) {
183
+ return and(postPublicCondition(params), eq(posts.slug, params.slug));
184
+ }
185
+ __name(postPublicSlugCondition, "postPublicSlugCondition");
186
+ function postDueCondition(params) {
187
+ return and(eq(posts.status, POST_STATUS.SCHEDULED), eq(posts.isTemplate, false), lte(posts.publishedAt, params.now));
188
+ }
189
+ __name(postDueCondition, "postDueCondition");
190
+ function postShortIdCondition(params) {
191
+ return and(eq(posts.companyId, params.companyId), eq(posts.shortId, params.shortId));
192
+ }
193
+ __name(postShortIdCondition, "postShortIdCondition");
194
+ function postPublicShortIdCondition(params) {
195
+ return and(postPublicCondition(params), eq(posts.shortId, params.shortId));
196
+ }
197
+ __name(postPublicShortIdCondition, "postPublicShortIdCondition");
198
+
199
+ // src/repositories/PostRepository.ts
200
+ var TAG_LIST_LIMIT = 200;
201
+ var SORT_COLUMNS = {
202
+ title: posts.title,
203
+ status: posts.status,
204
+ publishedAt: posts.publishedAt,
205
+ updatedAt: posts.updatedAt
206
+ };
207
+ function adminOrder(query) {
208
+ const column = SORT_COLUMNS[query.sort ?? "updatedAt"];
209
+ const direction = (query.order ?? "desc") === "asc" ? asc : desc;
210
+ const primary = query.sort === "publishedAt" ? sql3`${column} ${sql3.raw(query.order === "asc" ? "asc" : "desc")} nulls last` : direction(column);
211
+ return [
212
+ primary,
213
+ asc(posts.id)
214
+ ];
215
+ }
216
+ __name(adminOrder, "adminOrder");
217
+ var PostRepository = class {
218
+ static {
219
+ __name(this, "PostRepository");
220
+ }
221
+ db;
222
+ constructor(db) {
223
+ this.db = db;
224
+ }
225
+ async create(values) {
226
+ const [row] = await this.db.insert(posts).values(values).returning();
227
+ if (!row) throw new Error("content-module: insert em posts n\xE3o retornou linha");
228
+ return row;
229
+ }
230
+ async findById(params) {
231
+ const [row] = await this.db.select().from(posts).where(postOwnedByCondition(params)).limit(1);
232
+ return row;
233
+ }
234
+ async findBySlug(params) {
235
+ const [row] = await this.db.select().from(posts).where(postSlugCondition(params)).limit(1);
236
+ return row;
237
+ }
238
+ async findPublicBySlug(params) {
239
+ const [row] = await this.db.select().from(posts).where(postPublicSlugCondition(params)).limit(1);
240
+ return row;
241
+ }
242
+ async findByShortId(params) {
243
+ const [row] = await this.db.select().from(posts).where(postShortIdCondition(params)).limit(1);
244
+ return row;
245
+ }
246
+ async findPublicByShortId(params) {
247
+ const [row] = await this.db.select().from(posts).where(postPublicShortIdCondition(params)).limit(1);
248
+ return row;
249
+ }
250
+ async findPublicByFormerSlug(params) {
251
+ const [former] = await this.db.select({
252
+ postId: postFormerSlugs.postId
253
+ }).from(postFormerSlugs).where(and2(eq2(postFormerSlugs.companyId, params.companyId), eq2(postFormerSlugs.slug, params.slug))).limit(1);
254
+ if (!former) return void 0;
255
+ const [row] = await this.db.select().from(posts).where(and2(postPublicCondition(params), eq2(posts.id, former.postId))).limit(1);
256
+ return row;
257
+ }
258
+ async recordFormerSlug(params) {
259
+ await this.db.insert(postFormerSlugs).values(params).onConflictDoNothing();
260
+ }
261
+ async update(params) {
262
+ const [row] = await this.db.update(posts).set({
263
+ ...params.values,
264
+ updatedAt: /* @__PURE__ */ new Date()
265
+ }).where(postOwnedByCondition(params)).returning();
266
+ return row;
267
+ }
268
+ async listForAdmin(query) {
269
+ const where = postAdminListCondition(query);
270
+ const [rows, [counted]] = await Promise.all([
271
+ this.db.select().from(posts).where(where).orderBy(...adminOrder(query)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
272
+ this.db.select({
273
+ value: sql3`count(*)::int`
274
+ }).from(posts).where(where)
275
+ ]);
276
+ return {
277
+ rows,
278
+ total: counted?.value ?? 0
279
+ };
280
+ }
281
+ async listPublic(query) {
282
+ const where = postPublicCondition(query);
283
+ const [rows, [counted]] = await Promise.all([
284
+ this.db.select().from(posts).where(where).orderBy(desc(posts.publishedAt), asc(posts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
285
+ this.db.select({
286
+ value: sql3`count(*)::int`
287
+ }).from(posts).where(where)
288
+ ]);
289
+ return {
290
+ rows,
291
+ total: counted?.value ?? 0
292
+ };
293
+ }
294
+ async countByStatus(params) {
295
+ const now = sql3`${params.now.toISOString()}::timestamptz`;
296
+ const counted = /* @__PURE__ */ __name((condition) => sql3`count(*) filter (where ${condition})::int`, "counted");
297
+ const livePublished = sql3`(${posts.status} = ${POST_STATUS2.PUBLISHED} or (${posts.status} = ${POST_STATUS2.SCHEDULED} and ${posts.publishedAt} <= ${now}))`;
298
+ const [row] = await this.db.select({
299
+ published: counted(sql3`not ${posts.isTemplate} and ${livePublished}`),
300
+ scheduled: counted(sql3`not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS2.SCHEDULED} and ${posts.publishedAt} > ${now}`),
301
+ draft: counted(sql3`not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS2.DRAFT}`),
302
+ archived: counted(sql3`not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS2.ARCHIVED}`),
303
+ templates: counted(sql3`${posts.isTemplate} and ${posts.status} <> ${POST_STATUS2.ARCHIVED}`)
304
+ }).from(posts).where(eq2(posts.companyId, params.companyId));
305
+ return row ?? {
306
+ published: 0,
307
+ scheduled: 0,
308
+ draft: 0,
309
+ archived: 0,
310
+ templates: 0
311
+ };
312
+ }
313
+ async claimDueScheduled(params) {
314
+ const due = this.db.select({
315
+ id: posts.id
316
+ }).from(posts).where(postDueCondition({
317
+ now: params.now
318
+ })).orderBy(asc(posts.publishedAt), asc(posts.id)).limit(params.limit).for("update", {
319
+ skipLocked: true
320
+ });
321
+ return this.db.update(posts).set({
322
+ status: POST_STATUS2.PUBLISHED
323
+ }).where(inArray2(posts.id, due)).returning();
324
+ }
325
+ async listTags(params) {
326
+ const where = params.publicAt ? postPublicCondition({
327
+ companyId: params.companyId,
328
+ now: params.publicAt
329
+ }) : postAdminListCondition({
330
+ companyId: params.companyId,
331
+ now: /* @__PURE__ */ new Date()
332
+ });
333
+ const postTags = this.db.select({
334
+ tag: sql3`unnest(${posts.tags})`.as("tag")
335
+ }).from(posts).where(where).as("post_tags");
336
+ const rows = await this.db.select({
337
+ tag: postTags.tag,
338
+ count: sql3`count(*)::int`
339
+ }).from(postTags).groupBy(postTags.tag).orderBy(sql3`count(*) desc`, asc(postTags.tag)).limit(TAG_LIST_LIMIT);
340
+ return rows;
341
+ }
342
+ };
343
+
344
+ // src/repositories/RecurrenceRepository.ts
345
+ import { and as and3, asc as asc2, eq as eq3, lte as lte2 } from "drizzle-orm";
346
+ function recurrenceOwnedByCondition(params) {
347
+ return and3(eq3(recurrenceRules.companyId, params.companyId), eq3(recurrenceRules.id, params.id));
348
+ }
349
+ __name(recurrenceOwnedByCondition, "recurrenceOwnedByCondition");
350
+ var RecurrenceRepository = class {
351
+ static {
352
+ __name(this, "RecurrenceRepository");
353
+ }
354
+ db;
355
+ constructor(db) {
356
+ this.db = db;
357
+ }
358
+ async create(values) {
359
+ const [row] = await this.db.insert(recurrenceRules).values(values).returning();
360
+ if (!row) throw new Error("content-module: insert em recurrence_rules n\xE3o retornou linha");
361
+ return row;
362
+ }
363
+ async findById(params) {
364
+ const [row] = await this.db.select().from(recurrenceRules).where(recurrenceOwnedByCondition(params)).limit(1);
365
+ return row;
366
+ }
367
+ async list(params) {
368
+ return this.db.select().from(recurrenceRules).where(eq3(recurrenceRules.companyId, params.companyId)).orderBy(asc2(recurrenceRules.nextRunAt), asc2(recurrenceRules.id));
369
+ }
370
+ async update(params) {
371
+ const [row] = await this.db.update(recurrenceRules).set(params.values).where(recurrenceOwnedByCondition(params)).returning();
372
+ return row;
373
+ }
374
+ async remove(params) {
375
+ const removed = await this.db.delete(recurrenceRules).where(recurrenceOwnedByCondition(params)).returning({
376
+ id: recurrenceRules.id
377
+ });
378
+ return removed.length > 0;
379
+ }
380
+ async processDue(params) {
381
+ return this.db.transaction(async (transaction) => {
382
+ const due = await transaction.select().from(recurrenceRules).where(and3(eq3(recurrenceRules.isActive, true), lte2(recurrenceRules.nextRunAt, params.now))).orderBy(asc2(recurrenceRules.nextRunAt), asc2(recurrenceRules.id)).limit(params.limit).for("update", {
383
+ skipLocked: true
384
+ });
385
+ let processed = 0;
386
+ for (const rule of due) {
387
+ const values = await params.handle(rule);
388
+ await transaction.update(recurrenceRules).set(values).where(eq3(recurrenceRules.id, rule.id));
389
+ processed += 1;
390
+ }
391
+ return processed;
392
+ });
393
+ }
394
+ };
395
+
396
+ // src/use-cases/Feed.use-cases.ts
397
+ import { buildAtomFeed, buildExcerpt, buildPostUrl, buildRssFeed, renderMarkdownToHtml } from "@adatechnology/content-contracts";
398
+ var DEFAULT_ITEM_LIMIT = 20;
399
+ var SITEMAP_LIMIT = 5e4;
400
+ var FEED_FORMAT = {
401
+ RSS: "rss",
402
+ ATOM: "atom"
403
+ };
404
+ var BuildFeedUseCase = class {
405
+ static {
406
+ __name(this, "BuildFeedUseCase");
407
+ }
408
+ dependencies;
409
+ feed;
410
+ constructor(dependencies, feed) {
411
+ this.dependencies = dependencies;
412
+ this.feed = feed;
413
+ }
414
+ async execute(params) {
415
+ const now = this.dependencies.clock.now();
416
+ const page = await this.dependencies.posts.listPublic({
417
+ companyId: params.companyId,
418
+ now,
419
+ page: 1,
420
+ pageSize: this.feed.itemLimit ?? DEFAULT_ITEM_LIMIT
421
+ });
422
+ const channel = {
423
+ siteUrl: this.feed.siteUrl,
424
+ title: this.feed.title,
425
+ ...this.feed.description ? {
426
+ description: this.feed.description
427
+ } : {},
428
+ ...this.feed.language ? {
429
+ language: this.feed.language
430
+ } : {},
431
+ ...params.feedUrl ? {
432
+ feedUrl: params.feedUrl
433
+ } : {}
434
+ };
435
+ const items = page.rows.map((row) => this.toItem(row));
436
+ return params.format === FEED_FORMAT.ATOM ? buildAtomFeed({
437
+ channel,
438
+ items,
439
+ now
440
+ }) : buildRssFeed({
441
+ channel,
442
+ items
443
+ });
444
+ }
445
+ toItem(row) {
446
+ return {
447
+ title: row.title,
448
+ url: buildPostUrl({
449
+ siteUrl: this.feed.siteUrl,
450
+ slug: row.slug,
451
+ shortId: row.shortId,
452
+ postPathTemplate: this.feed.postPathTemplate
453
+ }),
454
+ publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
455
+ updatedAt: row.updatedAt.toISOString(),
456
+ summary: row.excerpt ?? buildExcerpt(row.body),
457
+ ...this.feed.includeContent ?? true ? {
458
+ contentHtml: renderMarkdownToHtml(row.body, {
459
+ headingIds: false
460
+ })
461
+ } : {},
462
+ ...row.authorName ? {
463
+ authorName: row.authorName
464
+ } : {},
465
+ categories: row.tags,
466
+ ...row.coverImageUrl ? {
467
+ imageUrl: row.coverImageUrl
468
+ } : {}
469
+ };
470
+ }
471
+ };
472
+ var ListSitemapEntriesUseCase = class {
473
+ static {
474
+ __name(this, "ListSitemapEntriesUseCase");
475
+ }
476
+ dependencies;
477
+ feed;
478
+ constructor(dependencies, feed) {
479
+ this.dependencies = dependencies;
480
+ this.feed = feed;
481
+ }
482
+ /** Entradas para o host juntar ao sitemap dele — o módulo não é dono do sitemap do site. */
483
+ async execute(params) {
484
+ const page = await this.dependencies.posts.listPublic({
485
+ companyId: params.companyId,
486
+ now: this.dependencies.clock.now(),
487
+ page: 1,
488
+ pageSize: SITEMAP_LIMIT
489
+ });
490
+ return page.rows.map((row) => ({
491
+ loc: buildPostUrl({
492
+ siteUrl: this.feed.siteUrl,
493
+ slug: row.slug,
494
+ shortId: row.shortId,
495
+ postPathTemplate: this.feed.postPathTemplate
496
+ }),
497
+ lastmod: row.updatedAt.toISOString()
498
+ }));
499
+ }
500
+ };
501
+
502
+ // src/use-cases/Post.use-cases.ts
503
+ import { buildTagLabels, createPostSchema, DuplicateSlugError, estimateReadingTimeMinutes, listPostsQuerySchema, normalizeTags, POST_EVENT, POST_STATUS as POST_STATUS4, PostNotFoundError, TemplateNotPublishableError, publishPostSchema, buildShortSlug, updatePostSchema, withSlugSuffix } from "@adatechnology/content-contracts";
504
+
505
+ // src/shared/shortId.ts
506
+ import { randomInt } from "crypto";
507
+ import { SHORT_ID_LENGTH } from "@adatechnology/content-contracts";
508
+ var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
509
+ function generateShortId() {
510
+ let value = "";
511
+ for (let index2 = 0; index2 < SHORT_ID_LENGTH; index2 += 1) value += ALPHABET[randomInt(ALPHABET.length)];
512
+ return value;
513
+ }
514
+ __name(generateShortId, "generateShortId");
515
+
516
+ // src/shared/isUniqueViolation.ts
517
+ var UNIQUE_VIOLATION = "23505";
518
+ function isUniqueViolation(error) {
519
+ let current = error;
520
+ for (let depth = 0; depth < 3 && typeof current === "object" && current !== null; depth += 1) {
521
+ if (current.code === UNIQUE_VIOLATION) return true;
522
+ current = current.cause;
523
+ }
524
+ return false;
525
+ }
526
+ __name(isUniqueViolation, "isUniqueViolation");
527
+
528
+ // src/shared/notifyPostChanged.ts
529
+ async function notifyPostChanged(dependencies, type, post) {
530
+ const hook = dependencies.hooks?.onPostChanged;
531
+ if (!hook) return;
532
+ try {
533
+ await hook({
534
+ type,
535
+ post
536
+ });
537
+ } catch (error) {
538
+ dependencies.logger?.error("content-module: hook onPostChanged falhou", {
539
+ postId: post.id,
540
+ type,
541
+ error: error instanceof Error ? error.message : String(error)
542
+ });
543
+ }
544
+ }
545
+ __name(notifyPostChanged, "notifyPostChanged");
546
+
547
+ // src/shared/toContract.ts
548
+ import { POST_STATUS as POST_STATUS3 } from "@adatechnology/content-contracts";
549
+ function effectiveStatus(row, now) {
550
+ if (row.status === POST_STATUS3.SCHEDULED && row.publishedAt && row.publishedAt <= now) return POST_STATUS3.PUBLISHED;
551
+ return row.status;
552
+ }
553
+ __name(effectiveStatus, "effectiveStatus");
554
+ function toPostSummary(row, now) {
555
+ return {
556
+ id: row.id,
557
+ companyId: row.companyId,
558
+ slug: row.slug,
559
+ shortId: row.shortId,
560
+ title: row.title,
561
+ excerpt: row.excerpt,
562
+ coverImageUrl: row.coverImageUrl,
563
+ coverImageAlt: row.coverImageAlt,
564
+ tags: row.tags,
565
+ tagLabels: row.tagLabels,
566
+ status: effectiveStatus(row, now),
567
+ isTemplate: row.isTemplate,
568
+ publishedAt: row.publishedAt?.toISOString() ?? null,
569
+ authorName: row.authorName,
570
+ seoTitle: row.seoTitle,
571
+ seoDescription: row.seoDescription,
572
+ canonicalUrl: row.canonicalUrl,
573
+ readingTimeMinutes: row.readingTimeMinutes,
574
+ createdAt: row.createdAt.toISOString(),
575
+ updatedAt: row.updatedAt.toISOString()
576
+ };
577
+ }
578
+ __name(toPostSummary, "toPostSummary");
579
+ function toPost(row, now) {
580
+ return {
581
+ ...toPostSummary(row, now),
582
+ body: row.body
583
+ };
584
+ }
585
+ __name(toPost, "toPost");
586
+ function toPublicPostSummary(row) {
587
+ return {
588
+ id: row.id,
589
+ slug: row.slug,
590
+ shortId: row.shortId,
591
+ title: row.title,
592
+ excerpt: row.excerpt,
593
+ coverImageUrl: row.coverImageUrl,
594
+ coverImageAlt: row.coverImageAlt,
595
+ tags: row.tags,
596
+ tagLabels: row.tagLabels,
597
+ publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
598
+ updatedAt: row.updatedAt.toISOString(),
599
+ authorName: row.authorName,
600
+ seoTitle: row.seoTitle,
601
+ seoDescription: row.seoDescription,
602
+ canonicalUrl: row.canonicalUrl,
603
+ readingTimeMinutes: row.readingTimeMinutes
604
+ };
605
+ }
606
+ __name(toPublicPostSummary, "toPublicPostSummary");
607
+ function toPublicPost(row) {
608
+ return {
609
+ ...toPublicPostSummary(row),
610
+ body: row.body
611
+ };
612
+ }
613
+ __name(toPublicPost, "toPublicPost");
614
+ function toPagination(params) {
615
+ return {
616
+ ...params,
617
+ totalPages: Math.max(1, Math.ceil(params.total / params.pageSize))
618
+ };
619
+ }
620
+ __name(toPagination, "toPagination");
621
+
622
+ // src/use-cases/Post.use-cases.ts
623
+ var MAX_SLUG_ATTEMPTS = 50;
624
+ var FALLBACK_SLUG = "post";
625
+ var PostUseCaseBase = class {
626
+ static {
627
+ __name(this, "PostUseCaseBase");
628
+ }
629
+ dependencies;
630
+ constructor(dependencies) {
631
+ this.dependencies = dependencies;
632
+ }
633
+ now() {
634
+ return this.dependencies.clock.now();
635
+ }
636
+ async findOrFail(reference2) {
637
+ const row = await this.dependencies.posts.findById(reference2);
638
+ if (!row) throw new PostNotFoundError(reference2.id);
639
+ return row;
640
+ }
641
+ async save(reference2, values, event) {
642
+ const row = await this.dependencies.posts.update({
643
+ ...reference2,
644
+ values
645
+ }).catch((error) => {
646
+ if (isUniqueViolation(error) && values.slug) throw new DuplicateSlugError(values.slug);
647
+ throw error;
648
+ });
649
+ if (!row) throw new PostNotFoundError(reference2.id);
650
+ const post = toPost(row, this.now());
651
+ await notifyPostChanged(this.dependencies, event, post);
652
+ return post;
653
+ }
654
+ /** Id curto livre na empresa; a colisão (~1 em 2 bilhões) só repete o sorteio. */
655
+ async generateShortId(companyId) {
656
+ for (let attempt = 0; attempt < MAX_SLUG_ATTEMPTS; attempt += 1) {
657
+ const candidate = generateShortId();
658
+ if (!await this.dependencies.posts.findByShortId({
659
+ companyId,
660
+ shortId: candidate
661
+ })) return candidate;
662
+ }
663
+ throw new Error("content-module: sem id curto livre");
664
+ }
665
+ readingTime(body) {
666
+ return estimateReadingTimeMinutes(body, this.dependencies.config.wordsPerMinute);
667
+ }
668
+ async assertSlugAvailable(companyId, slug, ownId) {
669
+ const existing = await this.dependencies.posts.findBySlug({
670
+ companyId,
671
+ slug
672
+ });
673
+ if (existing && existing.id !== ownId) throw new DuplicateSlugError(slug);
674
+ }
675
+ /** `titulo`, `titulo-2`, `titulo-3`… Sequencial de propósito: cada tentativa depende da anterior. */
676
+ async generateSlug(companyId, title) {
677
+ return this.uniqueSlug(companyId, buildShortSlug(title, this.dependencies.config.slug) || FALLBACK_SLUG);
678
+ }
679
+ async uniqueSlug(companyId, base) {
680
+ for (let attempt = 1; attempt <= MAX_SLUG_ATTEMPTS; attempt += 1) {
681
+ const candidate = withSlugSuffix(base, attempt);
682
+ if (!await this.dependencies.posts.findBySlug({
683
+ companyId,
684
+ slug: candidate
685
+ })) return candidate;
686
+ }
687
+ return withSlugSuffix(base, Date.now());
688
+ }
689
+ };
690
+ function optionalFields(input) {
691
+ const values = {};
692
+ if (input.excerpt !== void 0) values.excerpt = input.excerpt || null;
693
+ if (input.coverImageUrl !== void 0) values.coverImageUrl = input.coverImageUrl || null;
694
+ if (input.coverImageAlt !== void 0) values.coverImageAlt = input.coverImageAlt || null;
695
+ if (input.authorName !== void 0) values.authorName = input.authorName || null;
696
+ if (input.seoTitle !== void 0) values.seoTitle = input.seoTitle || null;
697
+ if (input.seoDescription !== void 0) values.seoDescription = input.seoDescription || null;
698
+ if (input.canonicalUrl !== void 0) values.canonicalUrl = input.canonicalUrl || null;
699
+ return values;
700
+ }
701
+ __name(optionalFields, "optionalFields");
702
+ var CreatePostUseCase = class extends PostUseCaseBase {
703
+ static {
704
+ __name(this, "CreatePostUseCase");
705
+ }
706
+ async execute(params) {
707
+ const input = createPostSchema.parse(params.input);
708
+ const { companyId } = params;
709
+ if (input.slug) await this.assertSlugAvailable(companyId, input.slug);
710
+ const slug = input.slug ?? await this.generateSlug(companyId, input.title);
711
+ const row = await this.dependencies.posts.create({
712
+ companyId,
713
+ slug,
714
+ shortId: await this.generateShortId(companyId),
715
+ title: input.title,
716
+ body: input.body,
717
+ tags: normalizeTags(input.tags ?? []),
718
+ tagLabels: buildTagLabels({
719
+ typed: input.tags ?? [],
720
+ explicit: input.tagLabels
721
+ }),
722
+ status: POST_STATUS4.DRAFT,
723
+ readingTimeMinutes: this.readingTime(input.body),
724
+ ...optionalFields(input)
725
+ }).catch((error) => {
726
+ if (isUniqueViolation(error)) throw new DuplicateSlugError(slug);
727
+ throw error;
728
+ });
729
+ const post = toPost(row, this.now());
730
+ await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, post);
731
+ return post;
732
+ }
733
+ };
734
+ var UpdatePostUseCase = class extends PostUseCaseBase {
735
+ static {
736
+ __name(this, "UpdatePostUseCase");
737
+ }
738
+ /** Trocar o título não muda o slug: o endereço já pode ter sido compartilhado. */
739
+ async execute(params) {
740
+ const input = updatePostSchema.parse(params.input);
741
+ const existing = await this.findOrFail(params);
742
+ const values = optionalFields(input);
743
+ if (input.title !== void 0) values.title = input.title;
744
+ if (input.body !== void 0) {
745
+ values.body = input.body;
746
+ values.readingTimeMinutes = this.readingTime(input.body);
747
+ }
748
+ if (input.tags !== void 0 || input.tagLabels !== void 0) {
749
+ const tags = normalizeTags(input.tags ?? existing.tags);
750
+ values.tags = tags;
751
+ values.tagLabels = buildTagLabels({
752
+ typed: input.tags ?? tags,
753
+ explicit: input.tagLabels,
754
+ previous: existing.tagLabels
755
+ });
756
+ }
757
+ if (input.slug !== void 0 && input.slug !== existing.slug) {
758
+ await this.assertSlugAvailable(params.companyId, input.slug, existing.id);
759
+ values.slug = input.slug;
760
+ await this.dependencies.posts.recordFormerSlug({
761
+ companyId: params.companyId,
762
+ postId: existing.id,
763
+ slug: existing.slug
764
+ });
765
+ }
766
+ return this.save(params, values, POST_EVENT.UPDATED);
767
+ }
768
+ };
769
+ var PublishPostUseCase = class extends PostUseCaseBase {
770
+ static {
771
+ __name(this, "PublishPostUseCase");
772
+ }
773
+ /** Sem data: publica agora. Data futura: agenda. Data passada: publica com a data informada. */
774
+ async execute(params) {
775
+ const input = publishPostSchema.parse(params.input ?? {});
776
+ const existing = await this.findOrFail(params);
777
+ if (existing.isTemplate) throw new TemplateNotPublishableError(params.id);
778
+ const now = this.now();
779
+ const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now;
780
+ const status = publishedAt > now ? POST_STATUS4.SCHEDULED : POST_STATUS4.PUBLISHED;
781
+ return this.save(params, {
782
+ status,
783
+ publishedAt
784
+ }, POST_EVENT.PUBLISHED);
785
+ }
786
+ };
787
+ var UnpublishPostUseCase = class extends PostUseCaseBase {
788
+ static {
789
+ __name(this, "UnpublishPostUseCase");
790
+ }
791
+ /** Volta a rascunho e tira do ar na hora, inclusive cancelando um agendamento. */
792
+ async execute(params) {
793
+ await this.findOrFail(params);
794
+ return this.save(params, {
795
+ status: POST_STATUS4.DRAFT,
796
+ publishedAt: null
797
+ }, POST_EVENT.UNPUBLISHED);
798
+ }
799
+ };
800
+ var ArchivePostUseCase = class extends PostUseCaseBase {
801
+ static {
802
+ __name(this, "ArchivePostUseCase");
803
+ }
804
+ /** "Excluir" no painel é arquivar: some do site, mas o conteúdo e o slug continuam guardados. */
805
+ async execute(params) {
806
+ await this.findOrFail(params);
807
+ return this.save(params, {
808
+ status: POST_STATUS4.ARCHIVED
809
+ }, POST_EVENT.ARCHIVED);
810
+ }
811
+ };
812
+ var GetPostUseCase = class extends PostUseCaseBase {
813
+ static {
814
+ __name(this, "GetPostUseCase");
815
+ }
816
+ async execute(params) {
817
+ return toPost(await this.findOrFail(params), this.now());
818
+ }
819
+ };
820
+ var ListPostsUseCase = class extends PostUseCaseBase {
821
+ static {
822
+ __name(this, "ListPostsUseCase");
823
+ }
824
+ async execute(params) {
825
+ const { companyId, ...rawQuery } = params;
826
+ const query = listPostsQuerySchema.parse(rawQuery);
827
+ const { tag: rawTag, ...rest } = query;
828
+ const tags = rawTag ? normalizeTags(rawTag.split(",")) : [];
829
+ const now = this.now();
830
+ const page = await this.dependencies.posts.listForAdmin({
831
+ companyId,
832
+ ...rest,
833
+ isTemplate: query.isTemplate ?? false,
834
+ now,
835
+ ...tags.length > 0 ? {
836
+ tags
837
+ } : {}
838
+ });
839
+ return {
840
+ data: page.rows.map((row) => toPostSummary(row, now)),
841
+ pagination: toPagination({
842
+ total: page.total,
843
+ page: query.page,
844
+ pageSize: query.pageSize
845
+ })
846
+ };
847
+ }
848
+ };
849
+
850
+ // src/use-cases/PublicPost.use-cases.ts
851
+ import { listPublishedPostsQuerySchema, normalizeTag, parsePostRef, PostNotFoundError as PostNotFoundError2 } from "@adatechnology/content-contracts";
852
+ var GetPublishedPostBySlugUseCase = class {
853
+ static {
854
+ __name(this, "GetPublishedPostBySlugUseCase");
855
+ }
856
+ dependencies;
857
+ constructor(dependencies) {
858
+ this.dependencies = dependencies;
859
+ }
860
+ /**
861
+ * `slug` aceita o endereço canônico `<shortId>-<slug>`, o slug atual e slug antigo. O id curto
862
+ * manda: título/slug editado depois não quebra link compartilhado. O host compara `buildPostRef`
863
+ * do resultado com o pedido e redireciona (301) quando forem diferentes.
864
+ */
865
+ async execute(params) {
866
+ const { posts: posts2, clock } = this.dependencies;
867
+ const parsed = parsePostRef(params.slug);
868
+ const query = {
869
+ companyId: params.companyId,
870
+ now: clock.now()
871
+ };
872
+ const row = (parsed.shortId ? await posts2.findPublicByShortId({
873
+ ...query,
874
+ shortId: parsed.shortId
875
+ }) : void 0) ?? await posts2.findPublicBySlug({
876
+ ...query,
877
+ slug: parsed.slug
878
+ }) ?? await posts2.findPublicByFormerSlug({
879
+ ...query,
880
+ slug: parsed.slug
881
+ });
882
+ if (!row) throw new PostNotFoundError2(parsed.slug);
883
+ return toPublicPost(row);
884
+ }
885
+ };
886
+ var ListPublishedPostsUseCase = class {
887
+ static {
888
+ __name(this, "ListPublishedPostsUseCase");
889
+ }
890
+ dependencies;
891
+ constructor(dependencies) {
892
+ this.dependencies = dependencies;
893
+ }
894
+ async execute(params) {
895
+ const { companyId, ...rawQuery } = params;
896
+ const query = listPublishedPostsQuerySchema.parse(rawQuery);
897
+ const tag = query.tag ? normalizeTag(query.tag) : void 0;
898
+ const page = await this.dependencies.posts.listPublic({
899
+ companyId,
900
+ now: this.dependencies.clock.now(),
901
+ page: query.page,
902
+ pageSize: query.pageSize,
903
+ ...tag ? {
904
+ tag
905
+ } : {}
906
+ });
907
+ return {
908
+ data: page.rows.map(toPublicPostSummary),
909
+ pagination: toPagination({
910
+ total: page.total,
911
+ page: query.page,
912
+ pageSize: query.pageSize
913
+ })
914
+ };
915
+ }
916
+ };
917
+ var TAG_SCOPE = {
918
+ PUBLIC: "public",
919
+ ADMIN: "admin"
920
+ };
921
+ var ListTagsUseCase = class {
922
+ static {
923
+ __name(this, "ListTagsUseCase");
924
+ }
925
+ dependencies;
926
+ constructor(dependencies) {
927
+ this.dependencies = dependencies;
928
+ }
929
+ /** `public` conta só posts no ar; `admin` conta todos, para o autor reaproveitar a tag. */
930
+ async execute(params) {
931
+ return this.dependencies.posts.listTags({
932
+ companyId: params.companyId,
933
+ ...params.scope === TAG_SCOPE.PUBLIC ? {
934
+ publicAt: this.dependencies.clock.now()
935
+ } : {}
936
+ });
937
+ }
938
+ };
939
+
940
+ // src/use-cases/Recurrence.use-cases.ts
941
+ import { createRecurrenceSchema, NotATemplateError, PostNotFoundError as PostNotFoundError3, RecurrenceNotFoundError, updateRecurrenceSchema } from "@adatechnology/content-contracts";
942
+ var RecurrenceUseCaseBase = class RecurrenceUseCaseBase2 {
943
+ static {
944
+ __name(this, "RecurrenceUseCaseBase");
945
+ }
946
+ dependencies;
947
+ constructor(dependencies) {
948
+ this.dependencies = dependencies;
949
+ }
950
+ async toRule(row) {
951
+ const template = await this.dependencies.posts.findById({
952
+ companyId: row.companyId,
953
+ id: row.templateId
954
+ });
955
+ return {
956
+ id: row.id,
957
+ companyId: row.companyId,
958
+ templateId: row.templateId,
959
+ templateTitle: template?.title ?? "",
960
+ frequency: row.frequency,
961
+ isActive: row.isActive,
962
+ nextRunAt: row.nextRunAt.toISOString(),
963
+ lastRunAt: row.lastRunAt?.toISOString() ?? null,
964
+ lastPostId: row.lastPostId,
965
+ createdAt: row.createdAt.toISOString()
966
+ };
967
+ }
968
+ async findOrFail(params) {
969
+ const row = await this.dependencies.recurrences.findById(params);
970
+ if (!row) throw new RecurrenceNotFoundError(params.id);
971
+ return row;
972
+ }
973
+ };
974
+ var CreateRecurrenceUseCase = class extends RecurrenceUseCaseBase {
975
+ static {
976
+ __name(this, "CreateRecurrenceUseCase");
977
+ }
978
+ async execute(params) {
979
+ const input = createRecurrenceSchema.parse(params.input);
980
+ const template = await this.dependencies.posts.findById({
981
+ companyId: params.companyId,
982
+ id: input.templateId
983
+ });
984
+ if (!template) throw new PostNotFoundError3(input.templateId);
985
+ if (!template.isTemplate) throw new NotATemplateError(input.templateId);
986
+ const startsAt = new Date(input.startsAt);
987
+ const values = {
988
+ companyId: params.companyId,
989
+ templateId: input.templateId,
990
+ frequency: input.frequency,
991
+ anchorDay: startsAt.getUTCDate(),
992
+ nextRunAt: startsAt
993
+ };
994
+ return this.toRule(await this.dependencies.recurrences.create(values));
995
+ }
996
+ };
997
+ var ListRecurrencesUseCase = class extends RecurrenceUseCaseBase {
998
+ static {
999
+ __name(this, "ListRecurrencesUseCase");
1000
+ }
1001
+ async execute(params) {
1002
+ const rows = await this.dependencies.recurrences.list(params);
1003
+ return Promise.all(rows.map((row) => this.toRule(row)));
1004
+ }
1005
+ };
1006
+ var UpdateRecurrenceUseCase = class extends RecurrenceUseCaseBase {
1007
+ static {
1008
+ __name(this, "UpdateRecurrenceUseCase");
1009
+ }
1010
+ /** Pausar/retomar e remarcar a próxima execução. */
1011
+ async execute(params) {
1012
+ const input = updateRecurrenceSchema.parse(params.input);
1013
+ await this.findOrFail(params);
1014
+ const values = {};
1015
+ if (input.isActive !== void 0) values.isActive = input.isActive;
1016
+ if (input.nextRunAt !== void 0) {
1017
+ values.nextRunAt = new Date(input.nextRunAt);
1018
+ values.anchorDay = values.nextRunAt.getUTCDate();
1019
+ }
1020
+ const row = await this.dependencies.recurrences.update({
1021
+ companyId: params.companyId,
1022
+ id: params.id,
1023
+ values
1024
+ });
1025
+ if (!row) throw new RecurrenceNotFoundError(params.id);
1026
+ return this.toRule(row);
1027
+ }
1028
+ };
1029
+ var RemoveRecurrenceUseCase = class extends RecurrenceUseCaseBase {
1030
+ static {
1031
+ __name(this, "RemoveRecurrenceUseCase");
1032
+ }
1033
+ /** Apaga só a regra: os posts que ela já publicou continuam no ar. */
1034
+ async execute(params) {
1035
+ if (!await this.dependencies.recurrences.remove(params)) throw new RecurrenceNotFoundError(params.id);
1036
+ }
1037
+ };
1038
+
1039
+ // src/use-cases/Scheduling.use-cases.ts
1040
+ import { POST_EVENT as POST_EVENT3, POST_STATUS as POST_STATUS6, PostNotPublishedError, republishPostSchema, RepublishDateInFutureError, SLUG_MAX_LENGTH, slugify } from "@adatechnology/content-contracts";
1041
+
1042
+ // src/shared/recurrence.ts
1043
+ import { RECURRENCE_FREQUENCY } from "@adatechnology/content-contracts";
1044
+ var WEEK_MS = 7 * 24 * 60 * 60 * 1e3;
1045
+ function daysInMonth(year, monthIndex) {
1046
+ return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate();
1047
+ }
1048
+ __name(daysInMonth, "daysInMonth");
1049
+ function addMonths(from, anchorDay, months) {
1050
+ const target = new Date(Date.UTC(from.getUTCFullYear(), from.getUTCMonth() + months, 1));
1051
+ const day = Math.min(anchorDay, daysInMonth(target.getUTCFullYear(), target.getUTCMonth()));
1052
+ return new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth(), day, from.getUTCHours(), from.getUTCMinutes(), from.getUTCSeconds(), from.getUTCMilliseconds()));
1053
+ }
1054
+ __name(addMonths, "addMonths");
1055
+ function nextOccurrence(params) {
1056
+ if (params.frequency === RECURRENCE_FREQUENCY.WEEKLY) return new Date(params.from.getTime() + WEEK_MS);
1057
+ return addMonths(params.from, params.anchorDay, 1);
1058
+ }
1059
+ __name(nextOccurrence, "nextOccurrence");
1060
+ function nextOccurrenceAfter(params) {
1061
+ let candidate = nextOccurrence(params);
1062
+ while (candidate <= params.now) candidate = nextOccurrence({
1063
+ ...params,
1064
+ from: candidate
1065
+ });
1066
+ return candidate;
1067
+ }
1068
+ __name(nextOccurrenceAfter, "nextOccurrenceAfter");
1069
+ function toDateStamp(date) {
1070
+ return date.toISOString().slice(0, 10);
1071
+ }
1072
+ __name(toDateStamp, "toDateStamp");
1073
+
1074
+ // src/use-cases/Template.use-cases.ts
1075
+ import { createFromTemplateSchema, DuplicateSlugError as DuplicateSlugError2, normalizeTags as normalizeTags2, NotATemplateError as NotATemplateError2, POST_EVENT as POST_EVENT2, POST_STATUS as POST_STATUS5, saveAsTemplateSchema } from "@adatechnology/content-contracts";
1076
+ var TEMPLATE_SLUG_PREFIX = "modelo";
1077
+ function copiableFields(row) {
1078
+ return {
1079
+ excerpt: row.excerpt,
1080
+ body: row.body,
1081
+ coverImageUrl: row.coverImageUrl,
1082
+ coverImageAlt: row.coverImageAlt,
1083
+ tags: normalizeTags2(row.tags),
1084
+ tagLabels: row.tagLabels,
1085
+ authorName: row.authorName,
1086
+ seoTitle: row.seoTitle,
1087
+ seoDescription: row.seoDescription,
1088
+ readingTimeMinutes: row.readingTimeMinutes
1089
+ };
1090
+ }
1091
+ __name(copiableFields, "copiableFields");
1092
+ var TemplateUseCaseBase = class TemplateUseCaseBase2 extends PostUseCaseBase {
1093
+ static {
1094
+ __name(this, "TemplateUseCaseBase");
1095
+ }
1096
+ async insertCopy(params) {
1097
+ const row = await this.dependencies.posts.create({
1098
+ ...copiableFields(params.source),
1099
+ companyId: params.companyId,
1100
+ slug: params.slug,
1101
+ shortId: await this.generateShortId(params.companyId),
1102
+ title: params.title,
1103
+ isTemplate: params.isTemplate,
1104
+ status: params.status ?? POST_STATUS5.DRAFT,
1105
+ ...params.publishedAt ? {
1106
+ publishedAt: params.publishedAt
1107
+ } : {}
1108
+ }).catch((error) => {
1109
+ if (isUniqueViolation(error)) throw new DuplicateSlugError2(params.slug);
1110
+ throw error;
1111
+ });
1112
+ const post = toPost(row, this.now());
1113
+ await notifyPostChanged(this.dependencies, POST_EVENT2.CREATED, post);
1114
+ return post;
1115
+ }
1116
+ };
1117
+ var SaveAsTemplateUseCase = class extends TemplateUseCaseBase {
1118
+ static {
1119
+ __name(this, "SaveAsTemplateUseCase");
1120
+ }
1121
+ /** Copia o post (qualquer status) para um modelo. O original não muda. */
1122
+ async execute(params) {
1123
+ const input = saveAsTemplateSchema.parse(params.input ?? {});
1124
+ const source = await this.findOrFail(params);
1125
+ const title = input.title ?? source.title;
1126
+ const slug = await this.generateSlug(params.companyId, `${TEMPLATE_SLUG_PREFIX} ${title}`);
1127
+ return this.insertCopy({
1128
+ companyId: params.companyId,
1129
+ slug,
1130
+ title,
1131
+ source,
1132
+ isTemplate: true
1133
+ });
1134
+ }
1135
+ };
1136
+ var CreateFromTemplateUseCase = class extends TemplateUseCaseBase {
1137
+ static {
1138
+ __name(this, "CreateFromTemplateUseCase");
1139
+ }
1140
+ /** Cria um RASCUNHO novo com o conteúdo do modelo, pronto para editar e publicar. */
1141
+ async execute(params) {
1142
+ const input = createFromTemplateSchema.parse(params.input ?? {});
1143
+ const template = await this.findOrFail(params);
1144
+ if (!template.isTemplate) throw new NotATemplateError2(params.id);
1145
+ const title = input.title ?? template.title;
1146
+ if (input.slug) await this.assertSlugAvailable(params.companyId, input.slug);
1147
+ const slug = input.slug ?? await this.generateSlug(params.companyId, title);
1148
+ return this.insertCopy({
1149
+ companyId: params.companyId,
1150
+ slug,
1151
+ title,
1152
+ source: template,
1153
+ isTemplate: false
1154
+ });
1155
+ }
1156
+ };
1157
+ var CountPostsUseCase = class extends PostUseCaseBase {
1158
+ static {
1159
+ __name(this, "CountPostsUseCase");
1160
+ }
1161
+ /** Números das abas do painel, numa consulta só. */
1162
+ async execute(params) {
1163
+ return this.dependencies.posts.countByStatus({
1164
+ companyId: params.companyId,
1165
+ now: this.now()
1166
+ });
1167
+ }
1168
+ };
1169
+
1170
+ // src/use-cases/Scheduling.use-cases.ts
1171
+ var DEFAULT_BATCH_LIMIT = 100;
1172
+ var DATE_SUFFIX_LENGTH = 11;
1173
+ var FALLBACK_SLUG2 = "post";
1174
+ var RepublishPostUseCase = class extends PostUseCaseBase {
1175
+ static {
1176
+ __name(this, "RepublishPostUseCase");
1177
+ }
1178
+ /**
1179
+ * Muda a data de um post JÁ publicado, mantendo o MESMO endereço. É a opção segura para SEO: o
1180
+ * link antigo (compartilhado, indexado, com backlinks) continua valendo e não nasce conteúdo
1181
+ * duplicado. Data futura é recusada — o post sairia do ar até lá e o leitor veria 404.
1182
+ */
1183
+ async execute(params) {
1184
+ const input = republishPostSchema.parse(params.input ?? {});
1185
+ const existing = await this.findOrFail(params);
1186
+ const now = this.now();
1187
+ if (existing.isTemplate || effectiveStatus(existing, now) !== POST_STATUS6.PUBLISHED) {
1188
+ throw new PostNotPublishedError(params.id);
1189
+ }
1190
+ const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now;
1191
+ if (publishedAt > now) throw new RepublishDateInFutureError();
1192
+ return this.save(params, {
1193
+ status: POST_STATUS6.PUBLISHED,
1194
+ publishedAt
1195
+ }, POST_EVENT3.REPUBLISHED);
1196
+ }
1197
+ };
1198
+ var PublishDueUseCase = class extends PostUseCaseBase {
1199
+ static {
1200
+ __name(this, "PublishDueUseCase");
1201
+ }
1202
+ /**
1203
+ * Idempotente e seguro com várias instâncias chamando ao mesmo tempo: cada post/regra é reclamado
1204
+ * por uma só execução. Sem trabalho vencido, não faz nada. `now` existe para teste e reprocesso.
1205
+ */
1206
+ async execute(params = {}) {
1207
+ const now = params.now ?? this.now();
1208
+ const limit = params.limit ?? DEFAULT_BATCH_LIMIT;
1209
+ const materialized = await this.materializeRecurrences({
1210
+ now,
1211
+ limit
1212
+ });
1213
+ const rows = await this.dependencies.posts.claimDueScheduled({
1214
+ now,
1215
+ limit
1216
+ });
1217
+ for (const row of rows) {
1218
+ await notifyPostChanged(this.dependencies, POST_EVENT3.PUBLISHED, toPost(row, now));
1219
+ }
1220
+ if (rows.length > 0 || materialized > 0) {
1221
+ this.dependencies.logger?.info("content-module: publishDue", {
1222
+ published: rows.length,
1223
+ materialized
1224
+ });
1225
+ }
1226
+ return {
1227
+ published: rows.length,
1228
+ materialized
1229
+ };
1230
+ }
1231
+ materializeRecurrences(params) {
1232
+ return this.dependencies.recurrences.processDue({
1233
+ ...params,
1234
+ handle: /* @__PURE__ */ __name((rule) => this.materialize(rule, params.now), "handle")
1235
+ });
1236
+ }
1237
+ /** Um post publicado agora a partir do modelo; a regra avança para a próxima data futura. */
1238
+ async materialize(rule, now) {
1239
+ const advance = {
1240
+ nextRunAt: nextOccurrenceAfter({
1241
+ frequency: rule.frequency,
1242
+ from: rule.nextRunAt,
1243
+ anchorDay: rule.anchorDay,
1244
+ now
1245
+ })
1246
+ };
1247
+ const template = await this.dependencies.posts.findById({
1248
+ companyId: rule.companyId,
1249
+ id: rule.templateId
1250
+ });
1251
+ if (!template || !template.isTemplate || template.status === POST_STATUS6.ARCHIVED) {
1252
+ this.dependencies.logger?.warn("content-module: modelo da recorr\xEAncia indispon\xEDvel", {
1253
+ ruleId: rule.id
1254
+ });
1255
+ return {
1256
+ isActive: false
1257
+ };
1258
+ }
1259
+ const base = (slugify(template.title) || FALLBACK_SLUG2).slice(0, SLUG_MAX_LENGTH - DATE_SUFFIX_LENGTH);
1260
+ const slug = await this.uniqueSlug(rule.companyId, `${base.replace(/-+$/g, "")}-${toDateStamp(now)}`);
1261
+ const row = await this.dependencies.posts.create({
1262
+ ...copiableFields(template),
1263
+ companyId: rule.companyId,
1264
+ slug,
1265
+ shortId: await this.generateShortId(rule.companyId),
1266
+ title: template.title,
1267
+ isTemplate: false,
1268
+ status: POST_STATUS6.PUBLISHED,
1269
+ publishedAt: now
1270
+ });
1271
+ const post = toPost(row, now);
1272
+ await notifyPostChanged(this.dependencies, POST_EVENT3.CREATED, post);
1273
+ await notifyPostChanged(this.dependencies, POST_EVENT3.PUBLISHED, post);
1274
+ return {
1275
+ ...advance,
1276
+ lastRunAt: now,
1277
+ lastPostId: row.id
1278
+ };
1279
+ }
1280
+ };
1281
+
1282
+ // src/use-cases/UploadCoverImage.use-case.ts
1283
+ import { ImageStorageDisabledError, InvalidCoverImageError } from "@adatechnology/content-contracts";
1284
+
1285
+ // src/shared/coverImage.constant.ts
1286
+ var COVER_IMAGE = {
1287
+ MAX_BYTES: 1024 * 1024,
1288
+ KEY_PREFIX: "content/posts",
1289
+ EXTENSION_BY_MIME: {
1290
+ "image/jpeg": "jpg",
1291
+ "image/png": "png",
1292
+ "image/webp": "webp"
1293
+ }
1294
+ };
1295
+
1296
+ // src/use-cases/UploadCoverImage.use-case.ts
1297
+ var UploadCoverImageUseCase = class {
1298
+ static {
1299
+ __name(this, "UploadCoverImageUseCase");
1300
+ }
1301
+ dependencies;
1302
+ constructor(dependencies) {
1303
+ this.dependencies = dependencies;
1304
+ }
1305
+ async execute(params) {
1306
+ const storage = this.dependencies.imageStorage;
1307
+ if (!storage) throw new ImageStorageDisabledError();
1308
+ const mimeType = (params.mimeType.split(";")[0] ?? "").trim().toLowerCase();
1309
+ const extension = COVER_IMAGE.EXTENSION_BY_MIME[mimeType];
1310
+ if (!extension) throw new InvalidCoverImageError("unsupported_type");
1311
+ if (params.bytes.byteLength === 0) throw new InvalidCoverImageError("empty");
1312
+ if (params.bytes.byteLength > COVER_IMAGE.MAX_BYTES) throw new InvalidCoverImageError("too_large");
1313
+ const key = `${COVER_IMAGE.KEY_PREFIX}/${params.companyId}/${crypto.randomUUID()}.${extension}`;
1314
+ return storage.upload({
1315
+ buffer: params.bytes,
1316
+ mimeType,
1317
+ key
1318
+ });
1319
+ }
1320
+ };
1321
+
1322
+ // src/ContentModule.ts
1323
+ var SYSTEM_CLOCK = {
1324
+ now: /* @__PURE__ */ __name(() => /* @__PURE__ */ new Date(), "now")
1325
+ };
1326
+ function assertValidConfig(config) {
1327
+ if (config.feed && !/^https?:\/\/[^/]/i.test(config.feed.siteUrl)) throw new ConfigMissingError("feed.siteUrl");
1328
+ if (config.feed && !config.feed.title.trim()) throw new ConfigMissingError("feed.title");
1329
+ if (config.feed?.postPathTemplate && !config.feed.postPathTemplate.includes("{slug}")) {
1330
+ throw new ConfigMissingError("feed.postPathTemplate");
1331
+ }
1332
+ if (config.wordsPerMinute !== void 0 && !(config.wordsPerMinute > 0)) throw new ConfigMissingError("wordsPerMinute");
1333
+ }
1334
+ __name(assertValidConfig, "assertValidConfig");
1335
+ function createContentModule(params) {
1336
+ const config = params.config ?? {};
1337
+ assertValidConfig(config);
1338
+ const posts2 = params.providers?.postStore ?? (params.db ? new PostRepository(params.db) : void 0);
1339
+ if (!posts2) throw new ConfigMissingError("db");
1340
+ const recurrences = params.providers?.recurrenceStore ?? (params.db ? new RecurrenceRepository(params.db) : void 0);
1341
+ if (!recurrences) throw new ConfigMissingError("db");
1342
+ const dependencies = {
1343
+ posts: posts2,
1344
+ recurrences,
1345
+ config,
1346
+ clock: params.providers?.clock ?? SYSTEM_CLOCK,
1347
+ ...params.hooks ? {
1348
+ hooks: params.hooks
1349
+ } : {},
1350
+ ...params.providers?.imageStorage ? {
1351
+ imageStorage: params.providers.imageStorage
1352
+ } : {},
1353
+ ...params.providers?.logger ? {
1354
+ logger: params.providers.logger
1355
+ } : {}
1356
+ };
1357
+ return {
1358
+ useCases: {
1359
+ createPost: new CreatePostUseCase(dependencies),
1360
+ updatePost: new UpdatePostUseCase(dependencies),
1361
+ archivePost: new ArchivePostUseCase(dependencies),
1362
+ publishPost: new PublishPostUseCase(dependencies),
1363
+ unpublishPost: new UnpublishPostUseCase(dependencies),
1364
+ getPost: new GetPostUseCase(dependencies),
1365
+ listPosts: new ListPostsUseCase(dependencies),
1366
+ getPublishedPostBySlug: new GetPublishedPostBySlugUseCase(dependencies),
1367
+ listPublishedPosts: new ListPublishedPostsUseCase(dependencies),
1368
+ listTags: new ListTagsUseCase(dependencies),
1369
+ countPosts: new CountPostsUseCase(dependencies),
1370
+ saveAsTemplate: new SaveAsTemplateUseCase(dependencies),
1371
+ createFromTemplate: new CreateFromTemplateUseCase(dependencies),
1372
+ republishPost: new RepublishPostUseCase(dependencies),
1373
+ createRecurrence: new CreateRecurrenceUseCase(dependencies),
1374
+ listRecurrences: new ListRecurrencesUseCase(dependencies),
1375
+ updateRecurrence: new UpdateRecurrenceUseCase(dependencies),
1376
+ removeRecurrence: new RemoveRecurrenceUseCase(dependencies),
1377
+ publishDue: new PublishDueUseCase(dependencies),
1378
+ ...dependencies.imageStorage ? {
1379
+ uploadCoverImage: new UploadCoverImageUseCase(dependencies)
1380
+ } : {},
1381
+ ...config.feed ? {
1382
+ buildFeed: new BuildFeedUseCase(dependencies, config.feed),
1383
+ listSitemapEntries: new ListSitemapEntriesUseCase(dependencies, config.feed)
1384
+ } : {}
1385
+ },
1386
+ config
1387
+ };
1388
+ }
1389
+ __name(createContentModule, "createContentModule");
1390
+
1391
+ // src/http/adminRoutes.ts
1392
+ import { createFromTemplateSchema as createFromTemplateSchema2, createPostSchema as createPostSchema2, createRecurrenceSchema as createRecurrenceSchema2, DEFAULT_ADMIN_SCOPES, listPostsQuerySchema as listPostsQuerySchema2, publishPostSchema as publishPostSchema2, republishPostSchema as republishPostSchema2, saveAsTemplateSchema as saveAsTemplateSchema2, updatePostSchema as updatePostSchema2, updateRecurrenceSchema as updateRecurrenceSchema2 } from "@adatechnology/content-contracts";
1393
+
1394
+ // src/http/requireCompany.ts
1395
+ import { CONTENT_ERROR_CODES, ContentError } from "@adatechnology/content-contracts";
1396
+ function requireCompany(context) {
1397
+ if (!context.auth?.companyId) {
1398
+ throw new ContentError("Rota exige contexto autenticado.", 401, CONTENT_ERROR_CODES.CONFIG_MISSING);
1399
+ }
1400
+ return context.auth.companyId;
1401
+ }
1402
+ __name(requireCompany, "requireCompany");
1403
+
1404
+ // src/http/adminRoutes.ts
1405
+ function reference(context) {
1406
+ return {
1407
+ companyId: requireCompany(context),
1408
+ id: context.params.id ?? ""
1409
+ };
1410
+ }
1411
+ __name(reference, "reference");
1412
+ var json = /* @__PURE__ */ __name((status, data) => ({
1413
+ kind: "json",
1414
+ status,
1415
+ body: {
1416
+ data
1417
+ }
1418
+ }), "json");
1419
+ function buildAdminRoutes(module) {
1420
+ const { useCases } = module;
1421
+ const requiredScopes = module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES;
1422
+ const admin = {
1423
+ scope: "admin",
1424
+ requiredScopes
1425
+ };
1426
+ const uploadRoutes = useCases.uploadCoverImage ? [
1427
+ {
1428
+ ...admin,
1429
+ method: "POST",
1430
+ path: "/posts/cover-images",
1431
+ operationId: "uploadPostCoverImage",
1432
+ summary: "Envia a imagem de capa (bytes crus, Content-Type jpeg/png/webp) e devolve a URL",
1433
+ async handler(context) {
1434
+ const upload = useCases.uploadCoverImage;
1435
+ if (!upload) return {
1436
+ kind: "empty",
1437
+ status: 404
1438
+ };
1439
+ const result = await upload.execute({
1440
+ companyId: requireCompany(context),
1441
+ bytes: context.rawBody ?? new Uint8Array(),
1442
+ mimeType: context.headers["content-type"] ?? ""
1443
+ });
1444
+ return json(201, result);
1445
+ }
1446
+ }
1447
+ ] : [];
1448
+ return [
1449
+ {
1450
+ ...admin,
1451
+ method: "GET",
1452
+ path: "/posts",
1453
+ querySchema: listPostsQuerySchema2,
1454
+ operationId: "listPosts",
1455
+ summary: "Lista posts da empresa (todos os status), com filtro por status, tag e busca",
1456
+ async handler(context) {
1457
+ const result = await useCases.listPosts.execute({
1458
+ companyId: requireCompany(context),
1459
+ ...context.query
1460
+ });
1461
+ return {
1462
+ kind: "json",
1463
+ status: 200,
1464
+ body: result
1465
+ };
1466
+ }
1467
+ },
1468
+ {
1469
+ ...admin,
1470
+ method: "POST",
1471
+ path: "/posts",
1472
+ bodySchema: createPostSchema2,
1473
+ operationId: "createPost",
1474
+ summary: "Cria um post como rascunho; sem slug, gera a partir do t\xEDtulo",
1475
+ async handler(context) {
1476
+ const post = await useCases.createPost.execute({
1477
+ companyId: requireCompany(context),
1478
+ input: context.body
1479
+ });
1480
+ return json(201, post);
1481
+ }
1482
+ },
1483
+ // Antes de `/posts/:id`: `findRoute` para na primeira rota que casa, e `:id` casaria "tags".
1484
+ {
1485
+ ...admin,
1486
+ method: "GET",
1487
+ path: "/posts/tags",
1488
+ operationId: "listPostTags",
1489
+ summary: "Tags usadas em qualquer post da empresa, com contagem",
1490
+ async handler(context) {
1491
+ return json(200, await useCases.listTags.execute({
1492
+ companyId: requireCompany(context),
1493
+ scope: TAG_SCOPE.ADMIN
1494
+ }));
1495
+ }
1496
+ },
1497
+ {
1498
+ ...admin,
1499
+ method: "GET",
1500
+ path: "/posts/counts",
1501
+ operationId: "countPosts",
1502
+ summary: "Contagem de posts por aba: publicados, agendados, rascunhos, arquivados e modelos",
1503
+ async handler(context) {
1504
+ return json(200, await useCases.countPosts.execute({
1505
+ companyId: requireCompany(context)
1506
+ }));
1507
+ }
1508
+ },
1509
+ ...recurrenceRoutes(module),
1510
+ ...uploadRoutes,
1511
+ {
1512
+ ...admin,
1513
+ method: "GET",
1514
+ path: "/posts/:id",
1515
+ operationId: "getPost",
1516
+ summary: "L\xEA um post da empresa (qualquer status)",
1517
+ async handler(context) {
1518
+ return json(200, await useCases.getPost.execute(reference(context)));
1519
+ }
1520
+ },
1521
+ {
1522
+ ...admin,
1523
+ method: "PATCH",
1524
+ path: "/posts/:id",
1525
+ bodySchema: updatePostSchema2,
1526
+ operationId: "updatePost",
1527
+ summary: "Atualiza campos de um post; trocar o t\xEDtulo n\xE3o troca o slug",
1528
+ async handler(context) {
1529
+ return json(200, await useCases.updatePost.execute({
1530
+ ...reference(context),
1531
+ input: context.body
1532
+ }));
1533
+ }
1534
+ },
1535
+ {
1536
+ ...admin,
1537
+ method: "DELETE",
1538
+ path: "/posts/:id",
1539
+ operationId: "archivePost",
1540
+ summary: "Arquiva o post: sai do site, conte\xFAdo e slug continuam guardados",
1541
+ async handler(context) {
1542
+ await useCases.archivePost.execute(reference(context));
1543
+ return {
1544
+ kind: "empty",
1545
+ status: 204
1546
+ };
1547
+ }
1548
+ },
1549
+ {
1550
+ ...admin,
1551
+ method: "POST",
1552
+ path: "/posts/:id/publish",
1553
+ // Opcional: `POST /publish` sem corpo publica agora.
1554
+ bodySchema: publishPostSchema2.optional(),
1555
+ operationId: "publishPost",
1556
+ summary: "Publica agora, ou agenda quando `publishedAt` \xE9 futuro",
1557
+ async handler(context) {
1558
+ return json(200, await useCases.publishPost.execute({
1559
+ ...reference(context),
1560
+ input: context.body ?? {}
1561
+ }));
1562
+ }
1563
+ },
1564
+ {
1565
+ ...admin,
1566
+ method: "POST",
1567
+ path: "/posts/:id/unpublish",
1568
+ operationId: "unpublishPost",
1569
+ summary: "Tira do ar (ou cancela o agendamento) e volta a rascunho",
1570
+ async handler(context) {
1571
+ return json(200, await useCases.unpublishPost.execute(reference(context)));
1572
+ }
1573
+ },
1574
+ {
1575
+ ...admin,
1576
+ method: "POST",
1577
+ path: "/posts/:id/republish",
1578
+ bodySchema: republishPostSchema2.optional(),
1579
+ operationId: "republishPost",
1580
+ summary: "Republica um post no ar com nova data, mantendo o mesmo endere\xE7o (SEO); data futura \xE9 recusada",
1581
+ async handler(context) {
1582
+ return json(200, await useCases.republishPost.execute({
1583
+ ...reference(context),
1584
+ input: context.body ?? {}
1585
+ }));
1586
+ }
1587
+ },
1588
+ {
1589
+ ...admin,
1590
+ method: "POST",
1591
+ path: "/posts/:id/save-as-template",
1592
+ bodySchema: saveAsTemplateSchema2.optional(),
1593
+ operationId: "savePostAsTemplate",
1594
+ summary: "Copia o post para um modelo (o original n\xE3o muda)",
1595
+ async handler(context) {
1596
+ return json(201, await useCases.saveAsTemplate.execute({
1597
+ ...reference(context),
1598
+ input: context.body ?? {}
1599
+ }));
1600
+ }
1601
+ },
1602
+ {
1603
+ ...admin,
1604
+ method: "POST",
1605
+ path: "/posts/:id/from-template",
1606
+ bodySchema: createFromTemplateSchema2.optional(),
1607
+ operationId: "createPostFromTemplate",
1608
+ summary: "Cria um rascunho novo a partir do modelo `:id`",
1609
+ async handler(context) {
1610
+ return json(201, await useCases.createFromTemplate.execute({
1611
+ ...reference(context),
1612
+ input: context.body ?? {}
1613
+ }));
1614
+ }
1615
+ }
1616
+ ];
1617
+ }
1618
+ __name(buildAdminRoutes, "buildAdminRoutes");
1619
+ function recurrenceRoutes(module) {
1620
+ const { useCases } = module;
1621
+ const admin = {
1622
+ scope: "admin",
1623
+ requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES
1624
+ };
1625
+ return [
1626
+ {
1627
+ ...admin,
1628
+ method: "GET",
1629
+ path: "/recurrences",
1630
+ operationId: "listRecurrences",
1631
+ summary: "Regras de recorr\xEAncia da empresa",
1632
+ async handler(context) {
1633
+ return json(200, await useCases.listRecurrences.execute({
1634
+ companyId: requireCompany(context)
1635
+ }));
1636
+ }
1637
+ },
1638
+ {
1639
+ ...admin,
1640
+ method: "POST",
1641
+ path: "/recurrences",
1642
+ bodySchema: createRecurrenceSchema2,
1643
+ operationId: "createRecurrence",
1644
+ summary: "Cria regra: publica um post novo, copiado do modelo, toda semana ou todo m\xEAs",
1645
+ async handler(context) {
1646
+ return json(201, await useCases.createRecurrence.execute({
1647
+ companyId: requireCompany(context),
1648
+ input: context.body
1649
+ }));
1650
+ }
1651
+ },
1652
+ {
1653
+ ...admin,
1654
+ method: "PATCH",
1655
+ path: "/recurrences/:id",
1656
+ bodySchema: updateRecurrenceSchema2,
1657
+ operationId: "updateRecurrence",
1658
+ summary: "Pausa, retoma ou remarca a pr\xF3xima execu\xE7\xE3o",
1659
+ async handler(context) {
1660
+ return json(200, await useCases.updateRecurrence.execute({
1661
+ ...reference(context),
1662
+ input: context.body
1663
+ }));
1664
+ }
1665
+ },
1666
+ {
1667
+ ...admin,
1668
+ method: "DELETE",
1669
+ path: "/recurrences/:id",
1670
+ operationId: "removeRecurrence",
1671
+ summary: "Apaga a regra; os posts j\xE1 publicados por ela continuam no ar",
1672
+ async handler(context) {
1673
+ await useCases.removeRecurrence.execute(reference(context));
1674
+ return {
1675
+ kind: "empty",
1676
+ status: 204
1677
+ };
1678
+ }
1679
+ }
1680
+ ];
1681
+ }
1682
+ __name(recurrenceRoutes, "recurrenceRoutes");
1683
+
1684
+ // src/http/publicRoutes.ts
1685
+ import { DEFAULT_PUBLIC_CACHE_CONTROL, listPublishedPostsQuerySchema as listPublishedPostsQuerySchema2, PostNotFoundError as PostNotFoundError4 } from "@adatechnology/content-contracts";
1686
+ var PUBLIC = {
1687
+ scope: "public"
1688
+ };
1689
+ function buildPublicRoutes(params) {
1690
+ const { useCases } = params.module;
1691
+ const cacheControl = params.module.config.publicCacheControl ?? DEFAULT_PUBLIC_CACHE_CONTROL;
1692
+ const cached = /* @__PURE__ */ __name((data) => ({
1693
+ kind: "json",
1694
+ status: 200,
1695
+ body: data,
1696
+ headers: {
1697
+ "Cache-Control": cacheControl
1698
+ }
1699
+ }), "cached");
1700
+ async function resolveCompany(context) {
1701
+ const companyId = await params.companyResolver.resolve({
1702
+ headers: context.headers,
1703
+ query: context.query
1704
+ });
1705
+ if (!companyId) throw new PostNotFoundError4("company");
1706
+ return companyId;
1707
+ }
1708
+ __name(resolveCompany, "resolveCompany");
1709
+ const routes = [
1710
+ {
1711
+ ...PUBLIC,
1712
+ method: "GET",
1713
+ path: "/public/posts",
1714
+ querySchema: listPublishedPostsQuerySchema2,
1715
+ operationId: "listPublishedPosts",
1716
+ summary: "Posts publicados, mais recentes primeiro, com filtro por tag",
1717
+ async handler(context) {
1718
+ const result = await useCases.listPublishedPosts.execute({
1719
+ companyId: await resolveCompany(context),
1720
+ ...context.query
1721
+ });
1722
+ return cached(result);
1723
+ }
1724
+ },
1725
+ {
1726
+ ...PUBLIC,
1727
+ method: "GET",
1728
+ path: "/public/posts/:slug",
1729
+ operationId: "getPublishedPost",
1730
+ summary: "Post publicado pelo slug; rascunho, agendado futuro e arquivado respondem 404",
1731
+ async handler(context) {
1732
+ const post = await useCases.getPublishedPostBySlug.execute({
1733
+ companyId: await resolveCompany(context),
1734
+ slug: context.params.slug ?? ""
1735
+ });
1736
+ return cached({
1737
+ data: post
1738
+ });
1739
+ }
1740
+ },
1741
+ {
1742
+ ...PUBLIC,
1743
+ method: "GET",
1744
+ path: "/public/tags",
1745
+ operationId: "listPublishedTags",
1746
+ summary: "Tags dos posts publicados, com contagem",
1747
+ async handler(context) {
1748
+ const tags = await useCases.listTags.execute({
1749
+ companyId: await resolveCompany(context),
1750
+ scope: TAG_SCOPE.PUBLIC
1751
+ });
1752
+ return cached({
1753
+ data: tags
1754
+ });
1755
+ }
1756
+ }
1757
+ ];
1758
+ const { buildFeed, listSitemapEntries } = useCases;
1759
+ if (!buildFeed || !listSitemapEntries) return routes;
1760
+ const feedRoute = /* @__PURE__ */ __name((path2, format, contentType, operationId) => ({
1761
+ ...PUBLIC,
1762
+ method: "GET",
1763
+ path: path2,
1764
+ operationId,
1765
+ summary: `Feed ${format.toUpperCase()} dos posts publicados`,
1766
+ async handler(context) {
1767
+ const body = await buildFeed.execute({
1768
+ companyId: await resolveCompany(context),
1769
+ format
1770
+ });
1771
+ return {
1772
+ kind: "text",
1773
+ status: 200,
1774
+ body,
1775
+ headers: {
1776
+ "Content-Type": contentType,
1777
+ "Cache-Control": cacheControl
1778
+ }
1779
+ };
1780
+ }
1781
+ }), "feedRoute");
1782
+ return [
1783
+ ...routes,
1784
+ feedRoute("/public/feed.xml", FEED_FORMAT.RSS, "application/rss+xml; charset=utf-8", "getRssFeed"),
1785
+ feedRoute("/public/atom.xml", FEED_FORMAT.ATOM, "application/atom+xml; charset=utf-8", "getAtomFeed"),
1786
+ {
1787
+ ...PUBLIC,
1788
+ method: "GET",
1789
+ path: "/public/sitemap-entries",
1790
+ operationId: "listSitemapEntries",
1791
+ summary: "Entradas de sitemap (loc, lastmod) dos posts publicados, para o host juntar ao sitemap dele",
1792
+ async handler(context) {
1793
+ return cached({
1794
+ data: await listSitemapEntries.execute({
1795
+ companyId: await resolveCompany(context)
1796
+ })
1797
+ });
1798
+ }
1799
+ }
1800
+ ];
1801
+ }
1802
+ __name(buildPublicRoutes, "buildPublicRoutes");
1803
+
1804
+ // src/http/routes.ts
1805
+ function createContentRoutes(params) {
1806
+ const admin = buildAdminRoutes(params.module);
1807
+ if (!params.publicCompanyResolver) return admin;
1808
+ return [
1809
+ ...admin,
1810
+ ...buildPublicRoutes({
1811
+ module: params.module,
1812
+ companyResolver: params.publicCompanyResolver
1813
+ })
1814
+ ];
1815
+ }
1816
+ __name(createContentRoutes, "createContentRoutes");
1817
+
1818
+ // src/runMigrations.ts
1819
+ import { join } from "path";
1820
+ var CONTENT_MIGRATIONS_TABLE = "content_migrations";
1821
+ function contentMigrationsFolder() {
1822
+ return join(__dirname, "migrations");
1823
+ }
1824
+ __name(contentMigrationsFolder, "contentMigrationsFolder");
1825
+ async function runContentMigrations(params) {
1826
+ await params.migrate(params.db, {
1827
+ migrationsFolder: contentMigrationsFolder(),
1828
+ migrationsTable: CONTENT_MIGRATIONS_TABLE
1829
+ });
1830
+ }
1831
+ __name(runContentMigrations, "runContentMigrations");
1832
+
1833
+ // src/testing/inMemoryPostStore.ts
1834
+ import { randomUUID } from "crypto";
1835
+ import { POST_STATUS as POST_STATUS7 } from "@adatechnology/content-contracts";
1836
+ function isPublic(row, now) {
1837
+ const live = row.status === POST_STATUS7.PUBLISHED || row.status === POST_STATUS7.SCHEDULED;
1838
+ return live && row.publishedAt !== null && row.publishedAt <= now;
1839
+ }
1840
+ __name(isPublic, "isPublic");
1841
+ function adminComparator(query) {
1842
+ const sign = query.order === "asc" ? 1 : -1;
1843
+ const value = /* @__PURE__ */ __name((row) => {
1844
+ if (query.sort === "title") return row.title.toLowerCase();
1845
+ if (query.sort === "status") return row.status;
1846
+ if (query.sort === "publishedAt") return row.publishedAt?.getTime() ?? sign * Number.POSITIVE_INFINITY;
1847
+ return row.updatedAt.getTime();
1848
+ }, "value");
1849
+ return (left, right) => {
1850
+ const a = value(left);
1851
+ const b = value(right);
1852
+ return (a < b ? -1 : a > b ? 1 : 0) * sign || left.id.localeCompare(right.id);
1853
+ };
1854
+ }
1855
+ __name(adminComparator, "adminComparator");
1856
+ function paginate(rows, page, pageSize) {
1857
+ return {
1858
+ rows: rows.slice((page - 1) * pageSize, page * pageSize).map((row) => ({
1859
+ ...row
1860
+ })),
1861
+ total: rows.length
1862
+ };
1863
+ }
1864
+ __name(paginate, "paginate");
1865
+ var UniqueViolation = class UniqueViolation2 extends Error {
1866
+ static {
1867
+ __name(this, "UniqueViolation");
1868
+ }
1869
+ code = "23505";
1870
+ };
1871
+ function createInMemoryPostStore(seed = []) {
1872
+ const rows = [
1873
+ ...seed
1874
+ ];
1875
+ const formerSlugs = [];
1876
+ const assertUniqueSlug = /* @__PURE__ */ __name((companyId, slug, ownId) => {
1877
+ if (rows.some((row) => row.companyId === companyId && row.slug === slug && row.id !== ownId)) {
1878
+ throw new UniqueViolation('duplicate key value violates unique constraint "idx_posts_company_slug"');
1879
+ }
1880
+ }, "assertUniqueSlug");
1881
+ return {
1882
+ rows,
1883
+ async findByShortId({ companyId, shortId }) {
1884
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.shortId === shortId);
1885
+ return row ? {
1886
+ ...row
1887
+ } : void 0;
1888
+ },
1889
+ async findPublicByShortId({ companyId, shortId, now }) {
1890
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.shortId === shortId && isPublic(candidate, now));
1891
+ return row ? {
1892
+ ...row
1893
+ } : void 0;
1894
+ },
1895
+ async findPublicByFormerSlug({ companyId, slug, now }) {
1896
+ const former = formerSlugs.find((entry) => entry.companyId === companyId && entry.slug === slug);
1897
+ const row = rows.find((candidate) => candidate.id === former?.postId && isPublic(candidate, now));
1898
+ return row ? {
1899
+ ...row
1900
+ } : void 0;
1901
+ },
1902
+ async recordFormerSlug(params) {
1903
+ if (!formerSlugs.some((entry) => entry.companyId === params.companyId && entry.slug === params.slug)) {
1904
+ formerSlugs.push({
1905
+ ...params
1906
+ });
1907
+ }
1908
+ },
1909
+ async create(values) {
1910
+ assertUniqueSlug(values.companyId, values.slug);
1911
+ const now = /* @__PURE__ */ new Date();
1912
+ const row = {
1913
+ id: randomUUID(),
1914
+ excerpt: null,
1915
+ body: "",
1916
+ coverImageUrl: null,
1917
+ coverImageAlt: null,
1918
+ tags: [],
1919
+ tagLabels: {},
1920
+ status: POST_STATUS7.DRAFT,
1921
+ isTemplate: false,
1922
+ publishedAt: null,
1923
+ authorName: null,
1924
+ seoTitle: null,
1925
+ seoDescription: null,
1926
+ canonicalUrl: null,
1927
+ readingTimeMinutes: 1,
1928
+ createdAt: now,
1929
+ updatedAt: now,
1930
+ ...values
1931
+ };
1932
+ rows.push(row);
1933
+ return {
1934
+ ...row
1935
+ };
1936
+ },
1937
+ async findById({ companyId, id }) {
1938
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id);
1939
+ return row ? {
1940
+ ...row
1941
+ } : void 0;
1942
+ },
1943
+ async findBySlug({ companyId, slug }) {
1944
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.slug === slug);
1945
+ return row ? {
1946
+ ...row
1947
+ } : void 0;
1948
+ },
1949
+ async findPublicBySlug({ companyId, slug, now }) {
1950
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.slug === slug && isPublic(candidate, now));
1951
+ return row ? {
1952
+ ...row
1953
+ } : void 0;
1954
+ },
1955
+ async update({ companyId, id, values }) {
1956
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id);
1957
+ if (!row) return void 0;
1958
+ if (values.slug !== void 0) assertUniqueSlug(companyId, values.slug, id);
1959
+ Object.assign(row, values, {
1960
+ updatedAt: new Date(Math.max(Date.now(), row.updatedAt.getTime() + 1))
1961
+ });
1962
+ return {
1963
+ ...row
1964
+ };
1965
+ },
1966
+ async listForAdmin(query) {
1967
+ const search = query.search?.toLowerCase();
1968
+ const matched = rows.filter((row) => row.companyId === query.companyId).filter((row) => query.isTemplate ? row.isTemplate && row.status !== POST_STATUS7.ARCHIVED : !row.isTemplate).filter((row) => !query.status || effectiveStatus(row, query.now) === query.status).filter((row) => !query.tags?.length || query.tags.some((tag) => row.tags.includes(tag))).filter((row) => !search || row.title.toLowerCase().includes(search) || row.slug.includes(search)).sort(adminComparator(query));
1969
+ return paginate(matched, query.page, query.pageSize);
1970
+ },
1971
+ async countByStatus({ companyId, now }) {
1972
+ const counts = {
1973
+ published: 0,
1974
+ scheduled: 0,
1975
+ draft: 0,
1976
+ archived: 0,
1977
+ templates: 0
1978
+ };
1979
+ for (const row of rows) {
1980
+ if (row.companyId !== companyId) continue;
1981
+ if (row.isTemplate) {
1982
+ if (row.status !== POST_STATUS7.ARCHIVED) counts.templates += 1;
1983
+ continue;
1984
+ }
1985
+ counts[effectiveStatus(row, now)] += 1;
1986
+ }
1987
+ return counts;
1988
+ },
1989
+ async claimDueScheduled({ now, limit }) {
1990
+ const due = rows.filter((row) => row.status === POST_STATUS7.SCHEDULED && !row.isTemplate && row.publishedAt && row.publishedAt <= now).sort((left, right) => (left.publishedAt?.getTime() ?? 0) - (right.publishedAt?.getTime() ?? 0)).slice(0, limit);
1991
+ for (const row of due) row.status = POST_STATUS7.PUBLISHED;
1992
+ return due.map((row) => ({
1993
+ ...row
1994
+ }));
1995
+ },
1996
+ async listPublic(query) {
1997
+ const matched = rows.filter((row) => row.companyId === query.companyId && isPublic(row, query.now)).filter((row) => !query.tag || row.tags.includes(query.tag)).sort((left, right) => (right.publishedAt?.getTime() ?? 0) - (left.publishedAt?.getTime() ?? 0));
1998
+ return paginate(matched, query.page, query.pageSize);
1999
+ },
2000
+ async listTags({ companyId, publicAt }) {
2001
+ const counts = /* @__PURE__ */ new Map();
2002
+ for (const row of rows) {
2003
+ if (row.companyId !== companyId || publicAt && !isPublic(row, publicAt)) continue;
2004
+ for (const tag of row.tags) counts.set(tag, (counts.get(tag) ?? 0) + 1);
2005
+ }
2006
+ return [
2007
+ ...counts.entries()
2008
+ ].map(([tag, count]) => ({
2009
+ tag,
2010
+ count
2011
+ })).sort((left, right) => right.count - left.count || left.tag.localeCompare(right.tag));
2012
+ }
2013
+ };
2014
+ }
2015
+ __name(createInMemoryPostStore, "createInMemoryPostStore");
2016
+
2017
+ // src/scheduler.ts
2018
+ var DEFAULT_SCHEDULER_INTERVAL_MS = 6e4;
2019
+ function startContentScheduler(params) {
2020
+ let isRunning = false;
2021
+ const tick = /* @__PURE__ */ __name(async () => {
2022
+ if (isRunning) return;
2023
+ isRunning = true;
2024
+ try {
2025
+ await params.module.useCases.publishDue.execute();
2026
+ } catch (error) {
2027
+ params.logger?.error("content-module: ciclo do agendador falhou", {
2028
+ error: error instanceof Error ? error.message : String(error)
2029
+ });
2030
+ } finally {
2031
+ isRunning = false;
2032
+ }
2033
+ }, "tick");
2034
+ const timer = setInterval(() => void tick(), params.intervalMs ?? DEFAULT_SCHEDULER_INTERVAL_MS);
2035
+ timer.unref?.();
2036
+ void tick();
2037
+ return () => clearInterval(timer);
2038
+ }
2039
+ __name(startContentScheduler, "startContentScheduler");
2040
+
2041
+ // src/testing/inMemoryRecurrenceStore.ts
2042
+ import { randomUUID as randomUUID2 } from "crypto";
2043
+ function createInMemoryRecurrenceStore() {
2044
+ const rows = [];
2045
+ const owned = /* @__PURE__ */ __name((companyId, id) => rows.find((row) => row.companyId === companyId && row.id === id), "owned");
2046
+ return {
2047
+ rows,
2048
+ async create(values) {
2049
+ const row = {
2050
+ id: randomUUID2(),
2051
+ isActive: true,
2052
+ lastRunAt: null,
2053
+ lastPostId: null,
2054
+ createdAt: /* @__PURE__ */ new Date(),
2055
+ ...values
2056
+ };
2057
+ rows.push(row);
2058
+ return {
2059
+ ...row
2060
+ };
2061
+ },
2062
+ async findById({ companyId, id }) {
2063
+ const row = owned(companyId, id);
2064
+ return row ? {
2065
+ ...row
2066
+ } : void 0;
2067
+ },
2068
+ async list({ companyId }) {
2069
+ return rows.filter((row) => row.companyId === companyId).sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime()).map((row) => ({
2070
+ ...row
2071
+ }));
2072
+ },
2073
+ async update({ companyId, id, values }) {
2074
+ const row = owned(companyId, id);
2075
+ if (!row) return void 0;
2076
+ Object.assign(row, values);
2077
+ return {
2078
+ ...row
2079
+ };
2080
+ },
2081
+ async remove({ companyId, id }) {
2082
+ const index2 = rows.findIndex((row) => row.companyId === companyId && row.id === id);
2083
+ if (index2 < 0) return false;
2084
+ rows.splice(index2, 1);
2085
+ return true;
2086
+ },
2087
+ async processDue({ now, limit, handle }) {
2088
+ const due = rows.filter((row) => row.isActive && row.nextRunAt <= now).sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime()).slice(0, limit);
2089
+ for (const row of due) Object.assign(row, await handle({
2090
+ ...row
2091
+ }));
2092
+ return due.length;
2093
+ }
2094
+ };
2095
+ }
2096
+ __name(createInMemoryRecurrenceStore, "createInMemoryRecurrenceStore");
2097
+ export {
2098
+ ArchivePostUseCase,
2099
+ BuildFeedUseCase,
2100
+ CONTENT_MIGRATIONS_TABLE,
2101
+ COVER_IMAGE,
2102
+ CountPostsUseCase,
2103
+ CreateFromTemplateUseCase,
2104
+ CreatePostUseCase,
2105
+ CreateRecurrenceUseCase,
2106
+ DEFAULT_SCHEDULER_INTERVAL_MS,
2107
+ FEED_FORMAT,
2108
+ GetPostUseCase,
2109
+ GetPublishedPostBySlugUseCase,
2110
+ ListPostsUseCase,
2111
+ ListPublishedPostsUseCase,
2112
+ ListRecurrencesUseCase,
2113
+ ListSitemapEntriesUseCase,
2114
+ ListTagsUseCase,
2115
+ PostRepository,
2116
+ PublishDueUseCase,
2117
+ PublishPostUseCase,
2118
+ RecurrenceRepository,
2119
+ RemoveRecurrenceUseCase,
2120
+ RepublishPostUseCase,
2121
+ SaveAsTemplateUseCase,
2122
+ TAG_SCOPE,
2123
+ UnpublishPostUseCase,
2124
+ UpdatePostUseCase,
2125
+ UpdateRecurrenceUseCase,
2126
+ UploadCoverImageUseCase,
2127
+ contentMigrationsFolder,
2128
+ contentSchema,
2129
+ createContentModule,
2130
+ createContentRoutes,
2131
+ createInMemoryPostStore,
2132
+ createInMemoryRecurrenceStore,
2133
+ nextOccurrence,
2134
+ nextOccurrenceAfter,
2135
+ posts,
2136
+ recurrenceRules,
2137
+ runContentMigrations,
2138
+ startContentScheduler
2139
+ };
2140
+ //# sourceMappingURL=index.js.map