@adatechnology/content-contracts 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.cjs ADDED
@@ -0,0 +1,1451 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ CONTENT_ERROR_CODES: () => CONTENT_ERROR_CODES,
25
+ ConfigMissingError: () => ConfigMissingError,
26
+ ContentError: () => ContentError,
27
+ DEFAULT_ADMIN_SCOPES: () => DEFAULT_ADMIN_SCOPES,
28
+ DEFAULT_LINK_REL: () => DEFAULT_LINK_REL,
29
+ DEFAULT_POST_PATH_TEMPLATE: () => DEFAULT_POST_PATH_TEMPLATE,
30
+ DEFAULT_PUBLIC_CACHE_CONTROL: () => DEFAULT_PUBLIC_CACHE_CONTROL,
31
+ DEFAULT_SHORT_SLUG_LENGTH: () => DEFAULT_SHORT_SLUG_LENGTH,
32
+ DEFAULT_WORDS_PER_MINUTE: () => DEFAULT_WORDS_PER_MINUTE,
33
+ DuplicateSlugError: () => DuplicateSlugError,
34
+ ImageStorageDisabledError: () => ImageStorageDisabledError,
35
+ InvalidCoverImageError: () => InvalidCoverImageError,
36
+ InvalidSlugError: () => InvalidSlugError,
37
+ NotATemplateError: () => NotATemplateError,
38
+ POST_EVENT: () => POST_EVENT,
39
+ POST_LIMITS: () => POST_LIMITS,
40
+ POST_SORT_FIELDS: () => POST_SORT_FIELDS,
41
+ POST_STATUS: () => POST_STATUS,
42
+ POST_STATUSES: () => POST_STATUSES,
43
+ PT_BR_STOP_WORDS: () => PT_BR_STOP_WORDS,
44
+ PostNotFoundError: () => PostNotFoundError,
45
+ PostNotPublishedError: () => PostNotPublishedError,
46
+ RECURRENCE_FREQUENCIES: () => RECURRENCE_FREQUENCIES,
47
+ RECURRENCE_FREQUENCY: () => RECURRENCE_FREQUENCY,
48
+ RecurrenceNotFoundError: () => RecurrenceNotFoundError,
49
+ RepublishDateInFutureError: () => RepublishDateInFutureError,
50
+ SHORT_ID_LENGTH: () => SHORT_ID_LENGTH,
51
+ SLUG_MAX_LENGTH: () => SLUG_MAX_LENGTH,
52
+ TAGS_MAX_COUNT: () => TAGS_MAX_COUNT,
53
+ TAG_MAX_LENGTH: () => TAG_MAX_LENGTH,
54
+ TemplateNotPublishableError: () => TemplateNotPublishableError,
55
+ buildAtomFeed: () => buildAtomFeed,
56
+ buildExcerpt: () => buildExcerpt,
57
+ buildPostPath: () => buildPostPath,
58
+ buildPostRef: () => buildPostRef,
59
+ buildPostUrl: () => buildPostUrl,
60
+ buildRssFeed: () => buildRssFeed,
61
+ buildShortSlug: () => buildShortSlug,
62
+ buildSitemapXml: () => buildSitemapXml,
63
+ buildTagLabels: () => buildTagLabels,
64
+ countWords: () => countWords,
65
+ createFromTemplateSchema: () => createFromTemplateSchema,
66
+ createHeadingIdGenerator: () => createHeadingIdGenerator,
67
+ createPostSchema: () => createPostSchema,
68
+ createRecurrenceSchema: () => createRecurrenceSchema,
69
+ documentToPlainText: () => documentToPlainText,
70
+ escapeHtml: () => escapeHtml,
71
+ escapeXml: () => escapeXml,
72
+ estimateReadingTimeMinutes: () => estimateReadingTimeMinutes,
73
+ formatTagLabel: () => formatTagLabel,
74
+ httpUrlSchema: () => httpUrlSchema,
75
+ inlineToPlainText: () => inlineToPlainText,
76
+ isAbsoluteHttpUrl: () => isAbsoluteHttpUrl,
77
+ isCanonicalPostRef: () => isCanonicalPostRef,
78
+ isPostStatus: () => isPostStatus,
79
+ isShortId: () => isShortId,
80
+ isValidSlug: () => isValidSlug,
81
+ listPostsQuerySchema: () => listPostsQuerySchema,
82
+ listPublishedPostsQuerySchema: () => listPublishedPostsQuerySchema,
83
+ markdownToPlainText: () => markdownToPlainText,
84
+ normalizeTag: () => normalizeTag,
85
+ normalizeTags: () => normalizeTags,
86
+ parseInline: () => parseInline,
87
+ parseMarkdown: () => parseMarkdown,
88
+ parsePostPath: () => parsePostPath,
89
+ parsePostRef: () => parsePostRef,
90
+ postFieldsSchema: () => postFieldsSchema,
91
+ publishPostSchema: () => publishPostSchema,
92
+ renderMarkdownDocument: () => renderMarkdownDocument,
93
+ renderMarkdownToHtml: () => renderMarkdownToHtml,
94
+ republishPostSchema: () => republishPostSchema,
95
+ resolveHeadingLevel: () => resolveHeadingLevel,
96
+ sanitizeImageUrl: () => sanitizeImageUrl,
97
+ sanitizeLinkUrl: () => sanitizeLinkUrl,
98
+ saveAsTemplateSchema: () => saveAsTemplateSchema,
99
+ slugSchema: () => slugSchema,
100
+ slugify: () => slugify,
101
+ updatePostSchema: () => updatePostSchema,
102
+ updateRecurrenceSchema: () => updateRecurrenceSchema,
103
+ withSlugSuffix: () => withSlugSuffix
104
+ });
105
+ module.exports = __toCommonJS(index_exports);
106
+
107
+ // src/content.types.ts
108
+ var POST_STATUS = {
109
+ DRAFT: "draft",
110
+ SCHEDULED: "scheduled",
111
+ PUBLISHED: "published",
112
+ ARCHIVED: "archived"
113
+ };
114
+ var POST_STATUSES = Object.values(POST_STATUS);
115
+ function isPostStatus(value) {
116
+ return typeof value === "string" && POST_STATUSES.includes(value);
117
+ }
118
+ __name(isPostStatus, "isPostStatus");
119
+ var RECURRENCE_FREQUENCY = {
120
+ WEEKLY: "weekly",
121
+ MONTHLY: "monthly"
122
+ };
123
+ var RECURRENCE_FREQUENCIES = Object.values(RECURRENCE_FREQUENCY);
124
+
125
+ // src/errors.ts
126
+ var ContentError = class extends Error {
127
+ static {
128
+ __name(this, "ContentError");
129
+ }
130
+ statusCode;
131
+ code;
132
+ details;
133
+ constructor(message, statusCode, code, details) {
134
+ super(message), this.statusCode = statusCode, this.code = code, this.details = details;
135
+ this.name = "ContentError";
136
+ }
137
+ };
138
+ var CONTENT_ERROR_CODES = {
139
+ POST_NOT_FOUND: "CONTENT_POST_NOT_FOUND",
140
+ DUPLICATE_SLUG: "CONTENT_DUPLICATE_SLUG",
141
+ INVALID_SLUG: "CONTENT_INVALID_SLUG",
142
+ CONFIG_MISSING: "CONTENT_CONFIG_MISSING",
143
+ INVALID_IMAGE: "CONTENT_INVALID_IMAGE",
144
+ IMAGE_STORAGE_DISABLED: "CONTENT_IMAGE_STORAGE_DISABLED",
145
+ NOT_A_TEMPLATE: "CONTENT_NOT_A_TEMPLATE",
146
+ TEMPLATE_NOT_PUBLISHABLE: "CONTENT_TEMPLATE_NOT_PUBLISHABLE",
147
+ NOT_PUBLISHED: "CONTENT_NOT_PUBLISHED",
148
+ REPUBLISH_DATE_IN_FUTURE: "CONTENT_REPUBLISH_DATE_IN_FUTURE",
149
+ RECURRENCE_NOT_FOUND: "CONTENT_RECURRENCE_NOT_FOUND"
150
+ };
151
+ var PostNotFoundError = class extends ContentError {
152
+ static {
153
+ __name(this, "PostNotFoundError");
154
+ }
155
+ reference;
156
+ constructor(reference) {
157
+ super("Post n\xE3o encontrado.", 404, CONTENT_ERROR_CODES.POST_NOT_FOUND, {
158
+ reference
159
+ }), this.reference = reference;
160
+ }
161
+ };
162
+ var DuplicateSlugError = class extends ContentError {
163
+ static {
164
+ __name(this, "DuplicateSlugError");
165
+ }
166
+ slug;
167
+ constructor(slug) {
168
+ super("J\xE1 existe post com este endere\xE7o (slug).", 409, CONTENT_ERROR_CODES.DUPLICATE_SLUG, {
169
+ slug
170
+ }), this.slug = slug;
171
+ }
172
+ };
173
+ var InvalidSlugError = class extends ContentError {
174
+ static {
175
+ __name(this, "InvalidSlugError");
176
+ }
177
+ slug;
178
+ constructor(slug) {
179
+ super("Endere\xE7o (slug) inv\xE1lido.", 400, CONTENT_ERROR_CODES.INVALID_SLUG, {
180
+ slug
181
+ }), this.slug = slug;
182
+ }
183
+ };
184
+ var ConfigMissingError = class extends ContentError {
185
+ static {
186
+ __name(this, "ConfigMissingError");
187
+ }
188
+ field;
189
+ constructor(field) {
190
+ super(`Configura\xE7\xE3o ausente ou inv\xE1lida: ${field}.`, 500, CONTENT_ERROR_CODES.CONFIG_MISSING, {
191
+ field
192
+ }), this.field = field;
193
+ }
194
+ };
195
+ var InvalidCoverImageError = class extends ContentError {
196
+ static {
197
+ __name(this, "InvalidCoverImageError");
198
+ }
199
+ reason;
200
+ constructor(reason) {
201
+ super("Imagem de capa inv\xE1lida.", 400, CONTENT_ERROR_CODES.INVALID_IMAGE, {
202
+ reason
203
+ }), this.reason = reason;
204
+ }
205
+ };
206
+ var ImageStorageDisabledError = class extends ContentError {
207
+ static {
208
+ __name(this, "ImageStorageDisabledError");
209
+ }
210
+ constructor() {
211
+ super("Envio de imagem n\xE3o configurado.", 501, CONTENT_ERROR_CODES.IMAGE_STORAGE_DISABLED);
212
+ }
213
+ };
214
+ var NotATemplateError = class extends ContentError {
215
+ static {
216
+ __name(this, "NotATemplateError");
217
+ }
218
+ postId;
219
+ constructor(postId) {
220
+ super("Este post n\xE3o \xE9 um modelo.", 422, CONTENT_ERROR_CODES.NOT_A_TEMPLATE, {
221
+ postId
222
+ }), this.postId = postId;
223
+ }
224
+ };
225
+ var TemplateNotPublishableError = class extends ContentError {
226
+ static {
227
+ __name(this, "TemplateNotPublishableError");
228
+ }
229
+ postId;
230
+ constructor(postId) {
231
+ super("Modelo n\xE3o pode ser publicado: crie um post a partir dele.", 422, CONTENT_ERROR_CODES.TEMPLATE_NOT_PUBLISHABLE, {
232
+ postId
233
+ }), this.postId = postId;
234
+ }
235
+ };
236
+ var PostNotPublishedError = class extends ContentError {
237
+ static {
238
+ __name(this, "PostNotPublishedError");
239
+ }
240
+ postId;
241
+ constructor(postId) {
242
+ super("S\xF3 post publicado pode ser republicado.", 422, CONTENT_ERROR_CODES.NOT_PUBLISHED, {
243
+ postId
244
+ }), this.postId = postId;
245
+ }
246
+ };
247
+ var RepublishDateInFutureError = class extends ContentError {
248
+ static {
249
+ __name(this, "RepublishDateInFutureError");
250
+ }
251
+ constructor() {
252
+ super("A nova data n\xE3o pode ser futura: o post sairia do ar at\xE9 l\xE1.", 422, CONTENT_ERROR_CODES.REPUBLISH_DATE_IN_FUTURE);
253
+ }
254
+ };
255
+ var RecurrenceNotFoundError = class extends ContentError {
256
+ static {
257
+ __name(this, "RecurrenceNotFoundError");
258
+ }
259
+ reference;
260
+ constructor(reference) {
261
+ super("Recorr\xEAncia n\xE3o encontrada.", 404, CONTENT_ERROR_CODES.RECURRENCE_NOT_FOUND, {
262
+ reference
263
+ }), this.reference = reference;
264
+ }
265
+ };
266
+
267
+ // src/schemas.ts
268
+ var import_zod = require("zod");
269
+
270
+ // src/slugify.ts
271
+ var SLUG_MAX_LENGTH = 120;
272
+ var SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
273
+ function slugify(value) {
274
+ const base = value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
275
+ if (base.length <= SLUG_MAX_LENGTH) return base;
276
+ const truncated = base.slice(0, SLUG_MAX_LENGTH);
277
+ const lastHyphen = truncated.lastIndexOf("-");
278
+ return (lastHyphen > 0 ? truncated.slice(0, lastHyphen) : truncated).replace(/-+$/g, "");
279
+ }
280
+ __name(slugify, "slugify");
281
+ function isValidSlug(value) {
282
+ return value.length > 0 && value.length <= SLUG_MAX_LENGTH && SLUG_PATTERN.test(value);
283
+ }
284
+ __name(isValidSlug, "isValidSlug");
285
+ function withSlugSuffix(slug, attempt) {
286
+ if (attempt <= 1) return slug;
287
+ const suffix = `-${attempt}`;
288
+ return `${slug.slice(0, SLUG_MAX_LENGTH - suffix.length).replace(/-+$/g, "")}${suffix}`;
289
+ }
290
+ __name(withSlugSuffix, "withSlugSuffix");
291
+ var DEFAULT_SHORT_SLUG_LENGTH = 60;
292
+ var PT_BR_STOP_WORDS = [
293
+ "a",
294
+ "as",
295
+ "o",
296
+ "os",
297
+ "um",
298
+ "uma",
299
+ "uns",
300
+ "umas",
301
+ "de",
302
+ "da",
303
+ "das",
304
+ "do",
305
+ "dos",
306
+ "em",
307
+ "na",
308
+ "nas",
309
+ "no",
310
+ "nos",
311
+ "e",
312
+ "ou",
313
+ "para",
314
+ "pra",
315
+ "pro",
316
+ "por",
317
+ "pelo",
318
+ "pela",
319
+ "pelos",
320
+ "pelas",
321
+ "com",
322
+ "sem",
323
+ "ao",
324
+ "aos",
325
+ "que",
326
+ "se"
327
+ ];
328
+ function buildShortSlug(title, options = {}) {
329
+ const maxLength = Math.min(options.maxLength ?? DEFAULT_SHORT_SLUG_LENGTH, SLUG_MAX_LENGTH);
330
+ const words = slugify(title).split("-").filter(Boolean);
331
+ const stop = new Set(options.stopWords === false ? [] : options.stopWords ?? PT_BR_STOP_WORDS);
332
+ const meaningful = words.filter((word) => !stop.has(word));
333
+ const kept = meaningful.length > 0 ? meaningful : words;
334
+ let slug = "";
335
+ for (const word of kept) {
336
+ const next = slug ? `${slug}-${word}` : word;
337
+ if (next.length > maxLength) break;
338
+ slug = next;
339
+ }
340
+ return slug || (kept[0] ?? "").slice(0, maxLength).replace(/-+$/g, "");
341
+ }
342
+ __name(buildShortSlug, "buildShortSlug");
343
+
344
+ // src/tags.ts
345
+ var TAG_MAX_LENGTH = 40;
346
+ var TAGS_MAX_COUNT = 20;
347
+ function normalizeTag(value) {
348
+ return value.trim().replace(/\s+/g, " ").toLowerCase().slice(0, TAG_MAX_LENGTH);
349
+ }
350
+ __name(normalizeTag, "normalizeTag");
351
+ function normalizeTags(values) {
352
+ const seen = /* @__PURE__ */ new Set();
353
+ const result = [];
354
+ for (const value of values) {
355
+ const tag = normalizeTag(value);
356
+ if (!tag || seen.has(tag)) continue;
357
+ seen.add(tag);
358
+ result.push(tag);
359
+ }
360
+ return result.slice(0, TAGS_MAX_COUNT);
361
+ }
362
+ __name(normalizeTags, "normalizeTags");
363
+ function buildTagLabels(params) {
364
+ const labels = {};
365
+ for (const value of params.typed) {
366
+ const tag = normalizeTag(value);
367
+ if (!tag) continue;
368
+ const typed = value.trim().replace(/\s+/g, " ").slice(0, TAG_MAX_LENGTH);
369
+ const label = params.explicit?.[tag]?.trim() || (typed !== tag ? typed : void 0) || params.previous?.[tag];
370
+ if (label && label !== tag) labels[tag] = label;
371
+ }
372
+ return labels;
373
+ }
374
+ __name(buildTagLabels, "buildTagLabels");
375
+ function formatTagLabel(tag, labels) {
376
+ const stored = labels?.[tag];
377
+ if (stored) return stored;
378
+ const spaced = tag.replace(/-+/g, " ").trim();
379
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
380
+ }
381
+ __name(formatTagLabel, "formatTagLabel");
382
+
383
+ // src/schemas.ts
384
+ var POST_LIMITS = {
385
+ TITLE: 200,
386
+ EXCERPT: 500,
387
+ BODY: 1e5,
388
+ URL: 2048,
389
+ IMAGE_ALT: 300,
390
+ AUTHOR_NAME: 120,
391
+ SEO_TITLE: 200,
392
+ SEO_DESCRIPTION: 320,
393
+ SEARCH: 120,
394
+ ADMIN_PAGE_SIZE: 100,
395
+ PUBLIC_PAGE_SIZE: 50
396
+ };
397
+ var slugSchema = import_zod.z.string().trim().toLowerCase().max(SLUG_MAX_LENGTH).refine(isValidSlug, {
398
+ message: "Use letras min\xFAsculas, n\xFAmeros e h\xEDfen."
399
+ });
400
+ var httpUrlSchema = import_zod.z.string().trim().max(POST_LIMITS.URL).url().refine((value) => /^https?:\/\//i.test(value), {
401
+ message: "Use um endere\xE7o http(s)."
402
+ });
403
+ var optionalText = /* @__PURE__ */ __name((max) => import_zod.z.string().trim().max(max).nullable().optional(), "optionalText");
404
+ var postFieldsSchema = import_zod.z.object({
405
+ title: import_zod.z.string().trim().min(1).max(POST_LIMITS.TITLE),
406
+ slug: slugSchema.optional(),
407
+ excerpt: optionalText(POST_LIMITS.EXCERPT),
408
+ body: import_zod.z.string().max(POST_LIMITS.BODY).default(""),
409
+ coverImageUrl: httpUrlSchema.nullable().optional(),
410
+ coverImageAlt: optionalText(POST_LIMITS.IMAGE_ALT),
411
+ tags: import_zod.z.array(import_zod.z.string().trim().min(1).max(TAG_MAX_LENGTH)).max(TAGS_MAX_COUNT).optional(),
412
+ /** Rótulo de exibição por tag (chave = tag normalizada). Sem rótulo, vale o texto digitado. */
413
+ tagLabels: import_zod.z.record(import_zod.z.string().trim().min(1).max(TAG_MAX_LENGTH)).optional(),
414
+ authorName: optionalText(POST_LIMITS.AUTHOR_NAME),
415
+ seoTitle: optionalText(POST_LIMITS.SEO_TITLE),
416
+ seoDescription: optionalText(POST_LIMITS.SEO_DESCRIPTION),
417
+ canonicalUrl: httpUrlSchema.nullable().optional()
418
+ });
419
+ var createPostSchema = postFieldsSchema.strict();
420
+ var updatePostSchema = postFieldsSchema.extend({
421
+ body: import_zod.z.string().max(POST_LIMITS.BODY)
422
+ }).partial().strict();
423
+ var publishPostSchema = import_zod.z.object({
424
+ publishedAt: import_zod.z.string().datetime({
425
+ offset: true
426
+ }).optional()
427
+ }).strict();
428
+ var pageSchema = import_zod.z.coerce.number().int().min(1).max(1e4).default(1);
429
+ var POST_SORT_FIELDS = [
430
+ "title",
431
+ "status",
432
+ "publishedAt",
433
+ "updatedAt"
434
+ ];
435
+ var listPostsQuerySchema = import_zod.z.object({
436
+ page: pageSchema,
437
+ pageSize: import_zod.z.coerce.number().int().min(1).max(POST_LIMITS.ADMIN_PAGE_SIZE).default(20),
438
+ status: import_zod.z.enum(POST_STATUSES).optional(),
439
+ /** Uma tag, ou várias separadas por vírgula (basta ter UMA delas). */
440
+ tag: import_zod.z.string().trim().min(1).max(TAG_MAX_LENGTH * TAGS_MAX_COUNT).optional(),
441
+ search: import_zod.z.string().trim().min(1).max(POST_LIMITS.SEARCH).optional(),
442
+ /** Padrão: `updatedAt` (o que o painel mexeu por último). */
443
+ sort: import_zod.z.enum(POST_SORT_FIELDS).default("updatedAt"),
444
+ order: import_zod.z.enum([
445
+ "asc",
446
+ "desc"
447
+ ]).default("desc"),
448
+ /** `true`: só modelos. Ausente/`false`: só posts (modelo nunca aparece misturado na lista). */
449
+ isTemplate: import_zod.z.union([
450
+ import_zod.z.boolean(),
451
+ import_zod.z.enum([
452
+ "true",
453
+ "false"
454
+ ])
455
+ ]).transform((value) => value === true || value === "true").optional()
456
+ });
457
+ var listPublishedPostsQuerySchema = import_zod.z.object({
458
+ page: pageSchema,
459
+ pageSize: import_zod.z.coerce.number().int().min(1).max(POST_LIMITS.PUBLIC_PAGE_SIZE).default(10),
460
+ tag: import_zod.z.string().trim().min(1).max(TAG_MAX_LENGTH).optional()
461
+ });
462
+ var isoInstant = import_zod.z.string().datetime({
463
+ offset: true
464
+ });
465
+ var saveAsTemplateSchema = import_zod.z.object({
466
+ title: import_zod.z.string().trim().min(1).max(POST_LIMITS.TITLE).optional()
467
+ }).strict();
468
+ var createFromTemplateSchema = import_zod.z.object({
469
+ title: import_zod.z.string().trim().min(1).max(POST_LIMITS.TITLE).optional(),
470
+ slug: slugSchema.optional()
471
+ }).strict();
472
+ var republishPostSchema = import_zod.z.object({
473
+ publishedAt: isoInstant.optional()
474
+ }).strict();
475
+ var createRecurrenceSchema = import_zod.z.object({
476
+ templateId: import_zod.z.string().uuid(),
477
+ frequency: import_zod.z.enum(RECURRENCE_FREQUENCIES),
478
+ /** Primeira publicação automática. */
479
+ startsAt: isoInstant
480
+ }).strict();
481
+ var updateRecurrenceSchema = import_zod.z.object({
482
+ isActive: import_zod.z.boolean().optional(),
483
+ nextRunAt: isoInstant.optional()
484
+ }).strict();
485
+
486
+ // src/providers.ts
487
+ var POST_EVENT = {
488
+ CREATED: "created",
489
+ UPDATED: "updated",
490
+ PUBLISHED: "published",
491
+ UNPUBLISHED: "unpublished",
492
+ ARCHIVED: "archived",
493
+ REPUBLISHED: "republished"
494
+ };
495
+ var DEFAULT_ADMIN_SCOPES = [
496
+ "content:admin"
497
+ ];
498
+ var DEFAULT_PUBLIC_CACHE_CONTROL = "public, max-age=60, s-maxage=300, stale-while-revalidate=600";
499
+
500
+ // src/postPath.ts
501
+ var SHORT_ID_LENGTH = 6;
502
+ var SHORT_ID_PATTERN = /^[0-9a-z]{6}$/;
503
+ var REF_PATTERN = /^([0-9a-z]{6})-(.+)$/;
504
+ function isShortId(value) {
505
+ return SHORT_ID_PATTERN.test(value);
506
+ }
507
+ __name(isShortId, "isShortId");
508
+ function buildPostRef(params) {
509
+ return `${params.shortId}-${params.slug}`;
510
+ }
511
+ __name(buildPostRef, "buildPostRef");
512
+ function buildPostPath(params) {
513
+ const base = params.basePath.replace(/\/+$/g, "");
514
+ return `${base}/${encodeURIComponent(buildPostRef(params))}`;
515
+ }
516
+ __name(buildPostPath, "buildPostPath");
517
+ function parsePostRef(ref) {
518
+ const slug = ref.trim().toLowerCase();
519
+ const match = REF_PATTERN.exec(slug);
520
+ return match?.[1] ? {
521
+ shortId: match[1],
522
+ slug
523
+ } : {
524
+ slug
525
+ };
526
+ }
527
+ __name(parsePostRef, "parsePostRef");
528
+ function parsePostPath(params) {
529
+ const base = params.basePath.replace(/\/+$/g, "");
530
+ const clean = params.path.split(/[?#]/)[0] ?? "";
531
+ if (!clean.startsWith(`${base}/`)) return void 0;
532
+ const rest = clean.slice(base.length + 1).replace(/\/+$/g, "");
533
+ if (!rest || rest.includes("/")) return void 0;
534
+ try {
535
+ return parsePostRef(decodeURIComponent(rest));
536
+ } catch {
537
+ return void 0;
538
+ }
539
+ }
540
+ __name(parsePostPath, "parsePostPath");
541
+ function isCanonicalPostRef(params) {
542
+ return params.ref.trim().toLowerCase() === buildPostRef(params);
543
+ }
544
+ __name(isCanonicalPostRef, "isCanonicalPostRef");
545
+
546
+ // src/markdown/sanitizeUrl.ts
547
+ var LINK_SCHEMES = /* @__PURE__ */ new Set([
548
+ "http",
549
+ "https",
550
+ "mailto",
551
+ "tel"
552
+ ]);
553
+ var IMAGE_SCHEMES = /* @__PURE__ */ new Set([
554
+ "http",
555
+ "https"
556
+ ]);
557
+ var SCHEME_PATTERN = /^([a-z][a-z0-9+.-]*):/i;
558
+ var INVISIBLE_PATTERN = new RegExp(
559
+ // eslint-disable-next-line no-control-regex -- casar caractere de controle é o objetivo
560
+ "[\\u0000-\\u0020\\u007f-\\u009f\\u00ad\\u200b-\\u200f\\u2028\\u2029\\ufeff]+",
561
+ "g"
562
+ );
563
+ function sanitize(url, allowedSchemes) {
564
+ const normalized = url.replace(INVISIBLE_PATTERN, "");
565
+ if (!normalized) return void 0;
566
+ const scheme = SCHEME_PATTERN.exec(normalized)?.[1];
567
+ if (scheme === void 0) return normalized;
568
+ return allowedSchemes.has(scheme.toLowerCase()) ? normalized : void 0;
569
+ }
570
+ __name(sanitize, "sanitize");
571
+ function sanitizeLinkUrl(url) {
572
+ return sanitize(url, LINK_SCHEMES);
573
+ }
574
+ __name(sanitizeLinkUrl, "sanitizeLinkUrl");
575
+ function sanitizeImageUrl(url) {
576
+ return sanitize(url, IMAGE_SCHEMES);
577
+ }
578
+ __name(sanitizeImageUrl, "sanitizeImageUrl");
579
+ function isAbsoluteHttpUrl(url) {
580
+ return /^https?:\/\//i.test(url) || url.startsWith("//");
581
+ }
582
+ __name(isAbsoluteHttpUrl, "isAbsoluteHttpUrl");
583
+
584
+ // src/markdown/parseInline.ts
585
+ var MAX_NESTING = 8;
586
+ var MAX_BRACKET_SCAN = 2e3;
587
+ var ESCAPABLE = new Set("\\`*_{}[]()#+-.!|~<>\"'");
588
+ var DELIMITERS = [
589
+ {
590
+ marker: "**",
591
+ type: "strong"
592
+ },
593
+ {
594
+ marker: "__",
595
+ type: "strong"
596
+ },
597
+ {
598
+ marker: "~~",
599
+ type: "strikethrough"
600
+ },
601
+ {
602
+ marker: "*",
603
+ type: "emphasis"
604
+ },
605
+ {
606
+ marker: "_",
607
+ type: "emphasis"
608
+ }
609
+ ];
610
+ function parseInline(text, depth = 0) {
611
+ return new InlineParser({
612
+ text,
613
+ depth,
614
+ noCloserFrom: /* @__PURE__ */ new Map()
615
+ }).parse();
616
+ }
617
+ __name(parseInline, "parseInline");
618
+ function isWordCharacter(character) {
619
+ return character !== void 0 && /[\p{L}\p{N}]/u.test(character);
620
+ }
621
+ __name(isWordCharacter, "isWordCharacter");
622
+ function isWhitespace(character) {
623
+ return character === void 0 || /\s/.test(character);
624
+ }
625
+ __name(isWhitespace, "isWhitespace");
626
+ var InlineParser = class InlineParser2 {
627
+ static {
628
+ __name(this, "InlineParser");
629
+ }
630
+ state;
631
+ nodes = [];
632
+ buffer = "";
633
+ position = 0;
634
+ constructor(state) {
635
+ this.state = state;
636
+ }
637
+ parse() {
638
+ const { text } = this.state;
639
+ while (this.position < text.length) {
640
+ if (!this.tryToken()) {
641
+ this.buffer += text[this.position];
642
+ this.position += 1;
643
+ }
644
+ }
645
+ this.flush();
646
+ return this.nodes;
647
+ }
648
+ tryToken() {
649
+ const character = this.state.text[this.position];
650
+ if (character === "\\") return this.tryEscape();
651
+ if (character === "\n") return this.tryLineBreak();
652
+ if (character === "`") return this.tryCodeSpan();
653
+ if (character === "!" && this.state.text[this.position + 1] === "[") return this.tryLinkOrImage(true);
654
+ if (character === "[") return this.tryLinkOrImage(false);
655
+ if (character === "<") return this.tryAutolink();
656
+ if (character === "*" || character === "_" || character === "~") return this.tryDelimited();
657
+ return false;
658
+ }
659
+ push(node) {
660
+ this.flush();
661
+ this.nodes.push(node);
662
+ }
663
+ flush() {
664
+ if (!this.buffer) return;
665
+ this.nodes.push({
666
+ type: "text",
667
+ value: this.buffer
668
+ });
669
+ this.buffer = "";
670
+ }
671
+ tryEscape() {
672
+ const next = this.state.text[this.position + 1];
673
+ if (next === "\n") {
674
+ this.push({
675
+ type: "break"
676
+ });
677
+ this.position += 2;
678
+ return true;
679
+ }
680
+ if (next === void 0 || !ESCAPABLE.has(next)) return false;
681
+ this.buffer += next;
682
+ this.position += 2;
683
+ return true;
684
+ }
685
+ /** Dois espaços antes da quebra = `<br>`; quebra simples vira espaço, como no CommonMark. */
686
+ tryLineBreak() {
687
+ if (this.buffer.endsWith(" ")) {
688
+ this.buffer = this.buffer.replace(/ +$/, "");
689
+ this.push({
690
+ type: "break"
691
+ });
692
+ } else {
693
+ this.buffer = `${this.buffer.replace(/ +$/, "")} `;
694
+ }
695
+ this.position += 1;
696
+ return true;
697
+ }
698
+ tryCodeSpan() {
699
+ const { text } = this.state;
700
+ let runEnd = this.position;
701
+ while (text[runEnd] === "`") runEnd += 1;
702
+ const run = text.slice(this.position, runEnd);
703
+ const memoKey = `code:${run.length}`;
704
+ if ((this.state.noCloserFrom.get(memoKey) ?? Infinity) <= runEnd) return this.literal(run);
705
+ let search = runEnd;
706
+ while (true) {
707
+ const found = text.indexOf(run, search);
708
+ if (found === -1) {
709
+ this.state.noCloserFrom.set(memoKey, runEnd);
710
+ return this.literal(run);
711
+ }
712
+ const closerEnd = found + run.length;
713
+ if (text[closerEnd] === "`" || text[found - 1] === "`") {
714
+ search = closerEnd;
715
+ while (text[search] === "`") search += 1;
716
+ continue;
717
+ }
718
+ let value = text.slice(runEnd, found).replace(/\n/g, " ");
719
+ if (value.length > 2 && value.startsWith(" ") && value.endsWith(" ") && value.trim()) value = value.slice(1, -1);
720
+ this.push({
721
+ type: "inlineCode",
722
+ value
723
+ });
724
+ this.position = closerEnd;
725
+ return true;
726
+ }
727
+ }
728
+ literal(value) {
729
+ this.buffer += value;
730
+ this.position += value.length;
731
+ return true;
732
+ }
733
+ tryLinkOrImage(isImage) {
734
+ const { text } = this.state;
735
+ const open = this.position + (isImage ? 1 : 0);
736
+ const close = findClosingBracket(text, open);
737
+ if (close === void 0 || text[close + 1] !== "(") return false;
738
+ const destination = parseDestination(text, close + 2);
739
+ if (!destination) return false;
740
+ const label = text.slice(open + 1, close);
741
+ this.position = destination.end;
742
+ if (isImage) {
743
+ this.pushImage(label, destination);
744
+ return true;
745
+ }
746
+ const children = this.parseNested(label);
747
+ const href = sanitizeLinkUrl(destination.url);
748
+ if (!href) {
749
+ this.flush();
750
+ this.nodes.push(...children);
751
+ return true;
752
+ }
753
+ this.push({
754
+ type: "link",
755
+ href,
756
+ ...destination.title ? {
757
+ title: destination.title
758
+ } : {},
759
+ children
760
+ });
761
+ return true;
762
+ }
763
+ pushImage(alt, destination) {
764
+ const plainAlt = alt.replace(/[\\*_`~[\]]/g, "");
765
+ const src = sanitizeImageUrl(destination.url);
766
+ if (!src) {
767
+ this.buffer += plainAlt;
768
+ return;
769
+ }
770
+ this.push({
771
+ type: "image",
772
+ src,
773
+ alt: plainAlt,
774
+ ...destination.title ? {
775
+ title: destination.title
776
+ } : {}
777
+ });
778
+ }
779
+ tryAutolink() {
780
+ const { text } = this.state;
781
+ const close = text.indexOf(">", this.position);
782
+ if (close === -1 || close - this.position > MAX_BRACKET_SCAN) return false;
783
+ const candidate = text.slice(this.position + 1, close);
784
+ if (!/^(https?:\/\/|mailto:)[^\s<>]+$/i.test(candidate)) return false;
785
+ const href = sanitizeLinkUrl(candidate);
786
+ if (!href) return false;
787
+ this.push({
788
+ type: "link",
789
+ href,
790
+ children: [
791
+ {
792
+ type: "text",
793
+ value: candidate
794
+ }
795
+ ]
796
+ });
797
+ this.position = close + 1;
798
+ return true;
799
+ }
800
+ tryDelimited() {
801
+ const { text } = this.state;
802
+ const rule = DELIMITERS.find((candidate) => text.startsWith(candidate.marker, this.position));
803
+ if (!rule || this.state.depth >= MAX_NESTING) return false;
804
+ const contentStart = this.position + rule.marker.length;
805
+ if (isWhitespace(text[contentStart])) return false;
806
+ if (rule.marker.startsWith("_") && isWordCharacter(text[this.position - 1])) return false;
807
+ const closer = this.findCloser(rule, contentStart);
808
+ if (closer === void 0) return false;
809
+ this.push({
810
+ type: rule.type,
811
+ children: this.parseNested(text.slice(contentStart, closer))
812
+ });
813
+ this.position = closer + rule.marker.length;
814
+ return true;
815
+ }
816
+ findCloser(rule, contentStart) {
817
+ const { text, noCloserFrom } = this.state;
818
+ if ((noCloserFrom.get(rule.marker) ?? Infinity) <= contentStart) return void 0;
819
+ let search = contentStart + 1;
820
+ while (true) {
821
+ const found = text.indexOf(rule.marker, search);
822
+ if (found === -1) {
823
+ noCloserFrom.set(rule.marker, contentStart);
824
+ return void 0;
825
+ }
826
+ const after = text[found + rule.marker.length];
827
+ const valid = !isWhitespace(text[found - 1]) && // `*` simples não fecha no primeiro `*` de um `**`: aquele par é de negrito.
828
+ !(rule.marker.length === 1 && (after === rule.marker || text[found - 1] === rule.marker)) && !(rule.marker.startsWith("_") && isWordCharacter(after));
829
+ if (valid) return found;
830
+ search = found + 1;
831
+ }
832
+ }
833
+ parseNested(text) {
834
+ return new InlineParser2({
835
+ text,
836
+ depth: this.state.depth + 1,
837
+ noCloserFrom: /* @__PURE__ */ new Map()
838
+ }).parse();
839
+ }
840
+ };
841
+ function findClosingBracket(text, open) {
842
+ let depth = 0;
843
+ const limit = Math.min(text.length, open + MAX_BRACKET_SCAN);
844
+ for (let index = open; index < limit; index += 1) {
845
+ const character = text[index];
846
+ if (character === "\\") {
847
+ index += 1;
848
+ } else if (character === "[") {
849
+ depth += 1;
850
+ } else if (character === "]") {
851
+ depth -= 1;
852
+ if (depth === 0) return index;
853
+ }
854
+ }
855
+ return void 0;
856
+ }
857
+ __name(findClosingBracket, "findClosingBracket");
858
+ function parseDestination(text, start) {
859
+ const limit = Math.min(text.length, start + MAX_BRACKET_SCAN);
860
+ let index = start;
861
+ while (index < limit && text[index] === " ") index += 1;
862
+ let url = "";
863
+ if (text[index] === "<") {
864
+ const close = text.indexOf(">", index);
865
+ if (close === -1 || close >= limit) return void 0;
866
+ url = text.slice(index + 1, close);
867
+ index = close + 1;
868
+ } else {
869
+ let depth = 0;
870
+ while (index < limit) {
871
+ const character = text[index];
872
+ if (/\s/.test(character)) break;
873
+ if (character === "(") depth += 1;
874
+ if (character === ")") {
875
+ if (depth === 0) break;
876
+ depth -= 1;
877
+ }
878
+ url += character;
879
+ index += 1;
880
+ }
881
+ }
882
+ while (index < limit && text[index] === " ") index += 1;
883
+ let title;
884
+ const quote = text[index];
885
+ if (quote === '"' || quote === "'") {
886
+ const close = text.indexOf(quote, index + 1);
887
+ if (close === -1 || close >= limit) return void 0;
888
+ title = text.slice(index + 1, close);
889
+ index = close + 1;
890
+ while (index < limit && text[index] === " ") index += 1;
891
+ }
892
+ if (text[index] !== ")") return void 0;
893
+ return {
894
+ url,
895
+ ...title ? {
896
+ title
897
+ } : {},
898
+ end: index + 1
899
+ };
900
+ }
901
+ __name(parseDestination, "parseDestination");
902
+
903
+ // src/markdown/parseMarkdown.ts
904
+ var MAX_BLOCK_DEPTH = 6;
905
+ var FENCE_PATTERN = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/;
906
+ var HEADING_PATTERN = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
907
+ var THEMATIC_BREAK_PATTERN = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
908
+ var QUOTE_PATTERN = /^ {0,3}> ?(.*)$/;
909
+ var LIST_ITEM_PATTERN = /^( {0,3})([-*+]|\d{1,9}[.)])([ \t]+|$)(.*)$/;
910
+ function parseMarkdown(source) {
911
+ const normalized = source.replace(/\r\n?/g, "\n").replace(/\u0000/g, "\uFFFD").replace(/\t/g, " ");
912
+ return {
913
+ type: "root",
914
+ children: parseBlocks(normalized.split("\n"), 0)
915
+ };
916
+ }
917
+ __name(parseMarkdown, "parseMarkdown");
918
+ function parseBlocks(lines, depth) {
919
+ const blocks = [];
920
+ let index = 0;
921
+ while (index < lines.length) {
922
+ const line = lines[index];
923
+ if (!line.trim()) {
924
+ index += 1;
925
+ continue;
926
+ }
927
+ const parsed = parseBlockAt(lines, index, depth);
928
+ blocks.push(parsed.block);
929
+ index = parsed.next;
930
+ }
931
+ return blocks;
932
+ }
933
+ __name(parseBlocks, "parseBlocks");
934
+ function parseBlockAt(lines, index, depth) {
935
+ const line = lines[index];
936
+ if (FENCE_PATTERN.test(line)) return parseFence(lines, index);
937
+ const heading = HEADING_PATTERN.exec(line);
938
+ if (heading) {
939
+ const level = heading[1].length;
940
+ return {
941
+ block: {
942
+ type: "heading",
943
+ level,
944
+ children: parseInline(heading[2] ?? "")
945
+ },
946
+ next: index + 1
947
+ };
948
+ }
949
+ if (THEMATIC_BREAK_PATTERN.test(line)) return {
950
+ block: {
951
+ type: "thematicBreak"
952
+ },
953
+ next: index + 1
954
+ };
955
+ if (depth < MAX_BLOCK_DEPTH && QUOTE_PATTERN.test(line)) return parseQuote(lines, index, depth);
956
+ if (depth < MAX_BLOCK_DEPTH && LIST_ITEM_PATTERN.test(line)) return parseList(lines, index, depth);
957
+ return parseParagraph(lines, index, depth);
958
+ }
959
+ __name(parseBlockAt, "parseBlockAt");
960
+ function startsBlock(line, depth) {
961
+ return FENCE_PATTERN.test(line) || HEADING_PATTERN.test(line) || THEMATIC_BREAK_PATTERN.test(line) || depth < MAX_BLOCK_DEPTH && (QUOTE_PATTERN.test(line) || LIST_ITEM_PATTERN.test(line));
962
+ }
963
+ __name(startsBlock, "startsBlock");
964
+ function parseFence(lines, index) {
965
+ const opening = FENCE_PATTERN.exec(lines[index]);
966
+ const fence = opening[1];
967
+ const language = (opening[2] ?? "").toLowerCase().replace(/[^a-z0-9+#-]/g, "").slice(0, 30);
968
+ const content = [];
969
+ let cursor = index + 1;
970
+ while (cursor < lines.length) {
971
+ const line = lines[cursor];
972
+ const trimmed = line.trim();
973
+ if (trimmed.startsWith(fence[0]) && trimmed.length >= fence.length && /^(`+|~+)$/.test(trimmed)) {
974
+ cursor += 1;
975
+ break;
976
+ }
977
+ content.push(line);
978
+ cursor += 1;
979
+ }
980
+ const block = language ? {
981
+ type: "codeBlock",
982
+ language,
983
+ value: content.join("\n")
984
+ } : {
985
+ type: "codeBlock",
986
+ value: content.join("\n")
987
+ };
988
+ return {
989
+ block,
990
+ next: cursor
991
+ };
992
+ }
993
+ __name(parseFence, "parseFence");
994
+ function parseQuote(lines, index, depth) {
995
+ const inner = [];
996
+ let cursor = index;
997
+ while (cursor < lines.length) {
998
+ const match = QUOTE_PATTERN.exec(lines[cursor]);
999
+ if (!match) break;
1000
+ inner.push(match[1] ?? "");
1001
+ cursor += 1;
1002
+ }
1003
+ return {
1004
+ block: {
1005
+ type: "blockquote",
1006
+ children: parseBlocks(inner, depth + 1)
1007
+ },
1008
+ next: cursor
1009
+ };
1010
+ }
1011
+ __name(parseQuote, "parseQuote");
1012
+ function parseParagraph(lines, index, depth) {
1013
+ const content = [
1014
+ lines[index].trimStart()
1015
+ ];
1016
+ let cursor = index + 1;
1017
+ while (cursor < lines.length) {
1018
+ const line = lines[cursor];
1019
+ if (!line.trim() || startsBlock(line, depth)) break;
1020
+ content.push(line.trimStart());
1021
+ cursor += 1;
1022
+ }
1023
+ return {
1024
+ block: {
1025
+ type: "paragraph",
1026
+ children: parseInline(content.join("\n").trimEnd())
1027
+ },
1028
+ next: cursor
1029
+ };
1030
+ }
1031
+ __name(parseParagraph, "parseParagraph");
1032
+ function readMarker(line) {
1033
+ const match = LIST_ITEM_PATTERN.exec(line);
1034
+ if (!match) return void 0;
1035
+ const indent = (match[1] ?? "").length;
1036
+ const marker = match[2];
1037
+ const spacing = (match[3] ?? "").length;
1038
+ const ordered = /\d/.test(marker);
1039
+ const contentIndent = indent + marker.length + (spacing === 0 || spacing > 4 ? 1 : spacing);
1040
+ return {
1041
+ ordered,
1042
+ delimiter: ordered ? marker.slice(-1) : marker,
1043
+ start: ordered ? Number.parseInt(marker, 10) : 1,
1044
+ contentIndent,
1045
+ text: match[4] ?? ""
1046
+ };
1047
+ }
1048
+ __name(readMarker, "readMarker");
1049
+ function indentOf(line) {
1050
+ return line.length - line.trimStart().length;
1051
+ }
1052
+ __name(indentOf, "indentOf");
1053
+ function parseList(lines, index, depth) {
1054
+ const first = readMarker(lines[index]);
1055
+ const items = [];
1056
+ let tight = true;
1057
+ let cursor = index;
1058
+ while (cursor < lines.length) {
1059
+ const marker = readMarker(lines[cursor]);
1060
+ if (!marker || marker.ordered !== first.ordered || marker.delimiter !== first.delimiter) break;
1061
+ const itemLines = [
1062
+ marker.text
1063
+ ];
1064
+ cursor += 1;
1065
+ let sawBlank = false;
1066
+ while (cursor < lines.length) {
1067
+ const line = lines[cursor];
1068
+ if (!line.trim()) {
1069
+ sawBlank = true;
1070
+ itemLines.push("");
1071
+ cursor += 1;
1072
+ continue;
1073
+ }
1074
+ if (indentOf(line) >= marker.contentIndent) {
1075
+ itemLines.push(line.slice(marker.contentIndent));
1076
+ cursor += 1;
1077
+ continue;
1078
+ }
1079
+ if (!sawBlank && !startsBlock(line, depth)) {
1080
+ itemLines.push(line.trimStart());
1081
+ cursor += 1;
1082
+ continue;
1083
+ }
1084
+ break;
1085
+ }
1086
+ while (itemLines.length > 0 && !itemLines[itemLines.length - 1].trim()) itemLines.pop();
1087
+ if (itemLines.some((line) => !line.trim())) tight = false;
1088
+ items.push(parseBlocks(itemLines, depth + 1));
1089
+ const lookahead = lines[cursor];
1090
+ if (sawBlank && lookahead !== void 0 && readMarker(lookahead)) tight = false;
1091
+ }
1092
+ const block = first.ordered ? {
1093
+ type: "list",
1094
+ ordered: true,
1095
+ start: first.start,
1096
+ tight,
1097
+ items
1098
+ } : {
1099
+ type: "list",
1100
+ ordered: false,
1101
+ tight,
1102
+ items
1103
+ };
1104
+ return {
1105
+ block,
1106
+ next: cursor
1107
+ };
1108
+ }
1109
+ __name(parseList, "parseList");
1110
+
1111
+ // src/markdown/plainText.ts
1112
+ function inlineToPlainText(nodes) {
1113
+ return nodes.map((node) => {
1114
+ switch (node.type) {
1115
+ case "text":
1116
+ case "inlineCode":
1117
+ return node.value;
1118
+ case "image":
1119
+ return node.alt;
1120
+ case "break":
1121
+ return "\n";
1122
+ default:
1123
+ return inlineToPlainText(node.children);
1124
+ }
1125
+ }).join("");
1126
+ }
1127
+ __name(inlineToPlainText, "inlineToPlainText");
1128
+ function blockToPlainText(block) {
1129
+ switch (block.type) {
1130
+ case "heading":
1131
+ case "paragraph":
1132
+ return inlineToPlainText(block.children);
1133
+ case "codeBlock":
1134
+ return block.value;
1135
+ case "blockquote":
1136
+ return block.children.map(blockToPlainText).join("\n\n");
1137
+ case "list":
1138
+ return block.items.map((item) => item.map(blockToPlainText).join("\n")).join("\n");
1139
+ case "thematicBreak":
1140
+ return "";
1141
+ }
1142
+ }
1143
+ __name(blockToPlainText, "blockToPlainText");
1144
+ function documentToPlainText(document) {
1145
+ return document.children.map(blockToPlainText).filter((text) => text.length > 0).join("\n\n");
1146
+ }
1147
+ __name(documentToPlainText, "documentToPlainText");
1148
+ function markdownToPlainText(markdown) {
1149
+ return documentToPlainText(parseMarkdown(markdown));
1150
+ }
1151
+ __name(markdownToPlainText, "markdownToPlainText");
1152
+
1153
+ // src/readingTime.ts
1154
+ var DEFAULT_WORDS_PER_MINUTE = 200;
1155
+ function countWords(text) {
1156
+ const words = text.trim().split(/\s+/);
1157
+ return words[0] === "" ? 0 : words.length;
1158
+ }
1159
+ __name(countWords, "countWords");
1160
+ function estimateReadingTimeMinutes(markdown, wordsPerMinute = DEFAULT_WORDS_PER_MINUTE) {
1161
+ const words = countWords(markdownToPlainText(markdown));
1162
+ return Math.max(1, Math.ceil(words / Math.max(1, wordsPerMinute)));
1163
+ }
1164
+ __name(estimateReadingTimeMinutes, "estimateReadingTimeMinutes");
1165
+ function buildExcerpt(markdown, maxLength = 200) {
1166
+ const text = markdownToPlainText(markdown).replace(/\s+/g, " ").trim();
1167
+ if (text.length <= maxLength) return text;
1168
+ const cut = text.slice(0, maxLength - 1);
1169
+ const lastSpace = cut.lastIndexOf(" ");
1170
+ return `${(lastSpace > maxLength / 2 ? cut.slice(0, lastSpace) : cut).replace(/[\s.,;:!?-]+$/, "")}\u2026`;
1171
+ }
1172
+ __name(buildExcerpt, "buildExcerpt");
1173
+
1174
+ // src/markdown/headingIds.ts
1175
+ function createHeadingIdGenerator(prefix = "") {
1176
+ const used = /* @__PURE__ */ new Map();
1177
+ return (text) => {
1178
+ const base = slugify(text) || "section";
1179
+ const count = (used.get(base) ?? 0) + 1;
1180
+ used.set(base, count);
1181
+ return `${prefix}${count === 1 ? base : `${base}-${count}`}`;
1182
+ };
1183
+ }
1184
+ __name(createHeadingIdGenerator, "createHeadingIdGenerator");
1185
+
1186
+ // src/markdown/renderHtml.ts
1187
+ var DEFAULT_LINK_REL = "noopener noreferrer";
1188
+ var ESCAPES = {
1189
+ "&": "&amp;",
1190
+ "<": "&lt;",
1191
+ ">": "&gt;",
1192
+ '"': "&quot;",
1193
+ "'": "&#39;"
1194
+ };
1195
+ function escapeHtml(value) {
1196
+ return value.replace(/[&<>"']/g, (character) => ESCAPES[character] ?? character);
1197
+ }
1198
+ __name(escapeHtml, "escapeHtml");
1199
+ function resolveHeadingLevel(level, offset = 0) {
1200
+ return Math.min(6, Math.max(1, level + offset));
1201
+ }
1202
+ __name(resolveHeadingLevel, "resolveHeadingLevel");
1203
+ function renderInline(nodes, context) {
1204
+ return nodes.map((node) => renderInlineNode(node, context)).join("");
1205
+ }
1206
+ __name(renderInline, "renderInline");
1207
+ function renderInlineNode(node, context) {
1208
+ switch (node.type) {
1209
+ case "text":
1210
+ return escapeHtml(node.value);
1211
+ case "strong":
1212
+ return `<strong>${renderInline(node.children, context)}</strong>`;
1213
+ case "emphasis":
1214
+ return `<em>${renderInline(node.children, context)}</em>`;
1215
+ case "strikethrough":
1216
+ return `<del>${renderInline(node.children, context)}</del>`;
1217
+ case "inlineCode":
1218
+ return `<code>${escapeHtml(node.value)}</code>`;
1219
+ case "break":
1220
+ return "<br>";
1221
+ case "image": {
1222
+ const title = node.title ? ` title="${escapeHtml(node.title)}"` : "";
1223
+ return `<img src="${escapeHtml(node.src)}" alt="${escapeHtml(node.alt)}"${title} loading="lazy" decoding="async">`;
1224
+ }
1225
+ case "link": {
1226
+ const title = node.title ? ` title="${escapeHtml(node.title)}"` : "";
1227
+ const newTab = (context.options.externalLinksInNewTab ?? true) && isAbsoluteHttpUrl(node.href);
1228
+ const target = newTab ? ' target="_blank"' : "";
1229
+ const rel = escapeHtml(context.options.linkRel ?? DEFAULT_LINK_REL);
1230
+ return `<a href="${escapeHtml(node.href)}"${title}${target} rel="${rel}">${renderInline(node.children, context)}</a>`;
1231
+ }
1232
+ }
1233
+ }
1234
+ __name(renderInlineNode, "renderInlineNode");
1235
+ function renderBlock(block, context, tight = false) {
1236
+ switch (block.type) {
1237
+ case "heading": {
1238
+ const level = resolveHeadingLevel(block.level, context.options.headingLevelOffset);
1239
+ const id = context.options.headingIds ?? true ? ` id="${escapeHtml(context.nextHeadingId(inlineToPlainText(block.children)))}"` : "";
1240
+ return `<h${level}${id}>${renderInline(block.children, context)}</h${level}>`;
1241
+ }
1242
+ case "paragraph":
1243
+ return tight ? renderInline(block.children, context) : `<p>${renderInline(block.children, context)}</p>`;
1244
+ case "blockquote":
1245
+ return `<blockquote>${block.children.map((child) => renderBlock(child, context)).join("")}</blockquote>`;
1246
+ case "codeBlock": {
1247
+ const className = block.language ? ` class="language-${escapeHtml(block.language)}"` : "";
1248
+ return `<pre><code${className}>${escapeHtml(block.value)}</code></pre>`;
1249
+ }
1250
+ case "thematicBreak":
1251
+ return "<hr>";
1252
+ case "list": {
1253
+ const tag = block.ordered ? "ol" : "ul";
1254
+ const start = block.ordered && block.start !== void 0 && block.start !== 1 ? ` start="${block.start}"` : "";
1255
+ const items = block.items.map((item) => `<li>${item.map((child) => renderBlock(child, context, block.tight)).join("")}</li>`).join("");
1256
+ return `<${tag}${start}>${items}</${tag}>`;
1257
+ }
1258
+ }
1259
+ }
1260
+ __name(renderBlock, "renderBlock");
1261
+ function renderMarkdownDocument(document, options = {}) {
1262
+ const context = {
1263
+ options,
1264
+ nextHeadingId: createHeadingIdGenerator(options.headingIdPrefix)
1265
+ };
1266
+ return document.children.map((block) => renderBlock(block, context)).join("\n");
1267
+ }
1268
+ __name(renderMarkdownDocument, "renderMarkdownDocument");
1269
+ function renderMarkdownToHtml(markdown, options = {}) {
1270
+ return renderMarkdownDocument(parseMarkdown(markdown), options);
1271
+ }
1272
+ __name(renderMarkdownToHtml, "renderMarkdownToHtml");
1273
+
1274
+ // src/feed.ts
1275
+ var DEFAULT_POST_PATH_TEMPLATE = "/blog/{slug}";
1276
+ var XML_ESCAPES = {
1277
+ "&": "&amp;",
1278
+ "<": "&lt;",
1279
+ ">": "&gt;",
1280
+ '"': "&quot;",
1281
+ "'": "&apos;"
1282
+ };
1283
+ function escapeXml(value) {
1284
+ return value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/g, "").replace(/[&<>"']/g, (character) => XML_ESCAPES[character] ?? character);
1285
+ }
1286
+ __name(escapeXml, "escapeXml");
1287
+ function buildPostUrl(params) {
1288
+ const base = params.siteUrl.replace(/\/+$/, "");
1289
+ const path = (params.postPathTemplate ?? DEFAULT_POST_PATH_TEMPLATE).replace("{shortId}", encodeURIComponent(params.shortId ?? "")).replace("{slug}", encodeURIComponent(params.slug));
1290
+ return `${base}${path.startsWith("/") ? path : `/${path}`}`;
1291
+ }
1292
+ __name(buildPostUrl, "buildPostUrl");
1293
+ function toRfc822(iso) {
1294
+ return new Date(iso).toUTCString();
1295
+ }
1296
+ __name(toRfc822, "toRfc822");
1297
+ function rssItem(item) {
1298
+ const parts = [
1299
+ `<title>${escapeXml(item.title)}</title>`,
1300
+ `<link>${escapeXml(item.url)}</link>`,
1301
+ `<guid isPermaLink="true">${escapeXml(item.url)}</guid>`,
1302
+ `<pubDate>${toRfc822(item.publishedAt)}</pubDate>`
1303
+ ];
1304
+ if (item.summary) parts.push(`<description>${escapeXml(item.summary)}</description>`);
1305
+ if (item.contentHtml) parts.push(`<content:encoded>${escapeXml(item.contentHtml)}</content:encoded>`);
1306
+ if (item.authorName) parts.push(`<dc:creator>${escapeXml(item.authorName)}</dc:creator>`);
1307
+ for (const category of item.categories ?? []) parts.push(`<category>${escapeXml(category)}</category>`);
1308
+ if (item.imageUrl) parts.push(`<enclosure url="${escapeXml(item.imageUrl)}" type="image/*" length="0"/>`);
1309
+ return `<item>${parts.join("")}</item>`;
1310
+ }
1311
+ __name(rssItem, "rssItem");
1312
+ function buildRssFeed(params) {
1313
+ const { channel } = params;
1314
+ const head = [
1315
+ `<title>${escapeXml(channel.title)}</title>`,
1316
+ `<link>${escapeXml(channel.siteUrl)}</link>`,
1317
+ `<description>${escapeXml(channel.description ?? channel.title)}</description>`
1318
+ ];
1319
+ if (channel.language) head.push(`<language>${escapeXml(channel.language)}</language>`);
1320
+ if (channel.feedUrl) head.push(`<atom:link href="${escapeXml(channel.feedUrl)}" rel="self" type="application/rss+xml"/>`);
1321
+ const latest = params.items[0];
1322
+ if (latest) head.push(`<lastBuildDate>${toRfc822(latest.updatedAt ?? latest.publishedAt)}</lastBuildDate>`);
1323
+ return `<?xml version="1.0" encoding="UTF-8"?>
1324
+ <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel>${head.join("")}${params.items.map(rssItem).join("")}</channel></rss>
1325
+ `;
1326
+ }
1327
+ __name(buildRssFeed, "buildRssFeed");
1328
+ function atomEntry(item) {
1329
+ const parts = [
1330
+ `<title>${escapeXml(item.title)}</title>`,
1331
+ `<link href="${escapeXml(item.url)}"/>`,
1332
+ `<id>${escapeXml(item.url)}</id>`,
1333
+ `<published>${new Date(item.publishedAt).toISOString()}</published>`,
1334
+ `<updated>${new Date(item.updatedAt ?? item.publishedAt).toISOString()}</updated>`
1335
+ ];
1336
+ if (item.summary) parts.push(`<summary>${escapeXml(item.summary)}</summary>`);
1337
+ if (item.contentHtml) parts.push(`<content type="html">${escapeXml(item.contentHtml)}</content>`);
1338
+ if (item.authorName) parts.push(`<author><name>${escapeXml(item.authorName)}</name></author>`);
1339
+ for (const category of item.categories ?? []) parts.push(`<category term="${escapeXml(category)}"/>`);
1340
+ return `<entry>${parts.join("")}</entry>`;
1341
+ }
1342
+ __name(atomEntry, "atomEntry");
1343
+ function buildAtomFeed(params) {
1344
+ const { channel } = params;
1345
+ const latest = params.items[0];
1346
+ const updated = latest ? new Date(latest.updatedAt ?? latest.publishedAt) : params.now ?? /* @__PURE__ */ new Date();
1347
+ const head = [
1348
+ `<title>${escapeXml(channel.title)}</title>`,
1349
+ `<id>${escapeXml(channel.feedUrl ?? channel.siteUrl)}</id>`,
1350
+ `<link href="${escapeXml(channel.siteUrl)}"/>`,
1351
+ `<updated>${updated.toISOString()}</updated>`
1352
+ ];
1353
+ if (channel.feedUrl) head.push(`<link rel="self" href="${escapeXml(channel.feedUrl)}"/>`);
1354
+ if (channel.description) head.push(`<subtitle>${escapeXml(channel.description)}</subtitle>`);
1355
+ const language = channel.language ? ` xml:lang="${escapeXml(channel.language)}"` : "";
1356
+ return `<?xml version="1.0" encoding="UTF-8"?>
1357
+ <feed xmlns="http://www.w3.org/2005/Atom"${language}>${head.join("")}${params.items.map(atomEntry).join("")}</feed>
1358
+ `;
1359
+ }
1360
+ __name(buildAtomFeed, "buildAtomFeed");
1361
+ function buildSitemapXml(entries) {
1362
+ const urls = entries.map((entry) => `<url><loc>${escapeXml(entry.loc)}</loc>${entry.lastmod ? `<lastmod>${escapeXml(entry.lastmod)}</lastmod>` : ""}</url>`).join("");
1363
+ return `<?xml version="1.0" encoding="UTF-8"?>
1364
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${urls}</urlset>
1365
+ `;
1366
+ }
1367
+ __name(buildSitemapXml, "buildSitemapXml");
1368
+ // Annotate the CommonJS export names for ESM import in node:
1369
+ 0 && (module.exports = {
1370
+ CONTENT_ERROR_CODES,
1371
+ ConfigMissingError,
1372
+ ContentError,
1373
+ DEFAULT_ADMIN_SCOPES,
1374
+ DEFAULT_LINK_REL,
1375
+ DEFAULT_POST_PATH_TEMPLATE,
1376
+ DEFAULT_PUBLIC_CACHE_CONTROL,
1377
+ DEFAULT_SHORT_SLUG_LENGTH,
1378
+ DEFAULT_WORDS_PER_MINUTE,
1379
+ DuplicateSlugError,
1380
+ ImageStorageDisabledError,
1381
+ InvalidCoverImageError,
1382
+ InvalidSlugError,
1383
+ NotATemplateError,
1384
+ POST_EVENT,
1385
+ POST_LIMITS,
1386
+ POST_SORT_FIELDS,
1387
+ POST_STATUS,
1388
+ POST_STATUSES,
1389
+ PT_BR_STOP_WORDS,
1390
+ PostNotFoundError,
1391
+ PostNotPublishedError,
1392
+ RECURRENCE_FREQUENCIES,
1393
+ RECURRENCE_FREQUENCY,
1394
+ RecurrenceNotFoundError,
1395
+ RepublishDateInFutureError,
1396
+ SHORT_ID_LENGTH,
1397
+ SLUG_MAX_LENGTH,
1398
+ TAGS_MAX_COUNT,
1399
+ TAG_MAX_LENGTH,
1400
+ TemplateNotPublishableError,
1401
+ buildAtomFeed,
1402
+ buildExcerpt,
1403
+ buildPostPath,
1404
+ buildPostRef,
1405
+ buildPostUrl,
1406
+ buildRssFeed,
1407
+ buildShortSlug,
1408
+ buildSitemapXml,
1409
+ buildTagLabels,
1410
+ countWords,
1411
+ createFromTemplateSchema,
1412
+ createHeadingIdGenerator,
1413
+ createPostSchema,
1414
+ createRecurrenceSchema,
1415
+ documentToPlainText,
1416
+ escapeHtml,
1417
+ escapeXml,
1418
+ estimateReadingTimeMinutes,
1419
+ formatTagLabel,
1420
+ httpUrlSchema,
1421
+ inlineToPlainText,
1422
+ isAbsoluteHttpUrl,
1423
+ isCanonicalPostRef,
1424
+ isPostStatus,
1425
+ isShortId,
1426
+ isValidSlug,
1427
+ listPostsQuerySchema,
1428
+ listPublishedPostsQuerySchema,
1429
+ markdownToPlainText,
1430
+ normalizeTag,
1431
+ normalizeTags,
1432
+ parseInline,
1433
+ parseMarkdown,
1434
+ parsePostPath,
1435
+ parsePostRef,
1436
+ postFieldsSchema,
1437
+ publishPostSchema,
1438
+ renderMarkdownDocument,
1439
+ renderMarkdownToHtml,
1440
+ republishPostSchema,
1441
+ resolveHeadingLevel,
1442
+ sanitizeImageUrl,
1443
+ sanitizeLinkUrl,
1444
+ saveAsTemplateSchema,
1445
+ slugSchema,
1446
+ slugify,
1447
+ updatePostSchema,
1448
+ updateRecurrenceSchema,
1449
+ withSlugSuffix
1450
+ });
1451
+ //# sourceMappingURL=index.cjs.map