@adatechnology/content-module 0.0.0-stage → 0.1.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 +101 -2
- package/dist/http/fetch.cjs +33 -0
- package/dist/http/fetch.cjs.map +1 -0
- package/dist/http/fetch.d.cts +2 -0
- package/dist/http/fetch.d.ts +2 -0
- package/dist/http/fetch.js +7 -0
- package/dist/http/fetch.js.map +1 -0
- package/dist/http/uws.cjs +31 -0
- package/dist/http/uws.cjs.map +1 -0
- package/dist/http/uws.d.cts +1 -0
- package/dist/http/uws.d.ts +1 -0
- package/dist/http/uws.js +6 -0
- package/dist/http/uws.js.map +1 -0
- package/dist/index.cjs +1291 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +743 -0
- package/dist/index.d.ts +743 -0
- package/dist/index.js +1249 -0
- package/dist/index.js.map +1 -0
- package/dist/migrations/0000_posts.sql +26 -0
- package/dist/migrations/meta/0000_snapshot.json +213 -0
- package/dist/migrations/meta/_journal.json +13 -0
- package/dist/openapi.cjs +41 -0
- package/dist/openapi.cjs.map +1 -0
- package/dist/openapi.d.cts +15 -0
- package/dist/openapi.d.ts +15 -0
- package/dist/openapi.js +18 -0
- package/dist/openapi.js.map +1 -0
- package/package.json +55 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1249 @@
|
|
|
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 { asc, desc, sql as sql2 } from "drizzle-orm";
|
|
16
|
+
|
|
17
|
+
// src/schema/schema.ts
|
|
18
|
+
import { index, integer, pgSchema, text, timestamp, uniqueIndex, uuid, varchar } from "drizzle-orm/pg-core";
|
|
19
|
+
var contentSchema = pgSchema("content");
|
|
20
|
+
var posts = contentSchema.table("posts", {
|
|
21
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
22
|
+
companyId: uuid("company_id").notNull(),
|
|
23
|
+
slug: varchar("slug", {
|
|
24
|
+
length: 120
|
|
25
|
+
}).notNull(),
|
|
26
|
+
title: varchar("title", {
|
|
27
|
+
length: 200
|
|
28
|
+
}).notNull(),
|
|
29
|
+
excerpt: varchar("excerpt", {
|
|
30
|
+
length: 500
|
|
31
|
+
}),
|
|
32
|
+
body: text("body").notNull().default(""),
|
|
33
|
+
coverImageUrl: varchar("cover_image_url", {
|
|
34
|
+
length: 2048
|
|
35
|
+
}),
|
|
36
|
+
coverImageAlt: varchar("cover_image_alt", {
|
|
37
|
+
length: 300
|
|
38
|
+
}),
|
|
39
|
+
tags: text("tags").array().notNull().default([]),
|
|
40
|
+
status: varchar("status", {
|
|
41
|
+
length: 12
|
|
42
|
+
}).notNull().default("draft"),
|
|
43
|
+
publishedAt: timestamp("published_at", {
|
|
44
|
+
withTimezone: true
|
|
45
|
+
}),
|
|
46
|
+
authorName: varchar("author_name", {
|
|
47
|
+
length: 120
|
|
48
|
+
}),
|
|
49
|
+
seoTitle: varchar("seo_title", {
|
|
50
|
+
length: 200
|
|
51
|
+
}),
|
|
52
|
+
seoDescription: varchar("seo_description", {
|
|
53
|
+
length: 320
|
|
54
|
+
}),
|
|
55
|
+
canonicalUrl: varchar("canonical_url", {
|
|
56
|
+
length: 2048
|
|
57
|
+
}),
|
|
58
|
+
readingTimeMinutes: integer("reading_time_minutes").notNull().default(1),
|
|
59
|
+
createdAt: timestamp("created_at", {
|
|
60
|
+
withTimezone: true
|
|
61
|
+
}).notNull().defaultNow(),
|
|
62
|
+
updatedAt: timestamp("updated_at", {
|
|
63
|
+
withTimezone: true
|
|
64
|
+
}).notNull().defaultNow()
|
|
65
|
+
}, (table) => [
|
|
66
|
+
// Sem `where deleted_at`: excluir é arquivar, e o slug arquivado continua reservado — reusá-lo
|
|
67
|
+
// faria um link antigo (já compartilhado) abrir outro post.
|
|
68
|
+
uniqueIndex("idx_posts_company_slug").on(table.companyId, table.slug),
|
|
69
|
+
// Serve a listagem pública: empresa + status + ordem por data.
|
|
70
|
+
index("idx_posts_company_status_published").on(table.companyId, table.status, table.publishedAt),
|
|
71
|
+
index("idx_posts_tags").using("gin", table.tags)
|
|
72
|
+
]);
|
|
73
|
+
|
|
74
|
+
// src/repositories/conditions.ts
|
|
75
|
+
import { and, arrayContains, eq, gt, inArray, lte, or, sql } from "drizzle-orm";
|
|
76
|
+
import { POST_STATUS } from "@adatechnology/content-contracts";
|
|
77
|
+
function postOwnedByCondition(params) {
|
|
78
|
+
return and(eq(posts.companyId, params.companyId), eq(posts.id, params.id));
|
|
79
|
+
}
|
|
80
|
+
__name(postOwnedByCondition, "postOwnedByCondition");
|
|
81
|
+
function postSlugCondition(params) {
|
|
82
|
+
return and(eq(posts.companyId, params.companyId), eq(posts.slug, params.slug));
|
|
83
|
+
}
|
|
84
|
+
__name(postSlugCondition, "postSlugCondition");
|
|
85
|
+
function postAdminListCondition(params) {
|
|
86
|
+
const conditions = [
|
|
87
|
+
eq(posts.companyId, params.companyId)
|
|
88
|
+
];
|
|
89
|
+
if (params.status) conditions.push(statusCondition(params.status, params.now));
|
|
90
|
+
if (params.tag) conditions.push(arrayContains(posts.tags, [
|
|
91
|
+
params.tag
|
|
92
|
+
]));
|
|
93
|
+
if (params.search) {
|
|
94
|
+
const pattern = `%${params.search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`;
|
|
95
|
+
conditions.push(sql`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`);
|
|
96
|
+
}
|
|
97
|
+
return and(...conditions);
|
|
98
|
+
}
|
|
99
|
+
__name(postAdminListCondition, "postAdminListCondition");
|
|
100
|
+
function statusCondition(status, now) {
|
|
101
|
+
if (status === POST_STATUS.PUBLISHED) {
|
|
102
|
+
return or(eq(posts.status, POST_STATUS.PUBLISHED), and(eq(posts.status, POST_STATUS.SCHEDULED), lte(posts.publishedAt, now)));
|
|
103
|
+
}
|
|
104
|
+
if (status === POST_STATUS.SCHEDULED) {
|
|
105
|
+
return and(eq(posts.status, POST_STATUS.SCHEDULED), gt(posts.publishedAt, now));
|
|
106
|
+
}
|
|
107
|
+
return eq(posts.status, status);
|
|
108
|
+
}
|
|
109
|
+
__name(statusCondition, "statusCondition");
|
|
110
|
+
function postPublicCondition(params) {
|
|
111
|
+
const conditions = [
|
|
112
|
+
eq(posts.companyId, params.companyId),
|
|
113
|
+
inArray(posts.status, [
|
|
114
|
+
POST_STATUS.PUBLISHED,
|
|
115
|
+
POST_STATUS.SCHEDULED
|
|
116
|
+
]),
|
|
117
|
+
lte(posts.publishedAt, params.now)
|
|
118
|
+
];
|
|
119
|
+
if (params.tag) conditions.push(arrayContains(posts.tags, [
|
|
120
|
+
params.tag
|
|
121
|
+
]));
|
|
122
|
+
return and(...conditions);
|
|
123
|
+
}
|
|
124
|
+
__name(postPublicCondition, "postPublicCondition");
|
|
125
|
+
function postPublicSlugCondition(params) {
|
|
126
|
+
return and(postPublicCondition(params), eq(posts.slug, params.slug));
|
|
127
|
+
}
|
|
128
|
+
__name(postPublicSlugCondition, "postPublicSlugCondition");
|
|
129
|
+
|
|
130
|
+
// src/repositories/PostRepository.ts
|
|
131
|
+
var TAG_LIST_LIMIT = 200;
|
|
132
|
+
var PostRepository = class {
|
|
133
|
+
static {
|
|
134
|
+
__name(this, "PostRepository");
|
|
135
|
+
}
|
|
136
|
+
db;
|
|
137
|
+
constructor(db) {
|
|
138
|
+
this.db = db;
|
|
139
|
+
}
|
|
140
|
+
async create(values) {
|
|
141
|
+
const [row] = await this.db.insert(posts).values(values).returning();
|
|
142
|
+
if (!row) throw new Error("content-module: insert em posts n\xE3o retornou linha");
|
|
143
|
+
return row;
|
|
144
|
+
}
|
|
145
|
+
async findById(params) {
|
|
146
|
+
const [row] = await this.db.select().from(posts).where(postOwnedByCondition(params)).limit(1);
|
|
147
|
+
return row;
|
|
148
|
+
}
|
|
149
|
+
async findBySlug(params) {
|
|
150
|
+
const [row] = await this.db.select().from(posts).where(postSlugCondition(params)).limit(1);
|
|
151
|
+
return row;
|
|
152
|
+
}
|
|
153
|
+
async findPublicBySlug(params) {
|
|
154
|
+
const [row] = await this.db.select().from(posts).where(postPublicSlugCondition(params)).limit(1);
|
|
155
|
+
return row;
|
|
156
|
+
}
|
|
157
|
+
async update(params) {
|
|
158
|
+
const [row] = await this.db.update(posts).set({
|
|
159
|
+
...params.values,
|
|
160
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
161
|
+
}).where(postOwnedByCondition(params)).returning();
|
|
162
|
+
return row;
|
|
163
|
+
}
|
|
164
|
+
async listForAdmin(query) {
|
|
165
|
+
const where = postAdminListCondition(query);
|
|
166
|
+
const [rows, [counted]] = await Promise.all([
|
|
167
|
+
this.db.select().from(posts).where(where).orderBy(desc(posts.updatedAt), asc(posts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
|
|
168
|
+
this.db.select({
|
|
169
|
+
value: sql2`count(*)::int`
|
|
170
|
+
}).from(posts).where(where)
|
|
171
|
+
]);
|
|
172
|
+
return {
|
|
173
|
+
rows,
|
|
174
|
+
total: counted?.value ?? 0
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
async listPublic(query) {
|
|
178
|
+
const where = postPublicCondition(query);
|
|
179
|
+
const [rows, [counted]] = await Promise.all([
|
|
180
|
+
this.db.select().from(posts).where(where).orderBy(desc(posts.publishedAt), asc(posts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
|
|
181
|
+
this.db.select({
|
|
182
|
+
value: sql2`count(*)::int`
|
|
183
|
+
}).from(posts).where(where)
|
|
184
|
+
]);
|
|
185
|
+
return {
|
|
186
|
+
rows,
|
|
187
|
+
total: counted?.value ?? 0
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
async listTags(params) {
|
|
191
|
+
const where = params.publicAt ? postPublicCondition({
|
|
192
|
+
companyId: params.companyId,
|
|
193
|
+
now: params.publicAt
|
|
194
|
+
}) : postAdminListCondition({
|
|
195
|
+
companyId: params.companyId,
|
|
196
|
+
now: /* @__PURE__ */ new Date()
|
|
197
|
+
});
|
|
198
|
+
const postTags = this.db.select({
|
|
199
|
+
tag: sql2`unnest(${posts.tags})`.as("tag")
|
|
200
|
+
}).from(posts).where(where).as("post_tags");
|
|
201
|
+
const rows = await this.db.select({
|
|
202
|
+
tag: postTags.tag,
|
|
203
|
+
count: sql2`count(*)::int`
|
|
204
|
+
}).from(postTags).groupBy(postTags.tag).orderBy(sql2`count(*) desc`, asc(postTags.tag)).limit(TAG_LIST_LIMIT);
|
|
205
|
+
return rows;
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
// src/use-cases/Feed.use-cases.ts
|
|
210
|
+
import { buildAtomFeed, buildExcerpt, buildPostUrl, buildRssFeed, renderMarkdownToHtml } from "@adatechnology/content-contracts";
|
|
211
|
+
var DEFAULT_ITEM_LIMIT = 20;
|
|
212
|
+
var SITEMAP_LIMIT = 5e4;
|
|
213
|
+
var FEED_FORMAT = {
|
|
214
|
+
RSS: "rss",
|
|
215
|
+
ATOM: "atom"
|
|
216
|
+
};
|
|
217
|
+
var BuildFeedUseCase = class {
|
|
218
|
+
static {
|
|
219
|
+
__name(this, "BuildFeedUseCase");
|
|
220
|
+
}
|
|
221
|
+
dependencies;
|
|
222
|
+
feed;
|
|
223
|
+
constructor(dependencies, feed) {
|
|
224
|
+
this.dependencies = dependencies;
|
|
225
|
+
this.feed = feed;
|
|
226
|
+
}
|
|
227
|
+
async execute(params) {
|
|
228
|
+
const now = this.dependencies.clock.now();
|
|
229
|
+
const page = await this.dependencies.posts.listPublic({
|
|
230
|
+
companyId: params.companyId,
|
|
231
|
+
now,
|
|
232
|
+
page: 1,
|
|
233
|
+
pageSize: this.feed.itemLimit ?? DEFAULT_ITEM_LIMIT
|
|
234
|
+
});
|
|
235
|
+
const channel = {
|
|
236
|
+
siteUrl: this.feed.siteUrl,
|
|
237
|
+
title: this.feed.title,
|
|
238
|
+
...this.feed.description ? {
|
|
239
|
+
description: this.feed.description
|
|
240
|
+
} : {},
|
|
241
|
+
...this.feed.language ? {
|
|
242
|
+
language: this.feed.language
|
|
243
|
+
} : {},
|
|
244
|
+
...params.feedUrl ? {
|
|
245
|
+
feedUrl: params.feedUrl
|
|
246
|
+
} : {}
|
|
247
|
+
};
|
|
248
|
+
const items = page.rows.map((row) => this.toItem(row));
|
|
249
|
+
return params.format === FEED_FORMAT.ATOM ? buildAtomFeed({
|
|
250
|
+
channel,
|
|
251
|
+
items,
|
|
252
|
+
now
|
|
253
|
+
}) : buildRssFeed({
|
|
254
|
+
channel,
|
|
255
|
+
items
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
toItem(row) {
|
|
259
|
+
return {
|
|
260
|
+
title: row.title,
|
|
261
|
+
url: buildPostUrl({
|
|
262
|
+
siteUrl: this.feed.siteUrl,
|
|
263
|
+
slug: row.slug,
|
|
264
|
+
postPathTemplate: this.feed.postPathTemplate
|
|
265
|
+
}),
|
|
266
|
+
publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
|
|
267
|
+
updatedAt: row.updatedAt.toISOString(),
|
|
268
|
+
summary: row.excerpt ?? buildExcerpt(row.body),
|
|
269
|
+
...this.feed.includeContent ?? true ? {
|
|
270
|
+
contentHtml: renderMarkdownToHtml(row.body, {
|
|
271
|
+
headingIds: false
|
|
272
|
+
})
|
|
273
|
+
} : {},
|
|
274
|
+
...row.authorName ? {
|
|
275
|
+
authorName: row.authorName
|
|
276
|
+
} : {},
|
|
277
|
+
categories: row.tags,
|
|
278
|
+
...row.coverImageUrl ? {
|
|
279
|
+
imageUrl: row.coverImageUrl
|
|
280
|
+
} : {}
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
var ListSitemapEntriesUseCase = class {
|
|
285
|
+
static {
|
|
286
|
+
__name(this, "ListSitemapEntriesUseCase");
|
|
287
|
+
}
|
|
288
|
+
dependencies;
|
|
289
|
+
feed;
|
|
290
|
+
constructor(dependencies, feed) {
|
|
291
|
+
this.dependencies = dependencies;
|
|
292
|
+
this.feed = feed;
|
|
293
|
+
}
|
|
294
|
+
/** Entradas para o host juntar ao sitemap dele — o módulo não é dono do sitemap do site. */
|
|
295
|
+
async execute(params) {
|
|
296
|
+
const page = await this.dependencies.posts.listPublic({
|
|
297
|
+
companyId: params.companyId,
|
|
298
|
+
now: this.dependencies.clock.now(),
|
|
299
|
+
page: 1,
|
|
300
|
+
pageSize: SITEMAP_LIMIT
|
|
301
|
+
});
|
|
302
|
+
return page.rows.map((row) => ({
|
|
303
|
+
loc: buildPostUrl({
|
|
304
|
+
siteUrl: this.feed.siteUrl,
|
|
305
|
+
slug: row.slug,
|
|
306
|
+
postPathTemplate: this.feed.postPathTemplate
|
|
307
|
+
}),
|
|
308
|
+
lastmod: row.updatedAt.toISOString()
|
|
309
|
+
}));
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
// src/use-cases/Post.use-cases.ts
|
|
314
|
+
import { createPostSchema, DuplicateSlugError, estimateReadingTimeMinutes, listPostsQuerySchema, normalizeTags, POST_EVENT, POST_STATUS as POST_STATUS3, PostNotFoundError, publishPostSchema, slugify, updatePostSchema, withSlugSuffix } from "@adatechnology/content-contracts";
|
|
315
|
+
|
|
316
|
+
// src/shared/isUniqueViolation.ts
|
|
317
|
+
var UNIQUE_VIOLATION = "23505";
|
|
318
|
+
function isUniqueViolation(error) {
|
|
319
|
+
let current = error;
|
|
320
|
+
for (let depth = 0; depth < 3 && typeof current === "object" && current !== null; depth += 1) {
|
|
321
|
+
if (current.code === UNIQUE_VIOLATION) return true;
|
|
322
|
+
current = current.cause;
|
|
323
|
+
}
|
|
324
|
+
return false;
|
|
325
|
+
}
|
|
326
|
+
__name(isUniqueViolation, "isUniqueViolation");
|
|
327
|
+
|
|
328
|
+
// src/shared/notifyPostChanged.ts
|
|
329
|
+
async function notifyPostChanged(dependencies, type, post) {
|
|
330
|
+
const hook = dependencies.hooks?.onPostChanged;
|
|
331
|
+
if (!hook) return;
|
|
332
|
+
try {
|
|
333
|
+
await hook({
|
|
334
|
+
type,
|
|
335
|
+
post
|
|
336
|
+
});
|
|
337
|
+
} catch (error) {
|
|
338
|
+
dependencies.logger?.error("content-module: hook onPostChanged falhou", {
|
|
339
|
+
postId: post.id,
|
|
340
|
+
type,
|
|
341
|
+
error: error instanceof Error ? error.message : String(error)
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
__name(notifyPostChanged, "notifyPostChanged");
|
|
346
|
+
|
|
347
|
+
// src/shared/toContract.ts
|
|
348
|
+
import { POST_STATUS as POST_STATUS2 } from "@adatechnology/content-contracts";
|
|
349
|
+
function effectiveStatus(row, now) {
|
|
350
|
+
if (row.status === POST_STATUS2.SCHEDULED && row.publishedAt && row.publishedAt <= now) return POST_STATUS2.PUBLISHED;
|
|
351
|
+
return row.status;
|
|
352
|
+
}
|
|
353
|
+
__name(effectiveStatus, "effectiveStatus");
|
|
354
|
+
function toPostSummary(row, now) {
|
|
355
|
+
return {
|
|
356
|
+
id: row.id,
|
|
357
|
+
companyId: row.companyId,
|
|
358
|
+
slug: row.slug,
|
|
359
|
+
title: row.title,
|
|
360
|
+
excerpt: row.excerpt,
|
|
361
|
+
coverImageUrl: row.coverImageUrl,
|
|
362
|
+
coverImageAlt: row.coverImageAlt,
|
|
363
|
+
tags: row.tags,
|
|
364
|
+
status: effectiveStatus(row, now),
|
|
365
|
+
publishedAt: row.publishedAt?.toISOString() ?? null,
|
|
366
|
+
authorName: row.authorName,
|
|
367
|
+
seoTitle: row.seoTitle,
|
|
368
|
+
seoDescription: row.seoDescription,
|
|
369
|
+
canonicalUrl: row.canonicalUrl,
|
|
370
|
+
readingTimeMinutes: row.readingTimeMinutes,
|
|
371
|
+
createdAt: row.createdAt.toISOString(),
|
|
372
|
+
updatedAt: row.updatedAt.toISOString()
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
__name(toPostSummary, "toPostSummary");
|
|
376
|
+
function toPost(row, now) {
|
|
377
|
+
return {
|
|
378
|
+
...toPostSummary(row, now),
|
|
379
|
+
body: row.body
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
__name(toPost, "toPost");
|
|
383
|
+
function toPublicPostSummary(row) {
|
|
384
|
+
return {
|
|
385
|
+
id: row.id,
|
|
386
|
+
slug: row.slug,
|
|
387
|
+
title: row.title,
|
|
388
|
+
excerpt: row.excerpt,
|
|
389
|
+
coverImageUrl: row.coverImageUrl,
|
|
390
|
+
coverImageAlt: row.coverImageAlt,
|
|
391
|
+
tags: row.tags,
|
|
392
|
+
publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
|
|
393
|
+
updatedAt: row.updatedAt.toISOString(),
|
|
394
|
+
authorName: row.authorName,
|
|
395
|
+
seoTitle: row.seoTitle,
|
|
396
|
+
seoDescription: row.seoDescription,
|
|
397
|
+
canonicalUrl: row.canonicalUrl,
|
|
398
|
+
readingTimeMinutes: row.readingTimeMinutes
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
__name(toPublicPostSummary, "toPublicPostSummary");
|
|
402
|
+
function toPublicPost(row) {
|
|
403
|
+
return {
|
|
404
|
+
...toPublicPostSummary(row),
|
|
405
|
+
body: row.body
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
__name(toPublicPost, "toPublicPost");
|
|
409
|
+
function toPagination(params) {
|
|
410
|
+
return {
|
|
411
|
+
...params,
|
|
412
|
+
totalPages: Math.max(1, Math.ceil(params.total / params.pageSize))
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
__name(toPagination, "toPagination");
|
|
416
|
+
|
|
417
|
+
// src/use-cases/Post.use-cases.ts
|
|
418
|
+
var MAX_SLUG_ATTEMPTS = 50;
|
|
419
|
+
var FALLBACK_SLUG = "post";
|
|
420
|
+
var PostUseCaseBase = class PostUseCaseBase2 {
|
|
421
|
+
static {
|
|
422
|
+
__name(this, "PostUseCaseBase");
|
|
423
|
+
}
|
|
424
|
+
dependencies;
|
|
425
|
+
constructor(dependencies) {
|
|
426
|
+
this.dependencies = dependencies;
|
|
427
|
+
}
|
|
428
|
+
now() {
|
|
429
|
+
return this.dependencies.clock.now();
|
|
430
|
+
}
|
|
431
|
+
async findOrFail(reference2) {
|
|
432
|
+
const row = await this.dependencies.posts.findById(reference2);
|
|
433
|
+
if (!row) throw new PostNotFoundError(reference2.id);
|
|
434
|
+
return row;
|
|
435
|
+
}
|
|
436
|
+
async save(reference2, values, event) {
|
|
437
|
+
const row = await this.dependencies.posts.update({
|
|
438
|
+
...reference2,
|
|
439
|
+
values
|
|
440
|
+
}).catch((error) => {
|
|
441
|
+
if (isUniqueViolation(error) && values.slug) throw new DuplicateSlugError(values.slug);
|
|
442
|
+
throw error;
|
|
443
|
+
});
|
|
444
|
+
if (!row) throw new PostNotFoundError(reference2.id);
|
|
445
|
+
const post = toPost(row, this.now());
|
|
446
|
+
await notifyPostChanged(this.dependencies, event, post);
|
|
447
|
+
return post;
|
|
448
|
+
}
|
|
449
|
+
readingTime(body) {
|
|
450
|
+
return estimateReadingTimeMinutes(body, this.dependencies.config.wordsPerMinute);
|
|
451
|
+
}
|
|
452
|
+
async assertSlugAvailable(companyId, slug, ownId) {
|
|
453
|
+
const existing = await this.dependencies.posts.findBySlug({
|
|
454
|
+
companyId,
|
|
455
|
+
slug
|
|
456
|
+
});
|
|
457
|
+
if (existing && existing.id !== ownId) throw new DuplicateSlugError(slug);
|
|
458
|
+
}
|
|
459
|
+
/** `titulo`, `titulo-2`, `titulo-3`… Sequencial de propósito: cada tentativa depende da anterior. */
|
|
460
|
+
async generateSlug(companyId, title) {
|
|
461
|
+
const base = slugify(title) || FALLBACK_SLUG;
|
|
462
|
+
for (let attempt = 1; attempt <= MAX_SLUG_ATTEMPTS; attempt += 1) {
|
|
463
|
+
const candidate = withSlugSuffix(base, attempt);
|
|
464
|
+
if (!await this.dependencies.posts.findBySlug({
|
|
465
|
+
companyId,
|
|
466
|
+
slug: candidate
|
|
467
|
+
})) return candidate;
|
|
468
|
+
}
|
|
469
|
+
return withSlugSuffix(base, Date.now());
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
function optionalFields(input) {
|
|
473
|
+
const values = {};
|
|
474
|
+
if (input.excerpt !== void 0) values.excerpt = input.excerpt || null;
|
|
475
|
+
if (input.coverImageUrl !== void 0) values.coverImageUrl = input.coverImageUrl || null;
|
|
476
|
+
if (input.coverImageAlt !== void 0) values.coverImageAlt = input.coverImageAlt || null;
|
|
477
|
+
if (input.authorName !== void 0) values.authorName = input.authorName || null;
|
|
478
|
+
if (input.seoTitle !== void 0) values.seoTitle = input.seoTitle || null;
|
|
479
|
+
if (input.seoDescription !== void 0) values.seoDescription = input.seoDescription || null;
|
|
480
|
+
if (input.canonicalUrl !== void 0) values.canonicalUrl = input.canonicalUrl || null;
|
|
481
|
+
return values;
|
|
482
|
+
}
|
|
483
|
+
__name(optionalFields, "optionalFields");
|
|
484
|
+
var CreatePostUseCase = class extends PostUseCaseBase {
|
|
485
|
+
static {
|
|
486
|
+
__name(this, "CreatePostUseCase");
|
|
487
|
+
}
|
|
488
|
+
async execute(params) {
|
|
489
|
+
const input = createPostSchema.parse(params.input);
|
|
490
|
+
const { companyId } = params;
|
|
491
|
+
if (input.slug) await this.assertSlugAvailable(companyId, input.slug);
|
|
492
|
+
const slug = input.slug ?? await this.generateSlug(companyId, input.title);
|
|
493
|
+
const row = await this.dependencies.posts.create({
|
|
494
|
+
companyId,
|
|
495
|
+
slug,
|
|
496
|
+
title: input.title,
|
|
497
|
+
body: input.body,
|
|
498
|
+
tags: normalizeTags(input.tags ?? []),
|
|
499
|
+
status: POST_STATUS3.DRAFT,
|
|
500
|
+
readingTimeMinutes: this.readingTime(input.body),
|
|
501
|
+
...optionalFields(input)
|
|
502
|
+
}).catch((error) => {
|
|
503
|
+
if (isUniqueViolation(error)) throw new DuplicateSlugError(slug);
|
|
504
|
+
throw error;
|
|
505
|
+
});
|
|
506
|
+
const post = toPost(row, this.now());
|
|
507
|
+
await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, post);
|
|
508
|
+
return post;
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
var UpdatePostUseCase = class extends PostUseCaseBase {
|
|
512
|
+
static {
|
|
513
|
+
__name(this, "UpdatePostUseCase");
|
|
514
|
+
}
|
|
515
|
+
/** Trocar o título não muda o slug: o endereço já pode ter sido compartilhado. */
|
|
516
|
+
async execute(params) {
|
|
517
|
+
const input = updatePostSchema.parse(params.input);
|
|
518
|
+
const existing = await this.findOrFail(params);
|
|
519
|
+
const values = optionalFields(input);
|
|
520
|
+
if (input.title !== void 0) values.title = input.title;
|
|
521
|
+
if (input.body !== void 0) {
|
|
522
|
+
values.body = input.body;
|
|
523
|
+
values.readingTimeMinutes = this.readingTime(input.body);
|
|
524
|
+
}
|
|
525
|
+
if (input.tags !== void 0) values.tags = normalizeTags(input.tags);
|
|
526
|
+
if (input.slug !== void 0 && input.slug !== existing.slug) {
|
|
527
|
+
await this.assertSlugAvailable(params.companyId, input.slug, existing.id);
|
|
528
|
+
values.slug = input.slug;
|
|
529
|
+
}
|
|
530
|
+
return this.save(params, values, POST_EVENT.UPDATED);
|
|
531
|
+
}
|
|
532
|
+
};
|
|
533
|
+
var PublishPostUseCase = class extends PostUseCaseBase {
|
|
534
|
+
static {
|
|
535
|
+
__name(this, "PublishPostUseCase");
|
|
536
|
+
}
|
|
537
|
+
/** Sem data: publica agora. Data futura: agenda. Data passada: publica com a data informada. */
|
|
538
|
+
async execute(params) {
|
|
539
|
+
const input = publishPostSchema.parse(params.input ?? {});
|
|
540
|
+
await this.findOrFail(params);
|
|
541
|
+
const now = this.now();
|
|
542
|
+
const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now;
|
|
543
|
+
const status = publishedAt > now ? POST_STATUS3.SCHEDULED : POST_STATUS3.PUBLISHED;
|
|
544
|
+
return this.save(params, {
|
|
545
|
+
status,
|
|
546
|
+
publishedAt
|
|
547
|
+
}, POST_EVENT.PUBLISHED);
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
var UnpublishPostUseCase = class extends PostUseCaseBase {
|
|
551
|
+
static {
|
|
552
|
+
__name(this, "UnpublishPostUseCase");
|
|
553
|
+
}
|
|
554
|
+
/** Volta a rascunho e tira do ar na hora, inclusive cancelando um agendamento. */
|
|
555
|
+
async execute(params) {
|
|
556
|
+
await this.findOrFail(params);
|
|
557
|
+
return this.save(params, {
|
|
558
|
+
status: POST_STATUS3.DRAFT,
|
|
559
|
+
publishedAt: null
|
|
560
|
+
}, POST_EVENT.UNPUBLISHED);
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
var ArchivePostUseCase = class extends PostUseCaseBase {
|
|
564
|
+
static {
|
|
565
|
+
__name(this, "ArchivePostUseCase");
|
|
566
|
+
}
|
|
567
|
+
/** "Excluir" no painel é arquivar: some do site, mas o conteúdo e o slug continuam guardados. */
|
|
568
|
+
async execute(params) {
|
|
569
|
+
await this.findOrFail(params);
|
|
570
|
+
return this.save(params, {
|
|
571
|
+
status: POST_STATUS3.ARCHIVED
|
|
572
|
+
}, POST_EVENT.ARCHIVED);
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
var GetPostUseCase = class extends PostUseCaseBase {
|
|
576
|
+
static {
|
|
577
|
+
__name(this, "GetPostUseCase");
|
|
578
|
+
}
|
|
579
|
+
async execute(params) {
|
|
580
|
+
return toPost(await this.findOrFail(params), this.now());
|
|
581
|
+
}
|
|
582
|
+
};
|
|
583
|
+
var ListPostsUseCase = class extends PostUseCaseBase {
|
|
584
|
+
static {
|
|
585
|
+
__name(this, "ListPostsUseCase");
|
|
586
|
+
}
|
|
587
|
+
async execute(params) {
|
|
588
|
+
const { companyId, ...rawQuery } = params;
|
|
589
|
+
const query = listPostsQuerySchema.parse(rawQuery);
|
|
590
|
+
const tag = query.tag ? normalizeTags([
|
|
591
|
+
query.tag
|
|
592
|
+
])[0] : void 0;
|
|
593
|
+
const now = this.now();
|
|
594
|
+
const page = await this.dependencies.posts.listForAdmin({
|
|
595
|
+
companyId,
|
|
596
|
+
...query,
|
|
597
|
+
now,
|
|
598
|
+
...tag ? {
|
|
599
|
+
tag
|
|
600
|
+
} : {}
|
|
601
|
+
});
|
|
602
|
+
return {
|
|
603
|
+
data: page.rows.map((row) => toPostSummary(row, now)),
|
|
604
|
+
pagination: toPagination({
|
|
605
|
+
total: page.total,
|
|
606
|
+
page: query.page,
|
|
607
|
+
pageSize: query.pageSize
|
|
608
|
+
})
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
|
|
613
|
+
// src/use-cases/PublicPost.use-cases.ts
|
|
614
|
+
import { listPublishedPostsQuerySchema, normalizeTag, PostNotFoundError as PostNotFoundError2 } from "@adatechnology/content-contracts";
|
|
615
|
+
var GetPublishedPostBySlugUseCase = class {
|
|
616
|
+
static {
|
|
617
|
+
__name(this, "GetPublishedPostBySlugUseCase");
|
|
618
|
+
}
|
|
619
|
+
dependencies;
|
|
620
|
+
constructor(dependencies) {
|
|
621
|
+
this.dependencies = dependencies;
|
|
622
|
+
}
|
|
623
|
+
async execute(params) {
|
|
624
|
+
const slug = params.slug.trim().toLowerCase();
|
|
625
|
+
const row = await this.dependencies.posts.findPublicBySlug({
|
|
626
|
+
companyId: params.companyId,
|
|
627
|
+
slug,
|
|
628
|
+
now: this.dependencies.clock.now()
|
|
629
|
+
});
|
|
630
|
+
if (!row) throw new PostNotFoundError2(slug);
|
|
631
|
+
return toPublicPost(row);
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
var ListPublishedPostsUseCase = class {
|
|
635
|
+
static {
|
|
636
|
+
__name(this, "ListPublishedPostsUseCase");
|
|
637
|
+
}
|
|
638
|
+
dependencies;
|
|
639
|
+
constructor(dependencies) {
|
|
640
|
+
this.dependencies = dependencies;
|
|
641
|
+
}
|
|
642
|
+
async execute(params) {
|
|
643
|
+
const { companyId, ...rawQuery } = params;
|
|
644
|
+
const query = listPublishedPostsQuerySchema.parse(rawQuery);
|
|
645
|
+
const tag = query.tag ? normalizeTag(query.tag) : void 0;
|
|
646
|
+
const page = await this.dependencies.posts.listPublic({
|
|
647
|
+
companyId,
|
|
648
|
+
now: this.dependencies.clock.now(),
|
|
649
|
+
page: query.page,
|
|
650
|
+
pageSize: query.pageSize,
|
|
651
|
+
...tag ? {
|
|
652
|
+
tag
|
|
653
|
+
} : {}
|
|
654
|
+
});
|
|
655
|
+
return {
|
|
656
|
+
data: page.rows.map(toPublicPostSummary),
|
|
657
|
+
pagination: toPagination({
|
|
658
|
+
total: page.total,
|
|
659
|
+
page: query.page,
|
|
660
|
+
pageSize: query.pageSize
|
|
661
|
+
})
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
var TAG_SCOPE = {
|
|
666
|
+
PUBLIC: "public",
|
|
667
|
+
ADMIN: "admin"
|
|
668
|
+
};
|
|
669
|
+
var ListTagsUseCase = class {
|
|
670
|
+
static {
|
|
671
|
+
__name(this, "ListTagsUseCase");
|
|
672
|
+
}
|
|
673
|
+
dependencies;
|
|
674
|
+
constructor(dependencies) {
|
|
675
|
+
this.dependencies = dependencies;
|
|
676
|
+
}
|
|
677
|
+
/** `public` conta só posts no ar; `admin` conta todos, para o autor reaproveitar a tag. */
|
|
678
|
+
async execute(params) {
|
|
679
|
+
return this.dependencies.posts.listTags({
|
|
680
|
+
companyId: params.companyId,
|
|
681
|
+
...params.scope === TAG_SCOPE.PUBLIC ? {
|
|
682
|
+
publicAt: this.dependencies.clock.now()
|
|
683
|
+
} : {}
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
};
|
|
687
|
+
|
|
688
|
+
// src/use-cases/UploadCoverImage.use-case.ts
|
|
689
|
+
import { ImageStorageDisabledError, InvalidCoverImageError } from "@adatechnology/content-contracts";
|
|
690
|
+
|
|
691
|
+
// src/shared/coverImage.constant.ts
|
|
692
|
+
var COVER_IMAGE = {
|
|
693
|
+
MAX_BYTES: 1024 * 1024,
|
|
694
|
+
KEY_PREFIX: "content/posts",
|
|
695
|
+
EXTENSION_BY_MIME: {
|
|
696
|
+
"image/jpeg": "jpg",
|
|
697
|
+
"image/png": "png",
|
|
698
|
+
"image/webp": "webp"
|
|
699
|
+
}
|
|
700
|
+
};
|
|
701
|
+
|
|
702
|
+
// src/use-cases/UploadCoverImage.use-case.ts
|
|
703
|
+
var UploadCoverImageUseCase = class {
|
|
704
|
+
static {
|
|
705
|
+
__name(this, "UploadCoverImageUseCase");
|
|
706
|
+
}
|
|
707
|
+
dependencies;
|
|
708
|
+
constructor(dependencies) {
|
|
709
|
+
this.dependencies = dependencies;
|
|
710
|
+
}
|
|
711
|
+
async execute(params) {
|
|
712
|
+
const storage = this.dependencies.imageStorage;
|
|
713
|
+
if (!storage) throw new ImageStorageDisabledError();
|
|
714
|
+
const mimeType = (params.mimeType.split(";")[0] ?? "").trim().toLowerCase();
|
|
715
|
+
const extension = COVER_IMAGE.EXTENSION_BY_MIME[mimeType];
|
|
716
|
+
if (!extension) throw new InvalidCoverImageError("unsupported_type");
|
|
717
|
+
if (params.bytes.byteLength === 0) throw new InvalidCoverImageError("empty");
|
|
718
|
+
if (params.bytes.byteLength > COVER_IMAGE.MAX_BYTES) throw new InvalidCoverImageError("too_large");
|
|
719
|
+
const key = `${COVER_IMAGE.KEY_PREFIX}/${params.companyId}/${crypto.randomUUID()}.${extension}`;
|
|
720
|
+
return storage.upload({
|
|
721
|
+
buffer: params.bytes,
|
|
722
|
+
mimeType,
|
|
723
|
+
key
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
};
|
|
727
|
+
|
|
728
|
+
// src/ContentModule.ts
|
|
729
|
+
var SYSTEM_CLOCK = {
|
|
730
|
+
now: /* @__PURE__ */ __name(() => /* @__PURE__ */ new Date(), "now")
|
|
731
|
+
};
|
|
732
|
+
function assertValidConfig(config) {
|
|
733
|
+
if (config.feed && !/^https?:\/\/[^/]/i.test(config.feed.siteUrl)) throw new ConfigMissingError("feed.siteUrl");
|
|
734
|
+
if (config.feed && !config.feed.title.trim()) throw new ConfigMissingError("feed.title");
|
|
735
|
+
if (config.feed?.postPathTemplate && !config.feed.postPathTemplate.includes("{slug}")) {
|
|
736
|
+
throw new ConfigMissingError("feed.postPathTemplate");
|
|
737
|
+
}
|
|
738
|
+
if (config.wordsPerMinute !== void 0 && !(config.wordsPerMinute > 0)) throw new ConfigMissingError("wordsPerMinute");
|
|
739
|
+
}
|
|
740
|
+
__name(assertValidConfig, "assertValidConfig");
|
|
741
|
+
function createContentModule(params) {
|
|
742
|
+
const config = params.config ?? {};
|
|
743
|
+
assertValidConfig(config);
|
|
744
|
+
const posts2 = params.providers?.postStore ?? (params.db ? new PostRepository(params.db) : void 0);
|
|
745
|
+
if (!posts2) throw new ConfigMissingError("db");
|
|
746
|
+
const dependencies = {
|
|
747
|
+
posts: posts2,
|
|
748
|
+
config,
|
|
749
|
+
clock: params.providers?.clock ?? SYSTEM_CLOCK,
|
|
750
|
+
...params.hooks ? {
|
|
751
|
+
hooks: params.hooks
|
|
752
|
+
} : {},
|
|
753
|
+
...params.providers?.imageStorage ? {
|
|
754
|
+
imageStorage: params.providers.imageStorage
|
|
755
|
+
} : {},
|
|
756
|
+
...params.providers?.logger ? {
|
|
757
|
+
logger: params.providers.logger
|
|
758
|
+
} : {}
|
|
759
|
+
};
|
|
760
|
+
return {
|
|
761
|
+
useCases: {
|
|
762
|
+
createPost: new CreatePostUseCase(dependencies),
|
|
763
|
+
updatePost: new UpdatePostUseCase(dependencies),
|
|
764
|
+
archivePost: new ArchivePostUseCase(dependencies),
|
|
765
|
+
publishPost: new PublishPostUseCase(dependencies),
|
|
766
|
+
unpublishPost: new UnpublishPostUseCase(dependencies),
|
|
767
|
+
getPost: new GetPostUseCase(dependencies),
|
|
768
|
+
listPosts: new ListPostsUseCase(dependencies),
|
|
769
|
+
getPublishedPostBySlug: new GetPublishedPostBySlugUseCase(dependencies),
|
|
770
|
+
listPublishedPosts: new ListPublishedPostsUseCase(dependencies),
|
|
771
|
+
listTags: new ListTagsUseCase(dependencies),
|
|
772
|
+
...dependencies.imageStorage ? {
|
|
773
|
+
uploadCoverImage: new UploadCoverImageUseCase(dependencies)
|
|
774
|
+
} : {},
|
|
775
|
+
...config.feed ? {
|
|
776
|
+
buildFeed: new BuildFeedUseCase(dependencies, config.feed),
|
|
777
|
+
listSitemapEntries: new ListSitemapEntriesUseCase(dependencies, config.feed)
|
|
778
|
+
} : {}
|
|
779
|
+
},
|
|
780
|
+
config
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
__name(createContentModule, "createContentModule");
|
|
784
|
+
|
|
785
|
+
// src/http/adminRoutes.ts
|
|
786
|
+
import { createPostSchema as createPostSchema2, DEFAULT_ADMIN_SCOPES, listPostsQuerySchema as listPostsQuerySchema2, publishPostSchema as publishPostSchema2, updatePostSchema as updatePostSchema2 } from "@adatechnology/content-contracts";
|
|
787
|
+
|
|
788
|
+
// src/http/requireCompany.ts
|
|
789
|
+
import { CONTENT_ERROR_CODES, ContentError } from "@adatechnology/content-contracts";
|
|
790
|
+
function requireCompany(context) {
|
|
791
|
+
if (!context.auth?.companyId) {
|
|
792
|
+
throw new ContentError("Rota exige contexto autenticado.", 401, CONTENT_ERROR_CODES.CONFIG_MISSING);
|
|
793
|
+
}
|
|
794
|
+
return context.auth.companyId;
|
|
795
|
+
}
|
|
796
|
+
__name(requireCompany, "requireCompany");
|
|
797
|
+
|
|
798
|
+
// src/http/adminRoutes.ts
|
|
799
|
+
function reference(context) {
|
|
800
|
+
return {
|
|
801
|
+
companyId: requireCompany(context),
|
|
802
|
+
id: context.params.id ?? ""
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
__name(reference, "reference");
|
|
806
|
+
var json = /* @__PURE__ */ __name((status, data) => ({
|
|
807
|
+
kind: "json",
|
|
808
|
+
status,
|
|
809
|
+
body: {
|
|
810
|
+
data
|
|
811
|
+
}
|
|
812
|
+
}), "json");
|
|
813
|
+
function buildAdminRoutes(module) {
|
|
814
|
+
const { useCases } = module;
|
|
815
|
+
const requiredScopes = module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES;
|
|
816
|
+
const admin = {
|
|
817
|
+
scope: "admin",
|
|
818
|
+
requiredScopes
|
|
819
|
+
};
|
|
820
|
+
const uploadRoutes = useCases.uploadCoverImage ? [
|
|
821
|
+
{
|
|
822
|
+
...admin,
|
|
823
|
+
method: "POST",
|
|
824
|
+
path: "/posts/cover-images",
|
|
825
|
+
operationId: "uploadPostCoverImage",
|
|
826
|
+
summary: "Envia a imagem de capa (bytes crus, Content-Type jpeg/png/webp) e devolve a URL",
|
|
827
|
+
async handler(context) {
|
|
828
|
+
const upload = useCases.uploadCoverImage;
|
|
829
|
+
if (!upload) return {
|
|
830
|
+
kind: "empty",
|
|
831
|
+
status: 404
|
|
832
|
+
};
|
|
833
|
+
const result = await upload.execute({
|
|
834
|
+
companyId: requireCompany(context),
|
|
835
|
+
bytes: context.rawBody ?? new Uint8Array(),
|
|
836
|
+
mimeType: context.headers["content-type"] ?? ""
|
|
837
|
+
});
|
|
838
|
+
return json(201, result);
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
] : [];
|
|
842
|
+
return [
|
|
843
|
+
{
|
|
844
|
+
...admin,
|
|
845
|
+
method: "GET",
|
|
846
|
+
path: "/posts",
|
|
847
|
+
querySchema: listPostsQuerySchema2,
|
|
848
|
+
operationId: "listPosts",
|
|
849
|
+
summary: "Lista posts da empresa (todos os status), com filtro por status, tag e busca",
|
|
850
|
+
async handler(context) {
|
|
851
|
+
const result = await useCases.listPosts.execute({
|
|
852
|
+
companyId: requireCompany(context),
|
|
853
|
+
...context.query
|
|
854
|
+
});
|
|
855
|
+
return {
|
|
856
|
+
kind: "json",
|
|
857
|
+
status: 200,
|
|
858
|
+
body: result
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
},
|
|
862
|
+
{
|
|
863
|
+
...admin,
|
|
864
|
+
method: "POST",
|
|
865
|
+
path: "/posts",
|
|
866
|
+
bodySchema: createPostSchema2,
|
|
867
|
+
operationId: "createPost",
|
|
868
|
+
summary: "Cria um post como rascunho; sem slug, gera a partir do t\xEDtulo",
|
|
869
|
+
async handler(context) {
|
|
870
|
+
const post = await useCases.createPost.execute({
|
|
871
|
+
companyId: requireCompany(context),
|
|
872
|
+
input: context.body
|
|
873
|
+
});
|
|
874
|
+
return json(201, post);
|
|
875
|
+
}
|
|
876
|
+
},
|
|
877
|
+
// Antes de `/posts/:id`: `findRoute` para na primeira rota que casa, e `:id` casaria "tags".
|
|
878
|
+
{
|
|
879
|
+
...admin,
|
|
880
|
+
method: "GET",
|
|
881
|
+
path: "/posts/tags",
|
|
882
|
+
operationId: "listPostTags",
|
|
883
|
+
summary: "Tags usadas em qualquer post da empresa, com contagem",
|
|
884
|
+
async handler(context) {
|
|
885
|
+
return json(200, await useCases.listTags.execute({
|
|
886
|
+
companyId: requireCompany(context),
|
|
887
|
+
scope: TAG_SCOPE.ADMIN
|
|
888
|
+
}));
|
|
889
|
+
}
|
|
890
|
+
},
|
|
891
|
+
...uploadRoutes,
|
|
892
|
+
{
|
|
893
|
+
...admin,
|
|
894
|
+
method: "GET",
|
|
895
|
+
path: "/posts/:id",
|
|
896
|
+
operationId: "getPost",
|
|
897
|
+
summary: "L\xEA um post da empresa (qualquer status)",
|
|
898
|
+
async handler(context) {
|
|
899
|
+
return json(200, await useCases.getPost.execute(reference(context)));
|
|
900
|
+
}
|
|
901
|
+
},
|
|
902
|
+
{
|
|
903
|
+
...admin,
|
|
904
|
+
method: "PATCH",
|
|
905
|
+
path: "/posts/:id",
|
|
906
|
+
bodySchema: updatePostSchema2,
|
|
907
|
+
operationId: "updatePost",
|
|
908
|
+
summary: "Atualiza campos de um post; trocar o t\xEDtulo n\xE3o troca o slug",
|
|
909
|
+
async handler(context) {
|
|
910
|
+
return json(200, await useCases.updatePost.execute({
|
|
911
|
+
...reference(context),
|
|
912
|
+
input: context.body
|
|
913
|
+
}));
|
|
914
|
+
}
|
|
915
|
+
},
|
|
916
|
+
{
|
|
917
|
+
...admin,
|
|
918
|
+
method: "DELETE",
|
|
919
|
+
path: "/posts/:id",
|
|
920
|
+
operationId: "archivePost",
|
|
921
|
+
summary: "Arquiva o post: sai do site, conte\xFAdo e slug continuam guardados",
|
|
922
|
+
async handler(context) {
|
|
923
|
+
await useCases.archivePost.execute(reference(context));
|
|
924
|
+
return {
|
|
925
|
+
kind: "empty",
|
|
926
|
+
status: 204
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
},
|
|
930
|
+
{
|
|
931
|
+
...admin,
|
|
932
|
+
method: "POST",
|
|
933
|
+
path: "/posts/:id/publish",
|
|
934
|
+
// Opcional: `POST /publish` sem corpo publica agora.
|
|
935
|
+
bodySchema: publishPostSchema2.optional(),
|
|
936
|
+
operationId: "publishPost",
|
|
937
|
+
summary: "Publica agora, ou agenda quando `publishedAt` \xE9 futuro",
|
|
938
|
+
async handler(context) {
|
|
939
|
+
return json(200, await useCases.publishPost.execute({
|
|
940
|
+
...reference(context),
|
|
941
|
+
input: context.body ?? {}
|
|
942
|
+
}));
|
|
943
|
+
}
|
|
944
|
+
},
|
|
945
|
+
{
|
|
946
|
+
...admin,
|
|
947
|
+
method: "POST",
|
|
948
|
+
path: "/posts/:id/unpublish",
|
|
949
|
+
operationId: "unpublishPost",
|
|
950
|
+
summary: "Tira do ar (ou cancela o agendamento) e volta a rascunho",
|
|
951
|
+
async handler(context) {
|
|
952
|
+
return json(200, await useCases.unpublishPost.execute(reference(context)));
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
];
|
|
956
|
+
}
|
|
957
|
+
__name(buildAdminRoutes, "buildAdminRoutes");
|
|
958
|
+
|
|
959
|
+
// src/http/publicRoutes.ts
|
|
960
|
+
import { DEFAULT_PUBLIC_CACHE_CONTROL, listPublishedPostsQuerySchema as listPublishedPostsQuerySchema2, PostNotFoundError as PostNotFoundError3 } from "@adatechnology/content-contracts";
|
|
961
|
+
var PUBLIC = {
|
|
962
|
+
scope: "public"
|
|
963
|
+
};
|
|
964
|
+
function buildPublicRoutes(params) {
|
|
965
|
+
const { useCases } = params.module;
|
|
966
|
+
const cacheControl = params.module.config.publicCacheControl ?? DEFAULT_PUBLIC_CACHE_CONTROL;
|
|
967
|
+
const cached = /* @__PURE__ */ __name((data) => ({
|
|
968
|
+
kind: "json",
|
|
969
|
+
status: 200,
|
|
970
|
+
body: data,
|
|
971
|
+
headers: {
|
|
972
|
+
"Cache-Control": cacheControl
|
|
973
|
+
}
|
|
974
|
+
}), "cached");
|
|
975
|
+
async function resolveCompany(context) {
|
|
976
|
+
const companyId = await params.companyResolver.resolve({
|
|
977
|
+
headers: context.headers,
|
|
978
|
+
query: context.query
|
|
979
|
+
});
|
|
980
|
+
if (!companyId) throw new PostNotFoundError3("company");
|
|
981
|
+
return companyId;
|
|
982
|
+
}
|
|
983
|
+
__name(resolveCompany, "resolveCompany");
|
|
984
|
+
const routes = [
|
|
985
|
+
{
|
|
986
|
+
...PUBLIC,
|
|
987
|
+
method: "GET",
|
|
988
|
+
path: "/public/posts",
|
|
989
|
+
querySchema: listPublishedPostsQuerySchema2,
|
|
990
|
+
operationId: "listPublishedPosts",
|
|
991
|
+
summary: "Posts publicados, mais recentes primeiro, com filtro por tag",
|
|
992
|
+
async handler(context) {
|
|
993
|
+
const result = await useCases.listPublishedPosts.execute({
|
|
994
|
+
companyId: await resolveCompany(context),
|
|
995
|
+
...context.query
|
|
996
|
+
});
|
|
997
|
+
return cached(result);
|
|
998
|
+
}
|
|
999
|
+
},
|
|
1000
|
+
{
|
|
1001
|
+
...PUBLIC,
|
|
1002
|
+
method: "GET",
|
|
1003
|
+
path: "/public/posts/:slug",
|
|
1004
|
+
operationId: "getPublishedPost",
|
|
1005
|
+
summary: "Post publicado pelo slug; rascunho, agendado futuro e arquivado respondem 404",
|
|
1006
|
+
async handler(context) {
|
|
1007
|
+
const post = await useCases.getPublishedPostBySlug.execute({
|
|
1008
|
+
companyId: await resolveCompany(context),
|
|
1009
|
+
slug: context.params.slug ?? ""
|
|
1010
|
+
});
|
|
1011
|
+
return cached({
|
|
1012
|
+
data: post
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
},
|
|
1016
|
+
{
|
|
1017
|
+
...PUBLIC,
|
|
1018
|
+
method: "GET",
|
|
1019
|
+
path: "/public/tags",
|
|
1020
|
+
operationId: "listPublishedTags",
|
|
1021
|
+
summary: "Tags dos posts publicados, com contagem",
|
|
1022
|
+
async handler(context) {
|
|
1023
|
+
const tags = await useCases.listTags.execute({
|
|
1024
|
+
companyId: await resolveCompany(context),
|
|
1025
|
+
scope: TAG_SCOPE.PUBLIC
|
|
1026
|
+
});
|
|
1027
|
+
return cached({
|
|
1028
|
+
data: tags
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
];
|
|
1033
|
+
const { buildFeed, listSitemapEntries } = useCases;
|
|
1034
|
+
if (!buildFeed || !listSitemapEntries) return routes;
|
|
1035
|
+
const feedRoute = /* @__PURE__ */ __name((path2, format, contentType, operationId) => ({
|
|
1036
|
+
...PUBLIC,
|
|
1037
|
+
method: "GET",
|
|
1038
|
+
path: path2,
|
|
1039
|
+
operationId,
|
|
1040
|
+
summary: `Feed ${format.toUpperCase()} dos posts publicados`,
|
|
1041
|
+
async handler(context) {
|
|
1042
|
+
const body = await buildFeed.execute({
|
|
1043
|
+
companyId: await resolveCompany(context),
|
|
1044
|
+
format
|
|
1045
|
+
});
|
|
1046
|
+
return {
|
|
1047
|
+
kind: "text",
|
|
1048
|
+
status: 200,
|
|
1049
|
+
body,
|
|
1050
|
+
headers: {
|
|
1051
|
+
"Content-Type": contentType,
|
|
1052
|
+
"Cache-Control": cacheControl
|
|
1053
|
+
}
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
}), "feedRoute");
|
|
1057
|
+
return [
|
|
1058
|
+
...routes,
|
|
1059
|
+
feedRoute("/public/feed.xml", FEED_FORMAT.RSS, "application/rss+xml; charset=utf-8", "getRssFeed"),
|
|
1060
|
+
feedRoute("/public/atom.xml", FEED_FORMAT.ATOM, "application/atom+xml; charset=utf-8", "getAtomFeed"),
|
|
1061
|
+
{
|
|
1062
|
+
...PUBLIC,
|
|
1063
|
+
method: "GET",
|
|
1064
|
+
path: "/public/sitemap-entries",
|
|
1065
|
+
operationId: "listSitemapEntries",
|
|
1066
|
+
summary: "Entradas de sitemap (loc, lastmod) dos posts publicados, para o host juntar ao sitemap dele",
|
|
1067
|
+
async handler(context) {
|
|
1068
|
+
return cached({
|
|
1069
|
+
data: await listSitemapEntries.execute({
|
|
1070
|
+
companyId: await resolveCompany(context)
|
|
1071
|
+
})
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
];
|
|
1076
|
+
}
|
|
1077
|
+
__name(buildPublicRoutes, "buildPublicRoutes");
|
|
1078
|
+
|
|
1079
|
+
// src/http/routes.ts
|
|
1080
|
+
function createContentRoutes(params) {
|
|
1081
|
+
const admin = buildAdminRoutes(params.module);
|
|
1082
|
+
if (!params.publicCompanyResolver) return admin;
|
|
1083
|
+
return [
|
|
1084
|
+
...admin,
|
|
1085
|
+
...buildPublicRoutes({
|
|
1086
|
+
module: params.module,
|
|
1087
|
+
companyResolver: params.publicCompanyResolver
|
|
1088
|
+
})
|
|
1089
|
+
];
|
|
1090
|
+
}
|
|
1091
|
+
__name(createContentRoutes, "createContentRoutes");
|
|
1092
|
+
|
|
1093
|
+
// src/runMigrations.ts
|
|
1094
|
+
import { join } from "path";
|
|
1095
|
+
var CONTENT_MIGRATIONS_TABLE = "content_migrations";
|
|
1096
|
+
function contentMigrationsFolder() {
|
|
1097
|
+
return join(__dirname, "migrations");
|
|
1098
|
+
}
|
|
1099
|
+
__name(contentMigrationsFolder, "contentMigrationsFolder");
|
|
1100
|
+
async function runContentMigrations(params) {
|
|
1101
|
+
await params.migrate(params.db, {
|
|
1102
|
+
migrationsFolder: contentMigrationsFolder(),
|
|
1103
|
+
migrationsTable: CONTENT_MIGRATIONS_TABLE
|
|
1104
|
+
});
|
|
1105
|
+
}
|
|
1106
|
+
__name(runContentMigrations, "runContentMigrations");
|
|
1107
|
+
|
|
1108
|
+
// src/testing/inMemoryPostStore.ts
|
|
1109
|
+
import { randomUUID } from "crypto";
|
|
1110
|
+
import { POST_STATUS as POST_STATUS4 } from "@adatechnology/content-contracts";
|
|
1111
|
+
function isPublic(row, now) {
|
|
1112
|
+
const live = row.status === POST_STATUS4.PUBLISHED || row.status === POST_STATUS4.SCHEDULED;
|
|
1113
|
+
return live && row.publishedAt !== null && row.publishedAt <= now;
|
|
1114
|
+
}
|
|
1115
|
+
__name(isPublic, "isPublic");
|
|
1116
|
+
function paginate(rows, page, pageSize) {
|
|
1117
|
+
return {
|
|
1118
|
+
rows: rows.slice((page - 1) * pageSize, page * pageSize).map((row) => ({
|
|
1119
|
+
...row
|
|
1120
|
+
})),
|
|
1121
|
+
total: rows.length
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
__name(paginate, "paginate");
|
|
1125
|
+
var UniqueViolation = class UniqueViolation2 extends Error {
|
|
1126
|
+
static {
|
|
1127
|
+
__name(this, "UniqueViolation");
|
|
1128
|
+
}
|
|
1129
|
+
code = "23505";
|
|
1130
|
+
};
|
|
1131
|
+
function createInMemoryPostStore(seed = []) {
|
|
1132
|
+
const rows = [
|
|
1133
|
+
...seed
|
|
1134
|
+
];
|
|
1135
|
+
const assertUniqueSlug = /* @__PURE__ */ __name((companyId, slug, ownId) => {
|
|
1136
|
+
if (rows.some((row) => row.companyId === companyId && row.slug === slug && row.id !== ownId)) {
|
|
1137
|
+
throw new UniqueViolation('duplicate key value violates unique constraint "idx_posts_company_slug"');
|
|
1138
|
+
}
|
|
1139
|
+
}, "assertUniqueSlug");
|
|
1140
|
+
return {
|
|
1141
|
+
rows,
|
|
1142
|
+
async create(values) {
|
|
1143
|
+
assertUniqueSlug(values.companyId, values.slug);
|
|
1144
|
+
const now = /* @__PURE__ */ new Date();
|
|
1145
|
+
const row = {
|
|
1146
|
+
id: randomUUID(),
|
|
1147
|
+
excerpt: null,
|
|
1148
|
+
body: "",
|
|
1149
|
+
coverImageUrl: null,
|
|
1150
|
+
coverImageAlt: null,
|
|
1151
|
+
tags: [],
|
|
1152
|
+
status: POST_STATUS4.DRAFT,
|
|
1153
|
+
publishedAt: null,
|
|
1154
|
+
authorName: null,
|
|
1155
|
+
seoTitle: null,
|
|
1156
|
+
seoDescription: null,
|
|
1157
|
+
canonicalUrl: null,
|
|
1158
|
+
readingTimeMinutes: 1,
|
|
1159
|
+
createdAt: now,
|
|
1160
|
+
updatedAt: now,
|
|
1161
|
+
...values
|
|
1162
|
+
};
|
|
1163
|
+
rows.push(row);
|
|
1164
|
+
return {
|
|
1165
|
+
...row
|
|
1166
|
+
};
|
|
1167
|
+
},
|
|
1168
|
+
async findById({ companyId, id }) {
|
|
1169
|
+
const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id);
|
|
1170
|
+
return row ? {
|
|
1171
|
+
...row
|
|
1172
|
+
} : void 0;
|
|
1173
|
+
},
|
|
1174
|
+
async findBySlug({ companyId, slug }) {
|
|
1175
|
+
const row = rows.find((candidate) => candidate.companyId === companyId && candidate.slug === slug);
|
|
1176
|
+
return row ? {
|
|
1177
|
+
...row
|
|
1178
|
+
} : void 0;
|
|
1179
|
+
},
|
|
1180
|
+
async findPublicBySlug({ companyId, slug, now }) {
|
|
1181
|
+
const row = rows.find((candidate) => candidate.companyId === companyId && candidate.slug === slug && isPublic(candidate, now));
|
|
1182
|
+
return row ? {
|
|
1183
|
+
...row
|
|
1184
|
+
} : void 0;
|
|
1185
|
+
},
|
|
1186
|
+
async update({ companyId, id, values }) {
|
|
1187
|
+
const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id);
|
|
1188
|
+
if (!row) return void 0;
|
|
1189
|
+
if (values.slug !== void 0) assertUniqueSlug(companyId, values.slug, id);
|
|
1190
|
+
Object.assign(row, values, {
|
|
1191
|
+
updatedAt: new Date(Math.max(Date.now(), row.updatedAt.getTime() + 1))
|
|
1192
|
+
});
|
|
1193
|
+
return {
|
|
1194
|
+
...row
|
|
1195
|
+
};
|
|
1196
|
+
},
|
|
1197
|
+
async listForAdmin(query) {
|
|
1198
|
+
const search = query.search?.toLowerCase();
|
|
1199
|
+
const matched = rows.filter((row) => row.companyId === query.companyId).filter((row) => !query.status || effectiveStatus(row, query.now) === query.status).filter((row) => !query.tag || row.tags.includes(query.tag)).filter((row) => !search || row.title.toLowerCase().includes(search) || row.slug.includes(search)).sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime());
|
|
1200
|
+
return paginate(matched, query.page, query.pageSize);
|
|
1201
|
+
},
|
|
1202
|
+
async listPublic(query) {
|
|
1203
|
+
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));
|
|
1204
|
+
return paginate(matched, query.page, query.pageSize);
|
|
1205
|
+
},
|
|
1206
|
+
async listTags({ companyId, publicAt }) {
|
|
1207
|
+
const counts = /* @__PURE__ */ new Map();
|
|
1208
|
+
for (const row of rows) {
|
|
1209
|
+
if (row.companyId !== companyId || publicAt && !isPublic(row, publicAt)) continue;
|
|
1210
|
+
for (const tag of row.tags) counts.set(tag, (counts.get(tag) ?? 0) + 1);
|
|
1211
|
+
}
|
|
1212
|
+
return [
|
|
1213
|
+
...counts.entries()
|
|
1214
|
+
].map(([tag, count]) => ({
|
|
1215
|
+
tag,
|
|
1216
|
+
count
|
|
1217
|
+
})).sort((left, right) => right.count - left.count || left.tag.localeCompare(right.tag));
|
|
1218
|
+
}
|
|
1219
|
+
};
|
|
1220
|
+
}
|
|
1221
|
+
__name(createInMemoryPostStore, "createInMemoryPostStore");
|
|
1222
|
+
export {
|
|
1223
|
+
ArchivePostUseCase,
|
|
1224
|
+
BuildFeedUseCase,
|
|
1225
|
+
CONTENT_MIGRATIONS_TABLE,
|
|
1226
|
+
COVER_IMAGE,
|
|
1227
|
+
CreatePostUseCase,
|
|
1228
|
+
FEED_FORMAT,
|
|
1229
|
+
GetPostUseCase,
|
|
1230
|
+
GetPublishedPostBySlugUseCase,
|
|
1231
|
+
ListPostsUseCase,
|
|
1232
|
+
ListPublishedPostsUseCase,
|
|
1233
|
+
ListSitemapEntriesUseCase,
|
|
1234
|
+
ListTagsUseCase,
|
|
1235
|
+
PostRepository,
|
|
1236
|
+
PublishPostUseCase,
|
|
1237
|
+
TAG_SCOPE,
|
|
1238
|
+
UnpublishPostUseCase,
|
|
1239
|
+
UpdatePostUseCase,
|
|
1240
|
+
UploadCoverImageUseCase,
|
|
1241
|
+
contentMigrationsFolder,
|
|
1242
|
+
contentSchema,
|
|
1243
|
+
createContentModule,
|
|
1244
|
+
createContentRoutes,
|
|
1245
|
+
createInMemoryPostStore,
|
|
1246
|
+
posts,
|
|
1247
|
+
runContentMigrations
|
|
1248
|
+
};
|
|
1249
|
+
//# sourceMappingURL=index.js.map
|