@jant/core 0.8.1 → 0.9.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/{app--uxnaIRV.js → app-BzH8jmh3.js} +1199 -262
- package/dist/client/.vite/manifest.json +2 -2
- package/dist/client/_assets/{client-BT6kpcuG.js → client-S8oryJ0m.js} +1 -1
- package/dist/client/_assets/{client-auth-begiT1tq.js → client-auth-Ds9G0IgR.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/node.js +2 -2
- package/package.json +1 -1
- package/src/__tests__/helpers/cursor-walk.ts +37 -7
- package/src/app.tsx +4 -0
- package/src/lib/__tests__/thread-fold.test.ts +43 -0
- package/src/lib/api-posts.ts +110 -2
- package/src/lib/api-public-posts.ts +263 -0
- package/src/lib/api-threads.ts +207 -0
- package/src/lib/thread-fold.ts +83 -41
- package/src/lib/thread-query.ts +143 -0
- package/src/middleware/cors.ts +8 -1
- package/src/middleware/deprecation.ts +48 -0
- package/src/routes/api/__tests__/mcp.test.ts +89 -0
- package/src/routes/api/__tests__/posts.test.ts +78 -0
- package/src/routes/api/__tests__/public-access.test.ts +5 -0
- package/src/routes/api/__tests__/threads.test.ts +115 -0
- package/src/routes/api/posts.ts +15 -104
- package/src/routes/api/public/__tests__/threads.test.ts +363 -0
- package/src/routes/api/public/archive.ts +82 -81
- package/src/routes/api/public/posts.ts +97 -298
- package/src/routes/api/public/threads.ts +141 -0
- package/src/routes/api/threads.ts +128 -0
- package/src/services/__tests__/thread.test.ts +495 -0
- package/src/services/index.ts +4 -0
- package/src/services/mcp.ts +208 -53
- package/src/services/post.ts +222 -43
- package/src/services/thread.ts +392 -0
- package/src/types/constants.ts +25 -0
- package/src/ui/feed/ThreadPreview.tsx +9 -14
- package/src/ui/feed/__tests__/thread-preview.test.ts +18 -22
- package/src/ui/feed/thread-preview-state.ts +0 -35
|
@@ -5344,9 +5344,9 @@ function normalizeThemeColorForMeta(color) {
|
|
|
5344
5344
|
*
|
|
5345
5345
|
* The dev flag itself lives in `build-env.ts`, which client bundles can import
|
|
5346
5346
|
* without these Worker-only globals.
|
|
5347
|
-
*/ var CORE_VERSION = "0.
|
|
5348
|
-
var CLIENT_JS_FILE = "/_assets/client-
|
|
5349
|
-
var CLIENT_AUTH_JS_FILE = "/_assets/client-auth-
|
|
5347
|
+
*/ var CORE_VERSION = "0.9.0-f5f1d977f9cb3f8e";
|
|
5348
|
+
var CLIENT_JS_FILE = "/_assets/client-S8oryJ0m.js";
|
|
5349
|
+
var CLIENT_AUTH_JS_FILE = "/_assets/client-auth-Ds9G0IgR.js";
|
|
5350
5350
|
var CLIENT_COMPOSE_PRELOAD = [
|
|
5351
5351
|
"/_assets/client-compose-D6rExKVK.js",
|
|
5352
5352
|
"/_assets/chunks/create-editor-B-m7X7S5.js",
|
|
@@ -5943,7 +5943,7 @@ var IconSprite = () => {
|
|
|
5943
5943
|
const authorStylesheetPath = resolvedClientBundle === "full" ? IS_VITE_DEV ? assetPath("/src/style-author.css") : toPublicAssetPath(CLIENT_AUTHOR_CSS_FILE, assetBasePath) : null;
|
|
5944
5944
|
const clientScriptPath = IS_VITE_DEV ? resolvedClientBundle === "full" ? assetPath("/src/client-auth.ts") : assetPath("/src/client.ts") : toPublicAssetPath(resolvedClientBundle === "full" ? CLIENT_AUTH_JS_FILE : CLIENT_JS_FILE, assetBasePath);
|
|
5945
5945
|
const composePreloadPaths = !IS_VITE_DEV && resolvedClientBundle === "full" ? CLIENT_COMPOSE_PRELOAD.map((file) => toPublicAssetPath(file, assetBasePath)) : [];
|
|
5946
|
-
const faviconAssetVersion = resolvedFaviconVersion || "0.
|
|
5946
|
+
const faviconAssetVersion = resolvedFaviconVersion || "0.9.0-f5f1d977f9cb3f8e";
|
|
5947
5947
|
const resolvedFaviconHref = faviconHref ?? (faviconAssetVersion ? toPublicPath(`/favicon.ico?v=${faviconAssetVersion}`, sitePathPrefix) : toPublicPath("/favicon.ico", sitePathPrefix));
|
|
5948
5948
|
const resolvedAppleTouchHref = appleTouchHref ?? (faviconAssetVersion ? toPublicPath(`/apple-touch-icon.png?v=${faviconAssetVersion}`, sitePathPrefix) : toPublicPath("/apple-touch-icon.png", sitePathPrefix));
|
|
5949
5949
|
const socialImageHref = resolvedSocialImagePath ? toAbsoluteAssetUrl(resolvedSocialImagePath, appConfig?.siteUrl || "", sitePathPrefix) : "";
|
|
@@ -6431,6 +6431,28 @@ var LATEST_FILTERABLE_YEAR = 9999;
|
|
|
6431
6431
|
* said the same thing in different words; folding it into `newest` left one
|
|
6432
6432
|
* menu the reader can learn once.
|
|
6433
6433
|
*/ var SMART_COLLECTION_SORT_ORDERS = COLLECTION_SORT_ORDERS;
|
|
6434
|
+
/**
|
|
6435
|
+
* How the Threads API orders a list of Threads — each value one the site
|
|
6436
|
+
* already shows somewhere, named for the axis it reads:
|
|
6437
|
+
*
|
|
6438
|
+
* - `activity`: the homepage, and a collection's `newest`. A Thread moves up
|
|
6439
|
+
* when it gains an announced post.
|
|
6440
|
+
* - `published`: the archive's default. Newest root publication first; a reply
|
|
6441
|
+
* never moves a Thread, so this is the order to walk a whole site in.
|
|
6442
|
+
* - `updated`: the archive's `?sort=updated`. Like `activity`, but a quiet
|
|
6443
|
+
* reply counts too.
|
|
6444
|
+
* - `oldest`: a collection's `oldest`. Oldest root publication first.
|
|
6445
|
+
* - `rating`: a collection's `rating_desc`. Highest rating first, then activity.
|
|
6446
|
+
*
|
|
6447
|
+
* Not `SORT_ORDERS`: `newest` means activity on a collection and would read as
|
|
6448
|
+
* publication here.
|
|
6449
|
+
*/ var THREAD_SORTS = [
|
|
6450
|
+
"activity",
|
|
6451
|
+
"published",
|
|
6452
|
+
"updated",
|
|
6453
|
+
"oldest",
|
|
6454
|
+
"rating"
|
|
6455
|
+
];
|
|
6434
6456
|
var NAV_ITEM_TYPES = [
|
|
6435
6457
|
"link",
|
|
6436
6458
|
"system",
|
|
@@ -18641,6 +18663,52 @@ var TimelineItemFromPost = ({ post, mode, display }) => {
|
|
|
18641
18663
|
return Math.max(0, totalReplyCount - shown.size);
|
|
18642
18664
|
}
|
|
18643
18665
|
/**
|
|
18666
|
+
* Fold a thread from its ranked windows: the replies each end of the fold
|
|
18667
|
+
* keeps, before any overlap between them is removed.
|
|
18668
|
+
*
|
|
18669
|
+
* Both access paths arrive here. The feed slices the windows out of the whole
|
|
18670
|
+
* chain; the site and the API rank them in SQL (`getThreadTimelineContext`),
|
|
18671
|
+
* which hands them over overlapping on purpose. A short thread's windows
|
|
18672
|
+
* overlap, and the hero is inside both of them on the shortest ones: with a
|
|
18673
|
+
* single reply, that reply is the newest *and* the whole leading window. Each
|
|
18674
|
+
* list therefore drops whatever an earlier one already shows, hero first.
|
|
18675
|
+
*
|
|
18676
|
+
* @param buckets.leadingReplies - The first `THREAD_LEADING_REPLIES` replies
|
|
18677
|
+
* @param buckets.trailingReplies - The replies just before the newest, oldest
|
|
18678
|
+
* first
|
|
18679
|
+
* @param buckets.latestReply - The newest reply
|
|
18680
|
+
* @param buckets.nextReply - The reply right after the leading window, the
|
|
18681
|
+
* only candidate for the gap; `null` when the thread has no such reply
|
|
18682
|
+
* @param buckets.totalReplyCount - Every published reply in the thread
|
|
18683
|
+
* @returns The fold
|
|
18684
|
+
* @example
|
|
18685
|
+
* foldReplyWindows({ leadingReplies: [r1, r2], trailingReplies: [r6, r7],
|
|
18686
|
+
* latestReply: r8, nextReply: r3, totalReplyCount: 8 });
|
|
18687
|
+
* // leading [r1, r2], trailing [r6, r7], latest r8, firstHidden r3, hidden 3
|
|
18688
|
+
*/ function foldReplyWindows({ leadingReplies: leadingWindow, trailingReplies: trailingWindow, latestReply, nextReply, totalReplyCount }) {
|
|
18689
|
+
const shown = /* @__PURE__ */ new Set([latestReply.id]);
|
|
18690
|
+
const keepUnshown = (replies) => replies.filter((reply) => {
|
|
18691
|
+
if (shown.has(reply.id)) return false;
|
|
18692
|
+
shown.add(reply.id);
|
|
18693
|
+
return true;
|
|
18694
|
+
});
|
|
18695
|
+
const leadingReplies = keepUnshown(leadingWindow);
|
|
18696
|
+
const trailingReplies = keepUnshown(trailingWindow);
|
|
18697
|
+
const hiddenCount = getThreadHiddenCount({
|
|
18698
|
+
leadingReplies,
|
|
18699
|
+
trailingReplies,
|
|
18700
|
+
latestReply,
|
|
18701
|
+
totalReplyCount
|
|
18702
|
+
});
|
|
18703
|
+
return {
|
|
18704
|
+
leadingReplies,
|
|
18705
|
+
trailingReplies,
|
|
18706
|
+
latestReply,
|
|
18707
|
+
firstHiddenReply: hiddenCount > 0 && nextReply && !shown.has(nextReply.id) ? nextReply : null,
|
|
18708
|
+
hiddenCount
|
|
18709
|
+
};
|
|
18710
|
+
}
|
|
18711
|
+
/**
|
|
18644
18712
|
* Fold a thread whose replies are already in hand.
|
|
18645
18713
|
*
|
|
18646
18714
|
* Takes the same slices the SQL path ranks for: the first
|
|
@@ -18657,50 +18725,17 @@ var TimelineItemFromPost = ({ post, mode, display }) => {
|
|
|
18657
18725
|
*/ function foldThreadReplies(replies) {
|
|
18658
18726
|
const latestReply = replies.at(-1);
|
|
18659
18727
|
if (!latestReply) return null;
|
|
18660
|
-
|
|
18661
|
-
|
|
18662
|
-
|
|
18663
|
-
const shown = /* @__PURE__ */ new Set([
|
|
18664
|
-
...leadingIds,
|
|
18665
|
-
...trailingReplies.map((reply) => reply.id),
|
|
18666
|
-
latestReply.id
|
|
18667
|
-
]);
|
|
18668
|
-
return {
|
|
18669
|
-
leadingReplies,
|
|
18670
|
-
trailingReplies,
|
|
18728
|
+
return foldReplyWindows({
|
|
18729
|
+
leadingReplies: replies.slice(0, 2),
|
|
18730
|
+
trailingReplies: replies.slice(-3, -1),
|
|
18671
18731
|
latestReply,
|
|
18672
|
-
|
|
18673
|
-
|
|
18674
|
-
|
|
18675
|
-
trailingReplies,
|
|
18676
|
-
latestReply,
|
|
18677
|
-
totalReplyCount: replies.length
|
|
18678
|
-
})
|
|
18679
|
-
};
|
|
18732
|
+
nextReply: replies[2] ?? null,
|
|
18733
|
+
totalReplyCount: replies.length
|
|
18734
|
+
});
|
|
18680
18735
|
}
|
|
18681
18736
|
//#endregion
|
|
18682
18737
|
//#region src/ui/feed/thread-preview-state.ts
|
|
18683
18738
|
/**
|
|
18684
|
-
* What the preview needs to know about its own fold.
|
|
18685
|
-
*
|
|
18686
|
-
* The count itself lives in `lib/thread-fold.ts`, where the feed reads it too —
|
|
18687
|
-
* a card and a feed entry that disagreed about how many posts are hidden would
|
|
18688
|
-
* be describing different threads.
|
|
18689
|
-
*
|
|
18690
|
-
* @param selection - The replies this preview shows, and the thread's total
|
|
18691
|
-
* @returns The hidden-post count the gap link announces
|
|
18692
|
-
* @example
|
|
18693
|
-
* getThreadPreviewState({ leadingReplies, trailingReplies, latestReply,
|
|
18694
|
-
* totalReplyCount: 8 }); // { hiddenCount: 3 }
|
|
18695
|
-
*/ function getThreadPreviewState({ leadingReplies, trailingReplies, latestReply, totalReplyCount }) {
|
|
18696
|
-
return { hiddenCount: getThreadHiddenCount({
|
|
18697
|
-
leadingReplies,
|
|
18698
|
-
trailingReplies,
|
|
18699
|
-
latestReply,
|
|
18700
|
-
totalReplyCount
|
|
18701
|
-
}) };
|
|
18702
|
-
}
|
|
18703
|
-
/**
|
|
18704
18739
|
* A lone root post shorter than this (plain-text code points) comfortably
|
|
18705
18740
|
* fits the thread-context height cap. Pairs with the
|
|
18706
18741
|
* `--site-thread-context-max-height` token (160px) in tokens.css — revisit
|
|
@@ -18744,12 +18779,14 @@ var CONTEXT_DISPLAY = {
|
|
|
18744
18779
|
var HERO_DISPLAY = {};
|
|
18745
18780
|
var ThreadPreview = ({ rootPost, leadingReplies, trailingReplies, latestReply, gapHref, totalReplyCount }) => {
|
|
18746
18781
|
const { i18n } = useLingui();
|
|
18747
|
-
const
|
|
18782
|
+
const fold = foldReplyWindows({
|
|
18748
18783
|
leadingReplies,
|
|
18749
18784
|
trailingReplies,
|
|
18750
18785
|
latestReply,
|
|
18786
|
+
nextReply: null,
|
|
18751
18787
|
totalReplyCount
|
|
18752
18788
|
});
|
|
18789
|
+
const hiddenCount = fold.hiddenCount;
|
|
18753
18790
|
const assumeOverflow = threadContextAssumesOverflow({
|
|
18754
18791
|
rootPost,
|
|
18755
18792
|
totalReplyCount
|
|
@@ -18757,14 +18794,8 @@ var ThreadPreview = ({ rootPost, leadingReplies, trailingReplies, latestReply, g
|
|
|
18757
18794
|
const hiddenPostsLabel = i18n._({ id: "oO0hKx" }, { count: hiddenCount });
|
|
18758
18795
|
const showMoreLabel = i18n._({ id: "fMPkxb" });
|
|
18759
18796
|
const showLessLabel = i18n._({ id: "6lGV3K" });
|
|
18760
|
-
const
|
|
18761
|
-
const
|
|
18762
|
-
if (visibleReplyIds.has(reply.id)) return false;
|
|
18763
|
-
visibleReplyIds.add(reply.id);
|
|
18764
|
-
return true;
|
|
18765
|
-
});
|
|
18766
|
-
const renderedLeadingReplies = dedupeReplies(leadingReplies);
|
|
18767
|
-
const renderedTrailingReplies = dedupeReplies(trailingReplies);
|
|
18797
|
+
const renderedLeadingReplies = fold.leadingReplies;
|
|
18798
|
+
const renderedTrailingReplies = fold.trailingReplies;
|
|
18768
18799
|
const gapLinkHref = gapHref ?? latestReply.permalink;
|
|
18769
18800
|
const rootItem = /*#__PURE__*/ jsxDEV$1("div", {
|
|
18770
18801
|
class: "thread-item thread-item-context",
|
|
@@ -36678,6 +36709,24 @@ customUrlsRoutes.post("/:id/delete", async (c) => {
|
|
|
36678
36709
|
});
|
|
36679
36710
|
//#endregion
|
|
36680
36711
|
//#region src/lib/api-posts.ts
|
|
36712
|
+
/**
|
|
36713
|
+
* The order `GET /api/posts` and `jant_posts_list` walk Posts in.
|
|
36714
|
+
*
|
|
36715
|
+
* Published Posts run newest-published first, pins ignored: a Post's place
|
|
36716
|
+
* then depends on its own publication alone, and a reply added to an old
|
|
36717
|
+
* Thread doesn't lift the root past a walk's cursor. Drafts keep the editing
|
|
36718
|
+
* order the composer's draft list reads, last edited first.
|
|
36719
|
+
*
|
|
36720
|
+
* @param status - The status the list is filtered to
|
|
36721
|
+
* @returns The `PostFilters` ordering fields for that list
|
|
36722
|
+
* @example
|
|
36723
|
+
* posts.listPage({ status, ...apiPostListOrder(status) }, { limit: 100 });
|
|
36724
|
+
*/ function apiPostListOrder(status) {
|
|
36725
|
+
return status === "draft" ? {} : {
|
|
36726
|
+
sortBy: "published",
|
|
36727
|
+
ignorePinnedSort: true
|
|
36728
|
+
};
|
|
36729
|
+
}
|
|
36681
36730
|
function toApiAttachment(media, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix) {
|
|
36682
36731
|
const publicUrl = getPublicUrlForProvider(media.provider, r2PublicUrl, s3PublicUrl, localPublicUrl);
|
|
36683
36732
|
const url = getMediaUrl(media.storageKey, publicUrl, sitePathPrefix);
|
|
@@ -36715,7 +36764,7 @@ function toApiAttachment(media, r2PublicUrl, imageTransformUrl, s3PublicUrl, loc
|
|
|
36715
36764
|
chars: media.chars
|
|
36716
36765
|
};
|
|
36717
36766
|
}
|
|
36718
|
-
function toApiPost(post, extras
|
|
36767
|
+
function toApiPost(post, extras) {
|
|
36719
36768
|
const { title, url, ...rest } = post;
|
|
36720
36769
|
const displayTitle = getPostDisplayTitle(post);
|
|
36721
36770
|
if (post.format === "quote") return {
|
|
@@ -36733,6 +36782,46 @@ function toApiPost(post, extras = {}) {
|
|
|
36733
36782
|
url: url ?? null
|
|
36734
36783
|
};
|
|
36735
36784
|
}
|
|
36785
|
+
/**
|
|
36786
|
+
* API responses for Posts already loaded. Attachments, Thread Post counts,
|
|
36787
|
+
* and (when asked) Thread collections are each read in one batch for the
|
|
36788
|
+
* whole set, so a page costs the same few round trips however long it is.
|
|
36789
|
+
*
|
|
36790
|
+
* @param deps - Services and app config; a request's `c.var` or an MCP context
|
|
36791
|
+
* @param posts - Posts to respond with, in order
|
|
36792
|
+
* @param options - `collectionIds` adds each Post's shared Thread collections
|
|
36793
|
+
* @returns One response per Post, in the same order
|
|
36794
|
+
* @example
|
|
36795
|
+
* const responses = await loadApiPostResponses(c.var, page.posts);
|
|
36796
|
+
*/ async function loadApiPostResponses(deps, posts, options = {}) {
|
|
36797
|
+
if (posts.length === 0) return [];
|
|
36798
|
+
const { services, appConfig } = deps;
|
|
36799
|
+
const postIds = posts.map((post) => post.id);
|
|
36800
|
+
const [mediaMap, threadPostCounts, collectionsMap] = await Promise.all([
|
|
36801
|
+
services.media.getByPostIds(postIds),
|
|
36802
|
+
services.posts.countThreadPosts(posts.map((post) => post.threadId)),
|
|
36803
|
+
options.collectionIds ? services.collections.getCollectionsByPostIds(postIds) : Promise.resolve(null)
|
|
36804
|
+
]);
|
|
36805
|
+
return posts.map((post) => toApiPost(post, {
|
|
36806
|
+
threadPostCount: threadPostCounts.get(post.threadId) ?? 0,
|
|
36807
|
+
attachments: (mediaMap.get(post.id) ?? []).map((media) => toApiAttachment(media, appConfig.r2PublicUrl, appConfig.imageTransformUrl, appConfig.s3PublicUrl, appConfig.localPublicUrl, appConfig.sitePathPrefix)),
|
|
36808
|
+
...collectionsMap ? { collectionIds: (collectionsMap.get(post.id) ?? []).map((collection) => collection.id) } : {}
|
|
36809
|
+
}));
|
|
36810
|
+
}
|
|
36811
|
+
/**
|
|
36812
|
+
* One Post's API response. See {@link loadApiPostResponses}.
|
|
36813
|
+
*
|
|
36814
|
+
* @param deps - Services and app config
|
|
36815
|
+
* @param post - The Post
|
|
36816
|
+
* @param options - `collectionIds` adds the Post's shared Thread collections
|
|
36817
|
+
* @returns The Post's response
|
|
36818
|
+
* @example
|
|
36819
|
+
* return c.json(await loadApiPostResponse(c.var, post));
|
|
36820
|
+
*/ async function loadApiPostResponse(deps, post, options = {}) {
|
|
36821
|
+
const [response] = await loadApiPostResponses(deps, [post], options);
|
|
36822
|
+
if (!response) throw new Error(`No response built for post ${post.id}`);
|
|
36823
|
+
return response;
|
|
36824
|
+
}
|
|
36736
36825
|
//#endregion
|
|
36737
36826
|
//#region src/lib/address.ts
|
|
36738
36827
|
/**
|
|
@@ -36795,18 +36884,17 @@ var PostSlugQuerySchema = z.discriminatedUnion("mode", [z.object({
|
|
|
36795
36884
|
})]);
|
|
36796
36885
|
postsApiRoutes.get("/", requireAuthApi(), async (c) => {
|
|
36797
36886
|
const { format, status, cursor, limit } = parseValidated(ListPostsQuerySchema, c.req.query());
|
|
36887
|
+
const listStatus = status ?? "published";
|
|
36798
36888
|
const { posts, nextCursor } = await c.var.services.posts.listPage({
|
|
36799
36889
|
format,
|
|
36800
|
-
status:
|
|
36890
|
+
status: listStatus,
|
|
36891
|
+
...apiPostListOrder(listStatus)
|
|
36801
36892
|
}, {
|
|
36802
36893
|
cursor,
|
|
36803
36894
|
limit
|
|
36804
36895
|
});
|
|
36805
|
-
const postIds = posts.map((p) => p.id);
|
|
36806
|
-
const mediaMap = await c.var.services.media.getByPostIds(postIds);
|
|
36807
|
-
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix } = c.var.appConfig;
|
|
36808
36896
|
return c.json({
|
|
36809
|
-
posts:
|
|
36897
|
+
posts: await loadApiPostResponses(c.var, posts),
|
|
36810
36898
|
nextCursor
|
|
36811
36899
|
});
|
|
36812
36900
|
});
|
|
@@ -36832,20 +36920,10 @@ postsApiRoutes.get("/:id/content", requireAuthApi(), async (c) => {
|
|
|
36832
36920
|
});
|
|
36833
36921
|
postsApiRoutes.get("/:id", requireAuthApi(), async (c) => {
|
|
36834
36922
|
const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
|
|
36835
|
-
const [post,
|
|
36836
|
-
c.var.services.posts.getById(id),
|
|
36837
|
-
c.var.services.media.getByPostId(id),
|
|
36838
|
-
c.var.services.collections.getCollectionsByPostId(id),
|
|
36839
|
-
c.var.services.posts.getThreadPosition(id)
|
|
36840
|
-
]);
|
|
36923
|
+
const [post, threadPosition] = await Promise.all([c.var.services.posts.getById(id), c.var.services.posts.getThreadPosition(id)]);
|
|
36841
36924
|
const foundPost = assertFound(post, "Post");
|
|
36842
|
-
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix } = c.var.appConfig;
|
|
36843
|
-
const collectionIds = threadCollections.map((col) => col.id);
|
|
36844
36925
|
return c.json({
|
|
36845
|
-
...
|
|
36846
|
-
collectionIds,
|
|
36847
|
-
attachments: mediaList.map((m) => toApiAttachment(m, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix))
|
|
36848
|
-
}),
|
|
36926
|
+
...await loadApiPostResponse(c.var, foundPost, { collectionIds: true }),
|
|
36849
36927
|
threadPosition
|
|
36850
36928
|
});
|
|
36851
36929
|
});
|
|
@@ -36885,10 +36963,8 @@ postsApiRoutes.post("/", requireAuthApi(), async (c) => {
|
|
|
36885
36963
|
maxParagraphs: c.var.appConfig.summaryMaxParagraphs,
|
|
36886
36964
|
maxChars: c.var.appConfig.summaryMaxChars
|
|
36887
36965
|
});
|
|
36888
|
-
const mediaList = await c.var.services.media.getByPostId(post.id);
|
|
36889
|
-
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix } = c.var.appConfig;
|
|
36890
36966
|
await triggerGitHubSyncInline(c);
|
|
36891
|
-
return c.json(
|
|
36967
|
+
return c.json(await loadApiPostResponse(c.var, post), 201);
|
|
36892
36968
|
});
|
|
36893
36969
|
postsApiRoutes.put("/:id", requireAuthApi(), async (c) => {
|
|
36894
36970
|
const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
|
|
@@ -36924,9 +37000,7 @@ postsApiRoutes.put("/:id", requireAuthApi(), async (c) => {
|
|
|
36924
37000
|
maxChars: c.var.appConfig.summaryMaxChars
|
|
36925
37001
|
}), "Post");
|
|
36926
37002
|
await triggerGitHubSyncInline(c);
|
|
36927
|
-
|
|
36928
|
-
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix } = c.var.appConfig;
|
|
36929
|
-
return c.json(toApiPost(post, { attachments: mediaList.map((m) => toApiAttachment(m, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix)) }));
|
|
37003
|
+
return c.json(await loadApiPostResponse(c.var, post));
|
|
36930
37004
|
});
|
|
36931
37005
|
var SetLanguageSchema = z.object({ language: ContentLanguageSchema });
|
|
36932
37006
|
var TranslationCandidatesQuerySchema = z.object({
|
|
@@ -37039,6 +37113,417 @@ postsApiRoutes.delete("/:id", requireAuthApi(), async (c) => {
|
|
|
37039
37113
|
return c.json({ success: true });
|
|
37040
37114
|
});
|
|
37041
37115
|
//#endregion
|
|
37116
|
+
//#region src/lib/tiptap-to-markdown.ts
|
|
37117
|
+
/**
|
|
37118
|
+
* Tiptap JSON → Markdown Converter
|
|
37119
|
+
*
|
|
37120
|
+
* Converts Tiptap JSON documents to Markdown using the official
|
|
37121
|
+
* Tiptap MarkdownManager and Jant's shared markdown schema.
|
|
37122
|
+
*/
|
|
37123
|
+
/**
|
|
37124
|
+
* Converts a Tiptap JSON document to a Markdown string.
|
|
37125
|
+
*
|
|
37126
|
+
* Throws rather than returning an empty string: a caller writing the result
|
|
37127
|
+
* somewhere (an export, a text attachment) would otherwise replace the
|
|
37128
|
+
* content with nothing and say nothing.
|
|
37129
|
+
*
|
|
37130
|
+
* @param json - Tiptap JSON document string
|
|
37131
|
+
* @returns Markdown string
|
|
37132
|
+
* @throws {SyntaxError} When `json` is not JSON
|
|
37133
|
+
* @throws {Error} When the root node is not a `doc`
|
|
37134
|
+
*
|
|
37135
|
+
* @example
|
|
37136
|
+
* ```ts
|
|
37137
|
+
* const md = tiptapJsonToMarkdown('{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Hello"}]}]}');
|
|
37138
|
+
* // "Hello"
|
|
37139
|
+
* ```
|
|
37140
|
+
*/ function tiptapJsonToMarkdown(json) {
|
|
37141
|
+
const doc = JSON.parse(json);
|
|
37142
|
+
if (doc.type !== "doc") throw new Error(`A TipTap body's root must be a doc node, not ${JSON.stringify(doc.type)}.`);
|
|
37143
|
+
return serializeMarkdownDocument(doc).trimEnd();
|
|
37144
|
+
}
|
|
37145
|
+
//#endregion
|
|
37146
|
+
//#region src/lib/api-public-posts.ts
|
|
37147
|
+
/**
|
|
37148
|
+
* Public API Post responses
|
|
37149
|
+
*
|
|
37150
|
+
* The reading view of a Post that `/api/public/*` returns: rendered body or
|
|
37151
|
+
* Markdown, public permalink, and public collection references.
|
|
37152
|
+
*/
|
|
37153
|
+
/**
|
|
37154
|
+
* The public Markdown for a post, or null for a historical body that isn't
|
|
37155
|
+
* TipTap JSON. One unreadable row answers null and is logged, rather than
|
|
37156
|
+
* failing the whole listing; `bodyHtml` still falls back to stored HTML.
|
|
37157
|
+
*/ function toPublicBodyMarkdown(postId, body) {
|
|
37158
|
+
try {
|
|
37159
|
+
return tiptapJsonToMarkdown(body);
|
|
37160
|
+
} catch (error) {
|
|
37161
|
+
console.error(`Couldn't convert the body of post ${postId} to Markdown`, error);
|
|
37162
|
+
return null;
|
|
37163
|
+
}
|
|
37164
|
+
}
|
|
37165
|
+
/**
|
|
37166
|
+
* One Post's reading view, from its attachments, its Thread's collections, and
|
|
37167
|
+
* its Thread's Post count.
|
|
37168
|
+
*
|
|
37169
|
+
* @param post - The Post
|
|
37170
|
+
* @param related - What was read about it in the same batch as its page
|
|
37171
|
+
* @param appConfig - Media URLs and the site path prefix
|
|
37172
|
+
* @param options - `content: "markdown"` returns `bodyMarkdown` instead of the
|
|
37173
|
+
* rendered body
|
|
37174
|
+
* @returns The public response
|
|
37175
|
+
* @example
|
|
37176
|
+
* toPublicPost(post, { media: [], collections: [], threadPostCount: 1 }, config);
|
|
37177
|
+
*/ function toPublicPost(post, related, appConfig, options) {
|
|
37178
|
+
const { r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix, storageDriver } = appConfig;
|
|
37179
|
+
const previewImagePublicUrl = getPublicUrlForProvider(storageDriver, r2PublicUrl, s3PublicUrl, localPublicUrl);
|
|
37180
|
+
const previewImageUrl = post.previewImageKey ? getImageUrl(getMediaUrl(post.previewImageKey, previewImagePublicUrl, sitePathPrefix), imageTransformUrl, {
|
|
37181
|
+
width: 1280,
|
|
37182
|
+
quality: 80,
|
|
37183
|
+
format: "auto",
|
|
37184
|
+
fit: "scale-down"
|
|
37185
|
+
}) : null;
|
|
37186
|
+
const base = {
|
|
37187
|
+
id: post.id,
|
|
37188
|
+
format: post.format,
|
|
37189
|
+
status: "published",
|
|
37190
|
+
visibility: post.visibility,
|
|
37191
|
+
slug: post.slug,
|
|
37192
|
+
permalink: toPublicPath(`/${post.slug}`, sitePathPrefix),
|
|
37193
|
+
quoteText: post.quoteText,
|
|
37194
|
+
summary: post.summary,
|
|
37195
|
+
rating: post.rating,
|
|
37196
|
+
previewKind: post.previewKind,
|
|
37197
|
+
previewProvider: post.previewProvider,
|
|
37198
|
+
previewImageUrl,
|
|
37199
|
+
replyToId: post.replyToId,
|
|
37200
|
+
threadId: post.threadId,
|
|
37201
|
+
language: post.language,
|
|
37202
|
+
translationGroupId: post.translationGroupId,
|
|
37203
|
+
quietReply: post.quietReply,
|
|
37204
|
+
pinnedAt: post.pinnedAt,
|
|
37205
|
+
featuredAt: post.featuredAt,
|
|
37206
|
+
publishedAt: post.publishedAt,
|
|
37207
|
+
lastActivityAt: post.lastActivityAt,
|
|
37208
|
+
threadUpdatedAt: post.threadUpdatedAt,
|
|
37209
|
+
threadPostCount: related.threadPostCount,
|
|
37210
|
+
createdAt: post.createdAt,
|
|
37211
|
+
updatedAt: post.updatedAt,
|
|
37212
|
+
attachments: related.media.map((media) => toApiAttachment(media, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix)),
|
|
37213
|
+
collections: related.collections.map((collection) => ({
|
|
37214
|
+
id: collection.id,
|
|
37215
|
+
slug: collection.slug,
|
|
37216
|
+
title: collection.title,
|
|
37217
|
+
url: toPublicPath(getCollectionPagePath(collection.slug), sitePathPrefix)
|
|
37218
|
+
}))
|
|
37219
|
+
};
|
|
37220
|
+
const contentFields = options?.content === "markdown" ? { bodyMarkdown: post.body ? toPublicBodyMarkdown(post.id, post.body) : null } : {
|
|
37221
|
+
bodyHtml: post.bodyHtml,
|
|
37222
|
+
bodyText: post.bodyText
|
|
37223
|
+
};
|
|
37224
|
+
if (post.format === "quote") return {
|
|
37225
|
+
...base,
|
|
37226
|
+
...contentFields,
|
|
37227
|
+
sourceName: post.title,
|
|
37228
|
+
sourceUrl: post.url
|
|
37229
|
+
};
|
|
37230
|
+
return {
|
|
37231
|
+
...base,
|
|
37232
|
+
...contentFields,
|
|
37233
|
+
title: post.title,
|
|
37234
|
+
url: post.url
|
|
37235
|
+
};
|
|
37236
|
+
}
|
|
37237
|
+
/**
|
|
37238
|
+
* Reading-view responses for Posts already loaded. Attachments, Thread
|
|
37239
|
+
* collections, and Thread Post counts are each read in one batch.
|
|
37240
|
+
*
|
|
37241
|
+
* @param deps - Services and app config; a request's `c.var`
|
|
37242
|
+
* @param posts - Posts to respond with, in order
|
|
37243
|
+
* @param options - `content: "markdown"` returns `bodyMarkdown`
|
|
37244
|
+
* @returns One response per Post, in the same order
|
|
37245
|
+
* @example
|
|
37246
|
+
* const responses = await loadPublicPostResponses(c.var, page.posts, {});
|
|
37247
|
+
*/ async function loadPublicPostResponses(deps, posts, options = {}) {
|
|
37248
|
+
if (posts.length === 0) return [];
|
|
37249
|
+
const { services, appConfig } = deps;
|
|
37250
|
+
const postIds = posts.map((post) => post.id);
|
|
37251
|
+
const [mediaMap, collectionsMap, threadPostCounts] = await Promise.all([
|
|
37252
|
+
services.media.getByPostIds(postIds),
|
|
37253
|
+
services.collections.getCollectionsByPostIds(postIds),
|
|
37254
|
+
services.posts.countThreadPosts(posts.map((post) => post.threadId))
|
|
37255
|
+
]);
|
|
37256
|
+
return posts.map((post) => toPublicPost(post, {
|
|
37257
|
+
media: mediaMap.get(post.id) ?? [],
|
|
37258
|
+
collections: collectionsMap.get(post.id) ?? [],
|
|
37259
|
+
threadPostCount: threadPostCounts.get(post.threadId) ?? 0
|
|
37260
|
+
}, appConfig, options));
|
|
37261
|
+
}
|
|
37262
|
+
//#endregion
|
|
37263
|
+
//#region src/lib/api-threads.ts
|
|
37264
|
+
/**
|
|
37265
|
+
* API Thread responses
|
|
37266
|
+
*
|
|
37267
|
+
* The Thread object the author API, the public API, and MCP return. One shape
|
|
37268
|
+
* for all three, parameterized by how each surface renders a Post and how it
|
|
37269
|
+
* names one: the author API's Post is the editing view, the public API's the
|
|
37270
|
+
* reading view.
|
|
37271
|
+
*/
|
|
37272
|
+
/**
|
|
37273
|
+
* Every Post a set of Thread responses renders, so their attachments and
|
|
37274
|
+
* counts can be read in one batch: each root, then the replies its fold shows.
|
|
37275
|
+
*
|
|
37276
|
+
* @param summaries - Threads to respond with
|
|
37277
|
+
* @returns The Posts, each once
|
|
37278
|
+
* @example
|
|
37279
|
+
* const responses = await render(collectThreadResponsePosts(summaries));
|
|
37280
|
+
*/ function collectThreadResponsePosts(summaries) {
|
|
37281
|
+
const seen = /* @__PURE__ */ new Map();
|
|
37282
|
+
for (const { root, fold } of summaries) {
|
|
37283
|
+
seen.set(root.id, root);
|
|
37284
|
+
if (!fold) continue;
|
|
37285
|
+
for (const post of [
|
|
37286
|
+
...fold.leadingReplies,
|
|
37287
|
+
...fold.trailingReplies,
|
|
37288
|
+
fold.latestReply
|
|
37289
|
+
]) seen.set(post.id, post);
|
|
37290
|
+
}
|
|
37291
|
+
return [...seen.values()];
|
|
37292
|
+
}
|
|
37293
|
+
/**
|
|
37294
|
+
* One Thread's response, from Post responses already rendered.
|
|
37295
|
+
*
|
|
37296
|
+
* @param summary - The Thread
|
|
37297
|
+
* @param respond - The rendered response for a Post in it
|
|
37298
|
+
* @param reference - How the surface names the Post a fold leaves out
|
|
37299
|
+
* @returns The Thread object
|
|
37300
|
+
* @example
|
|
37301
|
+
* toApiThreadResponse(summary, (post) => byId.get(post.id)!, toGap);
|
|
37302
|
+
*/ function toApiThreadResponse(summary, respond, reference) {
|
|
37303
|
+
const { root, fold } = summary;
|
|
37304
|
+
const response = {
|
|
37305
|
+
id: root.id,
|
|
37306
|
+
postCount: summary.postCount,
|
|
37307
|
+
lastActivityAt: root.lastActivityAt,
|
|
37308
|
+
threadUpdatedAt: root.threadUpdatedAt,
|
|
37309
|
+
root: respond(root)
|
|
37310
|
+
};
|
|
37311
|
+
if (fold === null) response.fold = {
|
|
37312
|
+
leading: [],
|
|
37313
|
+
hidden: 0,
|
|
37314
|
+
gap: null,
|
|
37315
|
+
trailing: []
|
|
37316
|
+
};
|
|
37317
|
+
else if (fold) response.fold = {
|
|
37318
|
+
leading: fold.leadingReplies.map(respond),
|
|
37319
|
+
hidden: fold.hiddenCount,
|
|
37320
|
+
gap: fold.firstHiddenReply ? reference(fold.firstHiddenReply) : null,
|
|
37321
|
+
trailing: [...fold.trailingReplies, fold.latestReply].map(respond)
|
|
37322
|
+
};
|
|
37323
|
+
return response;
|
|
37324
|
+
}
|
|
37325
|
+
/**
|
|
37326
|
+
* The author API's and MCP's Thread objects for Threads already listed.
|
|
37327
|
+
*
|
|
37328
|
+
* @param deps - Services and app config
|
|
37329
|
+
* @param summaries - Threads to respond with, in order
|
|
37330
|
+
* @returns One Thread object per summary, in the same order
|
|
37331
|
+
* @example
|
|
37332
|
+
* const threads = await loadApiThreadResponses(c.var, page.threads);
|
|
37333
|
+
*/ async function loadApiThreadResponses(deps, summaries) {
|
|
37334
|
+
return buildThreadResponses(summaries, (posts) => loadApiPostResponses(deps, posts), (post) => ({
|
|
37335
|
+
id: post.id,
|
|
37336
|
+
slug: post.slug
|
|
37337
|
+
}));
|
|
37338
|
+
}
|
|
37339
|
+
/**
|
|
37340
|
+
* The public API's Thread objects for Threads already listed.
|
|
37341
|
+
*
|
|
37342
|
+
* @param deps - Services and app config
|
|
37343
|
+
* @param summaries - Threads to respond with, in order
|
|
37344
|
+
* @param options - `content: "markdown"` returns `bodyMarkdown` on every Post
|
|
37345
|
+
* @returns One Thread object per summary, in the same order
|
|
37346
|
+
* @example
|
|
37347
|
+
* const threads = await loadPublicThreadResponses(c.var, page.threads, {});
|
|
37348
|
+
*/ async function loadPublicThreadResponses(deps, summaries, options = {}) {
|
|
37349
|
+
return buildThreadResponses(summaries, (posts) => loadPublicPostResponses(deps, posts, options), (post) => ({
|
|
37350
|
+
id: post.id,
|
|
37351
|
+
slug: post.slug,
|
|
37352
|
+
permalink: toPublicPath(`/${post.slug}`, deps.appConfig.sitePathPrefix)
|
|
37353
|
+
}));
|
|
37354
|
+
}
|
|
37355
|
+
/** Render every Post the Threads show in one batch, then assemble them. */ async function buildThreadResponses(summaries, render, reference) {
|
|
37356
|
+
const posts = collectThreadResponsePosts(summaries);
|
|
37357
|
+
const responses = await render(posts);
|
|
37358
|
+
const byId = new Map(posts.map((post, index) => [post.id, responses[index]]));
|
|
37359
|
+
return summaries.map((summary) => toApiThreadResponse(summary, (post) => {
|
|
37360
|
+
const response = byId.get(post.id);
|
|
37361
|
+
if (!response) throw new Error(`No response built for post ${post.id}`);
|
|
37362
|
+
return response;
|
|
37363
|
+
}, reference));
|
|
37364
|
+
}
|
|
37365
|
+
//#endregion
|
|
37366
|
+
//#region src/lib/thread-query.ts
|
|
37367
|
+
/**
|
|
37368
|
+
* Thread list queries
|
|
37369
|
+
*
|
|
37370
|
+
* Reads the filter dimensions a Thread list takes — the archive's, from the
|
|
37371
|
+
* same registry — out of an HTTP query string or MCP arguments, so the public
|
|
37372
|
+
* API, the author API, and MCP accept one vocabulary.
|
|
37373
|
+
*
|
|
37374
|
+
* One word differs from the archive page. A Thread list left unfiltered shows
|
|
37375
|
+
* what the homepage shows, so it needs a word for "every visibility a reader
|
|
37376
|
+
* may see": `visibility=any`. The registry's `visibility=all` is an old
|
|
37377
|
+
* spelling of leaving the parameter out, which here would mean the homepage's
|
|
37378
|
+
* set — the opposite of what the word says — so a Thread list refuses it.
|
|
37379
|
+
*/ var READER_VISIBILITIES = [
|
|
37380
|
+
"public",
|
|
37381
|
+
"featured",
|
|
37382
|
+
"hidden",
|
|
37383
|
+
"any"
|
|
37384
|
+
];
|
|
37385
|
+
var AUTHOR_VISIBILITIES = [...READER_VISIBILITIES, "private"];
|
|
37386
|
+
/** Spellings the registry reads that stay valid here. */ var LEGACY_VISIBILITIES = ["latest_hidden"];
|
|
37387
|
+
function allowedVisibilities(audience) {
|
|
37388
|
+
return audience === "reader" ? READER_VISIBILITIES : AUTHOR_VISIBILITIES;
|
|
37389
|
+
}
|
|
37390
|
+
/**
|
|
37391
|
+
* Read a Thread list's filter dimensions.
|
|
37392
|
+
*
|
|
37393
|
+
* @param read - Reads one parameter; `undefined` when absent
|
|
37394
|
+
* @param present - Every parameter name the request carries
|
|
37395
|
+
* @param options.allow - The endpoint's own parameters, which aren't
|
|
37396
|
+
* dimensions; anything else unknown is refused
|
|
37397
|
+
* @param options.audience - A reader may not name `private`
|
|
37398
|
+
* @param options.loadCollections - Loads the collection vocabulary, called only
|
|
37399
|
+
* when a collection is named
|
|
37400
|
+
* @returns The selection, or `empty` when a named collection doesn't exist
|
|
37401
|
+
* @throws {ValidationError} On an unknown parameter or an unreadable value
|
|
37402
|
+
* @example
|
|
37403
|
+
* const parsed = await parseThreadSelection(read, Object.keys(query), {
|
|
37404
|
+
* allow: ["cursor", "limit"],
|
|
37405
|
+
* audience: "reader",
|
|
37406
|
+
* loadCollections: () => services.collections.list(),
|
|
37407
|
+
* });
|
|
37408
|
+
*/ async function parseThreadSelection(read, present, options) {
|
|
37409
|
+
const visibility = read("visibility");
|
|
37410
|
+
if (visibility !== void 0) {
|
|
37411
|
+
const allowed = allowedVisibilities(options.audience);
|
|
37412
|
+
if (visibility === "all") throw new ValidationError("visibility=all isn't accepted here. Leave visibility out for what the homepage lists, or pass visibility=any for everything.");
|
|
37413
|
+
if (!allowed.includes(visibility) && !LEGACY_VISIBILITIES.includes(visibility)) throw new ValidationError(`Invalid visibility value. Allowed: ${allowed.join(", ")}`);
|
|
37414
|
+
}
|
|
37415
|
+
const includeHidden = visibility === "any";
|
|
37416
|
+
const readDimension = (key) => key === "visibility" && includeHidden ? void 0 : read(key);
|
|
37417
|
+
const parsed = parsePostFilterSelectionStrict(readDimension, present, { collections: readCollectionSlugs(readDimension).length > 0 ? buildCollectionVocabulary(await options.loadCollections()) : EMPTY_COLLECTION_VOCABULARY }, { allow: options.allow });
|
|
37418
|
+
if (parsed.ok) return {
|
|
37419
|
+
kind: "selection",
|
|
37420
|
+
selection: parsed.selection,
|
|
37421
|
+
includeHidden
|
|
37422
|
+
};
|
|
37423
|
+
if (parsed.issues.every((issue) => issue.param === "collection")) return { kind: "empty" };
|
|
37424
|
+
throw new ValidationError(parsed.issues[0]?.message ?? "Validation failed");
|
|
37425
|
+
}
|
|
37426
|
+
/**
|
|
37427
|
+
* Read `include`: a comma-separated list of extras to attach to each Thread.
|
|
37428
|
+
*
|
|
37429
|
+
* @param raw - The parameter's value, or `undefined`
|
|
37430
|
+
* @returns Whether the fold was asked for
|
|
37431
|
+
* @throws {ValidationError} On a value this endpoint doesn't offer
|
|
37432
|
+
* @example
|
|
37433
|
+
* parseThreadInclude("fold"); // { fold: true }
|
|
37434
|
+
*/ function parseThreadInclude(raw) {
|
|
37435
|
+
if (raw === void 0 || raw === "") return { fold: false };
|
|
37436
|
+
const values = raw.split(",").map((value) => value.trim());
|
|
37437
|
+
for (const value of values) if (value !== "fold") throw new ValidationError(`Invalid include value "${value}". Allowed: fold`);
|
|
37438
|
+
return { fold: values.includes("fold") };
|
|
37439
|
+
}
|
|
37440
|
+
//#endregion
|
|
37441
|
+
//#region src/routes/api/threads.ts
|
|
37442
|
+
/**
|
|
37443
|
+
* Threads API Routes
|
|
37444
|
+
*
|
|
37445
|
+
* The author's view of Threads: every status and visibility, Posts in the
|
|
37446
|
+
* editing view. The reader's view is `/api/public/threads`.
|
|
37447
|
+
*/ var threadsApiRoutes = new Hono();
|
|
37448
|
+
threadsApiRoutes.use("*", requireAuthApi());
|
|
37449
|
+
/** The list's own parameters; everything else is a filter dimension. */ var ListThreadsQuerySchema$1 = z.object({
|
|
37450
|
+
status: StatusSchema.optional(),
|
|
37451
|
+
lang: ContentLanguageSchema.optional(),
|
|
37452
|
+
sort: z.enum(THREAD_SORTS).optional(),
|
|
37453
|
+
include: z.string().optional(),
|
|
37454
|
+
cursor: z.string().optional(),
|
|
37455
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(20)
|
|
37456
|
+
});
|
|
37457
|
+
var LIST_PARAMS$1 = [
|
|
37458
|
+
"status",
|
|
37459
|
+
"lang",
|
|
37460
|
+
"sort",
|
|
37461
|
+
"include",
|
|
37462
|
+
"cursor",
|
|
37463
|
+
"limit"
|
|
37464
|
+
];
|
|
37465
|
+
var GetThreadQuerySchema$1 = z.object({ include: z.string().optional() });
|
|
37466
|
+
var ListThreadPostsQuerySchema$1 = z.object({
|
|
37467
|
+
status: StatusSchema.optional(),
|
|
37468
|
+
cursor: z.string().optional(),
|
|
37469
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(100)
|
|
37470
|
+
});
|
|
37471
|
+
threadsApiRoutes.get("/", async (c) => {
|
|
37472
|
+
const query = parseValidated(ListThreadsQuerySchema$1, c.req.query());
|
|
37473
|
+
const { fold } = parseThreadInclude(query.include);
|
|
37474
|
+
const parsed = await parseThreadSelection((key) => c.req.query(key), Object.keys(c.req.query()), {
|
|
37475
|
+
allow: LIST_PARAMS$1,
|
|
37476
|
+
audience: "author",
|
|
37477
|
+
loadCollections: () => c.var.services.collections.list()
|
|
37478
|
+
});
|
|
37479
|
+
if (parsed.kind === "empty") return c.json({
|
|
37480
|
+
threads: [],
|
|
37481
|
+
nextCursor: null
|
|
37482
|
+
});
|
|
37483
|
+
const { threads, nextCursor } = await c.var.services.threads.listThreads({
|
|
37484
|
+
audience: "author",
|
|
37485
|
+
status: query.status,
|
|
37486
|
+
selection: parsed.selection,
|
|
37487
|
+
lang: query.lang,
|
|
37488
|
+
sort: query.sort,
|
|
37489
|
+
fold
|
|
37490
|
+
}, {
|
|
37491
|
+
cursor: query.cursor,
|
|
37492
|
+
limit: query.limit
|
|
37493
|
+
});
|
|
37494
|
+
return c.json({
|
|
37495
|
+
threads: await loadApiThreadResponses(c.var, threads),
|
|
37496
|
+
nextCursor
|
|
37497
|
+
});
|
|
37498
|
+
});
|
|
37499
|
+
threadsApiRoutes.get("/:id", async (c) => {
|
|
37500
|
+
const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
|
|
37501
|
+
const { include } = parseValidated(GetThreadQuerySchema$1, c.req.query());
|
|
37502
|
+
const root = await c.var.services.threads.findRoot({ id }, "author");
|
|
37503
|
+
if (!root) throw new NotFoundError("Thread");
|
|
37504
|
+
const summaries = await c.var.services.threads.summarize([root], parseThreadInclude(include));
|
|
37505
|
+
const [thread] = await loadApiThreadResponses(c.var, summaries);
|
|
37506
|
+
if (!thread) throw new NotFoundError("Thread");
|
|
37507
|
+
return c.json(thread);
|
|
37508
|
+
});
|
|
37509
|
+
threadsApiRoutes.get("/:id/posts", async (c) => {
|
|
37510
|
+
const id = parseIdParam(c.req.param("id"), ID_PREFIX.post);
|
|
37511
|
+
const { status, cursor, limit } = parseValidated(ListThreadPostsQuerySchema$1, c.req.query());
|
|
37512
|
+
const root = await c.var.services.threads.findRoot({ id }, "author");
|
|
37513
|
+
if (!root) throw new NotFoundError("Thread");
|
|
37514
|
+
const { posts, nextCursor } = await c.var.services.threads.listPosts(root.id, {
|
|
37515
|
+
audience: "author",
|
|
37516
|
+
status
|
|
37517
|
+
}, {
|
|
37518
|
+
cursor,
|
|
37519
|
+
limit
|
|
37520
|
+
});
|
|
37521
|
+
return c.json({
|
|
37522
|
+
posts: await loadApiPostResponses(c.var, posts),
|
|
37523
|
+
nextCursor
|
|
37524
|
+
});
|
|
37525
|
+
});
|
|
37526
|
+
//#endregion
|
|
37042
37527
|
//#region src/routes/api/attachments.ts
|
|
37043
37528
|
/**
|
|
37044
37529
|
* Attachments API Routes
|
|
@@ -38191,6 +38676,78 @@ var AddCollectionThreadToolSchema = z.object({
|
|
|
38191
38676
|
threadId: PostIdSchema
|
|
38192
38677
|
});
|
|
38193
38678
|
var RemoveCollectionThreadToolSchema = AddCollectionThreadToolSchema;
|
|
38679
|
+
/**
|
|
38680
|
+
* The filter dimensions `jant_threads_list` takes, spelled as the HTTP API
|
|
38681
|
+
* and the archive spell them. They reach the same registry parser as a query
|
|
38682
|
+
* string would, so the vocabularies can't drift.
|
|
38683
|
+
*/ var THREAD_FILTER_TOOL_PROPERTIES = {
|
|
38684
|
+
format: {
|
|
38685
|
+
type: "string",
|
|
38686
|
+
enum: [...FORMATS]
|
|
38687
|
+
},
|
|
38688
|
+
collection: {
|
|
38689
|
+
type: "string",
|
|
38690
|
+
description: "Collection slug, or several comma-separated"
|
|
38691
|
+
},
|
|
38692
|
+
year: {
|
|
38693
|
+
type: "integer",
|
|
38694
|
+
description: "Publication year (UTC)"
|
|
38695
|
+
},
|
|
38696
|
+
media: {
|
|
38697
|
+
type: "string",
|
|
38698
|
+
description: "any, none, or comma-separated kinds: image, video, audio, text, document"
|
|
38699
|
+
},
|
|
38700
|
+
title: {
|
|
38701
|
+
type: "string",
|
|
38702
|
+
enum: ["any", "none"]
|
|
38703
|
+
},
|
|
38704
|
+
replies: {
|
|
38705
|
+
type: "string",
|
|
38706
|
+
enum: ["any", "none"]
|
|
38707
|
+
},
|
|
38708
|
+
visibility: {
|
|
38709
|
+
type: "string",
|
|
38710
|
+
enum: [
|
|
38711
|
+
"public",
|
|
38712
|
+
"featured",
|
|
38713
|
+
"hidden",
|
|
38714
|
+
"private"
|
|
38715
|
+
]
|
|
38716
|
+
}
|
|
38717
|
+
};
|
|
38718
|
+
var ListThreadsToolSchema = z.object({
|
|
38719
|
+
cursor: z.string().optional(),
|
|
38720
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(20),
|
|
38721
|
+
status: StatusSchema.optional(),
|
|
38722
|
+
sort: z.enum(THREAD_SORTS).optional(),
|
|
38723
|
+
fold: z.boolean().optional(),
|
|
38724
|
+
lang: ContentLanguageSchema.optional(),
|
|
38725
|
+
format: z.string().optional(),
|
|
38726
|
+
collection: z.string().optional(),
|
|
38727
|
+
year: z.number().int().optional(),
|
|
38728
|
+
media: z.string().optional(),
|
|
38729
|
+
title: z.string().optional(),
|
|
38730
|
+
replies: z.string().optional(),
|
|
38731
|
+
visibility: z.string().optional()
|
|
38732
|
+
});
|
|
38733
|
+
var LIST_THREADS_OWN_PARAMS = [
|
|
38734
|
+
"cursor",
|
|
38735
|
+
"limit",
|
|
38736
|
+
"status",
|
|
38737
|
+
"sort",
|
|
38738
|
+
"fold",
|
|
38739
|
+
"lang"
|
|
38740
|
+
];
|
|
38741
|
+
var GetThreadToolSchema = z.object({
|
|
38742
|
+
id: PostIdSchema,
|
|
38743
|
+
fold: z.boolean().optional()
|
|
38744
|
+
});
|
|
38745
|
+
var ListThreadPostsToolSchema = z.object({
|
|
38746
|
+
id: PostIdSchema,
|
|
38747
|
+
cursor: z.string().optional(),
|
|
38748
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(100),
|
|
38749
|
+
status: StatusSchema.optional()
|
|
38750
|
+
});
|
|
38194
38751
|
var mcpTools = [
|
|
38195
38752
|
{
|
|
38196
38753
|
name: "jant_posts_list",
|
|
@@ -38218,9 +38775,11 @@ var mcpTools = [
|
|
|
38218
38775
|
},
|
|
38219
38776
|
async execute(args, context) {
|
|
38220
38777
|
const input = ListPostsToolSchema.parse(args ?? {});
|
|
38778
|
+
const status = input.status ?? "published";
|
|
38221
38779
|
const { posts, nextCursor } = await context.services.posts.listPage({
|
|
38222
38780
|
format: input.format,
|
|
38223
|
-
status
|
|
38781
|
+
status,
|
|
38782
|
+
...apiPostListOrder(status)
|
|
38224
38783
|
}, {
|
|
38225
38784
|
cursor: input.cursor,
|
|
38226
38785
|
limit: input.limit
|
|
@@ -38269,6 +38828,133 @@ var mcpTools = [
|
|
|
38269
38828
|
return content;
|
|
38270
38829
|
}
|
|
38271
38830
|
},
|
|
38831
|
+
{
|
|
38832
|
+
name: "jant_threads_list",
|
|
38833
|
+
description: "List Threads (a root post and its replies), each with its post count. Takes the archive's filters; sort is activity (default), published, updated, oldest, or rating. Set fold to include the replies the homepage shows. Pass nextCursor back as cursor for the next page.",
|
|
38834
|
+
inputSchema: {
|
|
38835
|
+
type: "object",
|
|
38836
|
+
properties: {
|
|
38837
|
+
cursor: { type: "string" },
|
|
38838
|
+
limit: {
|
|
38839
|
+
type: "integer",
|
|
38840
|
+
minimum: 1,
|
|
38841
|
+
maximum: 100,
|
|
38842
|
+
default: 20
|
|
38843
|
+
},
|
|
38844
|
+
status: {
|
|
38845
|
+
type: "string",
|
|
38846
|
+
enum: [...STATUSES]
|
|
38847
|
+
},
|
|
38848
|
+
sort: {
|
|
38849
|
+
type: "string",
|
|
38850
|
+
enum: [...THREAD_SORTS]
|
|
38851
|
+
},
|
|
38852
|
+
fold: { type: "boolean" },
|
|
38853
|
+
lang: {
|
|
38854
|
+
type: "string",
|
|
38855
|
+
description: "BCP 47 content language"
|
|
38856
|
+
},
|
|
38857
|
+
...THREAD_FILTER_TOOL_PROPERTIES
|
|
38858
|
+
},
|
|
38859
|
+
additionalProperties: false
|
|
38860
|
+
},
|
|
38861
|
+
async execute(args, context) {
|
|
38862
|
+
const input = ListThreadsToolSchema.parse(args ?? {});
|
|
38863
|
+
const filterArgs = Object.fromEntries(Object.entries(input).filter(([key, value]) => value !== void 0 && !LIST_THREADS_OWN_PARAMS.includes(key)));
|
|
38864
|
+
const parsed = await parseThreadSelection((key) => {
|
|
38865
|
+
const value = filterArgs[key];
|
|
38866
|
+
return value === void 0 ? void 0 : String(value);
|
|
38867
|
+
}, Object.keys(filterArgs), {
|
|
38868
|
+
allow: [],
|
|
38869
|
+
audience: "author",
|
|
38870
|
+
loadCollections: () => context.services.collections.list()
|
|
38871
|
+
});
|
|
38872
|
+
if (parsed.kind === "empty") return {
|
|
38873
|
+
threads: [],
|
|
38874
|
+
nextCursor: null
|
|
38875
|
+
};
|
|
38876
|
+
const { threads, nextCursor } = await context.services.threads.listThreads({
|
|
38877
|
+
audience: "author",
|
|
38878
|
+
status: input.status,
|
|
38879
|
+
selection: parsed.selection,
|
|
38880
|
+
lang: input.lang,
|
|
38881
|
+
sort: input.sort,
|
|
38882
|
+
fold: input.fold
|
|
38883
|
+
}, {
|
|
38884
|
+
cursor: input.cursor,
|
|
38885
|
+
limit: input.limit
|
|
38886
|
+
});
|
|
38887
|
+
return {
|
|
38888
|
+
threads: await loadApiThreadResponses(context, threads),
|
|
38889
|
+
nextCursor
|
|
38890
|
+
};
|
|
38891
|
+
}
|
|
38892
|
+
},
|
|
38893
|
+
{
|
|
38894
|
+
name: "jant_threads_get",
|
|
38895
|
+
description: "Get the Thread any post belongs to: its root and post count, and with fold the replies the homepage shows.",
|
|
38896
|
+
inputSchema: {
|
|
38897
|
+
type: "object",
|
|
38898
|
+
properties: {
|
|
38899
|
+
id: {
|
|
38900
|
+
type: "string",
|
|
38901
|
+
description: "TypeID of any post in the Thread"
|
|
38902
|
+
},
|
|
38903
|
+
fold: { type: "boolean" }
|
|
38904
|
+
},
|
|
38905
|
+
required: ["id"],
|
|
38906
|
+
additionalProperties: false
|
|
38907
|
+
},
|
|
38908
|
+
async execute(args, context) {
|
|
38909
|
+
const input = GetThreadToolSchema.parse(args ?? {});
|
|
38910
|
+
const root = await context.services.threads.findRoot({ id: input.id }, "author");
|
|
38911
|
+
if (!root) throw new NotFoundError("Thread");
|
|
38912
|
+
const [thread] = await loadApiThreadResponses(context, await context.services.threads.summarize([root], { fold: input.fold }));
|
|
38913
|
+
return thread;
|
|
38914
|
+
}
|
|
38915
|
+
},
|
|
38916
|
+
{
|
|
38917
|
+
name: "jant_threads_list_posts",
|
|
38918
|
+
description: "List the posts of the Thread any post belongs to, root first, in Thread order. Pass nextCursor back as cursor for the next page.",
|
|
38919
|
+
inputSchema: {
|
|
38920
|
+
type: "object",
|
|
38921
|
+
properties: {
|
|
38922
|
+
id: {
|
|
38923
|
+
type: "string",
|
|
38924
|
+
description: "TypeID of any post in the Thread"
|
|
38925
|
+
},
|
|
38926
|
+
cursor: { type: "string" },
|
|
38927
|
+
limit: {
|
|
38928
|
+
type: "integer",
|
|
38929
|
+
minimum: 1,
|
|
38930
|
+
maximum: 100,
|
|
38931
|
+
default: 100
|
|
38932
|
+
},
|
|
38933
|
+
status: {
|
|
38934
|
+
type: "string",
|
|
38935
|
+
enum: [...STATUSES]
|
|
38936
|
+
}
|
|
38937
|
+
},
|
|
38938
|
+
required: ["id"],
|
|
38939
|
+
additionalProperties: false
|
|
38940
|
+
},
|
|
38941
|
+
async execute(args, context) {
|
|
38942
|
+
const input = ListThreadPostsToolSchema.parse(args ?? {});
|
|
38943
|
+
const root = await context.services.threads.findRoot({ id: input.id }, "author");
|
|
38944
|
+
if (!root) throw new NotFoundError("Thread");
|
|
38945
|
+
const { posts, nextCursor } = await context.services.threads.listPosts(root.id, {
|
|
38946
|
+
audience: "author",
|
|
38947
|
+
status: input.status
|
|
38948
|
+
}, {
|
|
38949
|
+
cursor: input.cursor,
|
|
38950
|
+
limit: input.limit
|
|
38951
|
+
});
|
|
38952
|
+
return {
|
|
38953
|
+
posts: await serializePosts(posts, context),
|
|
38954
|
+
nextCursor
|
|
38955
|
+
};
|
|
38956
|
+
}
|
|
38957
|
+
},
|
|
38272
38958
|
{
|
|
38273
38959
|
name: "jant_posts_create",
|
|
38274
38960
|
description: "Create a post. Supports the same JSON body as POST /api/posts.",
|
|
@@ -39054,28 +39740,15 @@ async function uploadMediaFromBase64(input, context) {
|
|
|
39054
39740
|
if (!media) throw new NotFoundError("Media");
|
|
39055
39741
|
return serializeMedia(media, context.appConfig);
|
|
39056
39742
|
}
|
|
39057
|
-
|
|
39058
|
-
|
|
39059
|
-
const postIds = posts.map((post) => post.id);
|
|
39060
|
-
const [mediaMap, collectionMap] = await Promise.all([context.services.media.getByPostIds(postIds), context.services.collections.getCollectionsByPostIds(postIds)]);
|
|
39061
|
-
return posts.map((post) => toApiPost(post, {
|
|
39062
|
-
attachments: serializeAttachments(mediaMap.get(post.id) ?? [], context.appConfig),
|
|
39063
|
-
collectionIds: (collectionMap.get(post.id) ?? []).map((collection) => collection.id)
|
|
39064
|
-
}));
|
|
39743
|
+
function serializePosts(posts, context) {
|
|
39744
|
+
return loadApiPostResponses(context, posts, { collectionIds: true });
|
|
39065
39745
|
}
|
|
39066
|
-
|
|
39067
|
-
|
|
39068
|
-
return toApiPost(post, {
|
|
39069
|
-
attachments: serializeAttachments(mediaList, context.appConfig),
|
|
39070
|
-
collectionIds: threadCollections.map((collection) => collection.id)
|
|
39071
|
-
});
|
|
39746
|
+
function serializePost(post, context) {
|
|
39747
|
+
return loadApiPostResponse(context, post, { collectionIds: true });
|
|
39072
39748
|
}
|
|
39073
39749
|
function serializeMedia(media, appConfig) {
|
|
39074
39750
|
return toApiMedia(media, appConfig);
|
|
39075
39751
|
}
|
|
39076
|
-
function serializeAttachments(mediaList, appConfig) {
|
|
39077
|
-
return mediaList.map((media) => toApiAttachment(media, appConfig.r2PublicUrl, appConfig.imageTransformUrl, appConfig.s3PublicUrl, appConfig.localPublicUrl, appConfig.sitePathPrefix));
|
|
39078
|
-
}
|
|
39079
39752
|
//#endregion
|
|
39080
39753
|
//#region src/routes/api/mcp.ts
|
|
39081
39754
|
var mcpApiRoutes = new Hono();
|
|
@@ -39227,36 +39900,6 @@ customUrlsApiRoutes.delete("/:id", requireAuthApi(), async (c) => {
|
|
|
39227
39900
|
return root.lastActivityAt ?? root.publishedAt ?? root.updatedAt;
|
|
39228
39901
|
}
|
|
39229
39902
|
//#endregion
|
|
39230
|
-
//#region src/lib/tiptap-to-markdown.ts
|
|
39231
|
-
/**
|
|
39232
|
-
* Tiptap JSON → Markdown Converter
|
|
39233
|
-
*
|
|
39234
|
-
* Converts Tiptap JSON documents to Markdown using the official
|
|
39235
|
-
* Tiptap MarkdownManager and Jant's shared markdown schema.
|
|
39236
|
-
*/
|
|
39237
|
-
/**
|
|
39238
|
-
* Converts a Tiptap JSON document to a Markdown string.
|
|
39239
|
-
*
|
|
39240
|
-
* Throws rather than returning an empty string: a caller writing the result
|
|
39241
|
-
* somewhere (an export, a text attachment) would otherwise replace the
|
|
39242
|
-
* content with nothing and say nothing.
|
|
39243
|
-
*
|
|
39244
|
-
* @param json - Tiptap JSON document string
|
|
39245
|
-
* @returns Markdown string
|
|
39246
|
-
* @throws {SyntaxError} When `json` is not JSON
|
|
39247
|
-
* @throws {Error} When the root node is not a `doc`
|
|
39248
|
-
*
|
|
39249
|
-
* @example
|
|
39250
|
-
* ```ts
|
|
39251
|
-
* const md = tiptapJsonToMarkdown('{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Hello"}]}]}');
|
|
39252
|
-
* // "Hello"
|
|
39253
|
-
* ```
|
|
39254
|
-
*/ function tiptapJsonToMarkdown(json) {
|
|
39255
|
-
const doc = JSON.parse(json);
|
|
39256
|
-
if (doc.type !== "doc") throw new Error(`A TipTap body's root must be a doc node, not ${JSON.stringify(doc.type)}.`);
|
|
39257
|
-
return serializeMarkdownDocument(doc).trimEnd();
|
|
39258
|
-
}
|
|
39259
|
-
//#endregion
|
|
39260
39903
|
//#region src/lib/hugo-markdown.ts
|
|
39261
39904
|
/**
|
|
39262
39905
|
* Shared Hugo Markdown parsing utilities.
|
|
@@ -73196,6 +73839,10 @@ function createPathService(db, siteId, databaseSchema = sqliteSchemaBundle) {
|
|
|
73196
73839
|
* visibility (public/latest_hidden/private), featuredAt, and pinnedAt timestamp.
|
|
73197
73840
|
*/
|
|
73198
73841
|
/**
|
|
73842
|
+
* The sort mode a cursor into one Thread's Posts records. Distinct from every
|
|
73843
|
+
* `list()` and collection mode, so a position in one never resumes another.
|
|
73844
|
+
*/ var THREAD_POSTS_SORT_MODE = "thread";
|
|
73845
|
+
/**
|
|
73199
73846
|
* Rebuild body HTML using the site's current runtime summary settings.
|
|
73200
73847
|
*
|
|
73201
73848
|
* Internal maintenance routes do not run behind the normal app-config
|
|
@@ -73315,13 +73962,32 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
73315
73962
|
* db.select().from(posts).orderBy(posts.threadId, ...threadOrder());
|
|
73316
73963
|
* sql`ROW_NUMBER() OVER (ORDER BY ${sql.join(threadOrder(), sql`, `)})`;
|
|
73317
73964
|
*/ function threadOrder(direction = "asc") {
|
|
73318
|
-
const terms =
|
|
73319
|
-
sql`CASE WHEN ${posts.replyToId} IS NULL THEN 0 ELSE 1 END`,
|
|
73320
|
-
sql`${posts.createdAt}`,
|
|
73321
|
-
sql`${posts.id}`
|
|
73322
|
-
];
|
|
73965
|
+
const terms = threadSortKeys().map((key) => key.expr);
|
|
73323
73966
|
return direction === "asc" ? terms : terms.map((term) => desc(term));
|
|
73324
73967
|
}
|
|
73968
|
+
/**
|
|
73969
|
+
* {@link threadOrder} as paged sort keys, for walking one Thread with a
|
|
73970
|
+
* cursor. The one definition both read, so a page of a Thread and the
|
|
73971
|
+
* Thread page itself cannot order its posts differently.
|
|
73972
|
+
*/ function threadSortKeys() {
|
|
73973
|
+
return [
|
|
73974
|
+
{
|
|
73975
|
+
expr: sql`CASE WHEN ${posts.replyToId} IS NULL THEN 0 ELSE 1 END`.mapWith(Number),
|
|
73976
|
+
direction: "asc",
|
|
73977
|
+
kind: "number"
|
|
73978
|
+
},
|
|
73979
|
+
{
|
|
73980
|
+
expr: sql`${posts.createdAt}`.mapWith(Number),
|
|
73981
|
+
direction: "asc",
|
|
73982
|
+
kind: "number"
|
|
73983
|
+
},
|
|
73984
|
+
{
|
|
73985
|
+
expr: sql`${posts.id}`,
|
|
73986
|
+
direction: "asc",
|
|
73987
|
+
kind: "id"
|
|
73988
|
+
}
|
|
73989
|
+
];
|
|
73990
|
+
}
|
|
73325
73991
|
function buildYearMonthExpr(column) {
|
|
73326
73992
|
return databaseDialect === "pg" ? sql`to_char(timezone('UTC', to_timestamp(${column})), 'YYYY-MM')` : sql`strftime('%Y-%m', ${column}, 'unixepoch')`;
|
|
73327
73993
|
}
|
|
@@ -73788,6 +74454,10 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
73788
74454
|
)`);
|
|
73789
74455
|
if (options?.hasRating) conditions.push(isNotNull(posts.rating));
|
|
73790
74456
|
if (options?.threadIds !== void 0) conditions.push(inArray(posts.threadId, options.threadIds));
|
|
74457
|
+
if (options?.rootFilters) conditions.push(inArray(posts.threadId, db.select({ id: posts.id }).from(posts).where(and(...buildFilterConditions({
|
|
74458
|
+
...options.rootFilters,
|
|
74459
|
+
excludeReplies: true
|
|
74460
|
+
})))));
|
|
73791
74461
|
return conditions;
|
|
73792
74462
|
}
|
|
73793
74463
|
/**
|
|
@@ -74747,6 +75417,46 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
74747
75417
|
async getThread(rootId) {
|
|
74748
75418
|
return hydratePosts(await db.select().from(posts).where(and(eq(posts.siteId, siteId), eq(posts.threadId, rootId))).orderBy(...threadOrder()));
|
|
74749
75419
|
},
|
|
75420
|
+
async listThreadPostsPage(threadId, options, { cursor, limit }) {
|
|
75421
|
+
const keys = threadSortKeys();
|
|
75422
|
+
const conditions = [
|
|
75423
|
+
eq(posts.siteId, siteId),
|
|
75424
|
+
eq(posts.threadId, threadId),
|
|
75425
|
+
eq(posts.status, options.status ?? "published")
|
|
75426
|
+
];
|
|
75427
|
+
if (cursor) {
|
|
75428
|
+
let values;
|
|
75429
|
+
if (isLegacyPostListCursor(cursor)) {
|
|
75430
|
+
const row = (await db.select(listSortKeyFields(keys)).from(posts).where(and(...conditions, eq(posts.id, cursor))).limit(1))[0];
|
|
75431
|
+
if (!row) throw new ValidationError(MISSING_LEGACY_CURSOR_MESSAGE);
|
|
75432
|
+
values = readListSortKeyValues(keys, row);
|
|
75433
|
+
} else values = decodePostListCursor(cursor, {
|
|
75434
|
+
mode: THREAD_POSTS_SORT_MODE,
|
|
75435
|
+
kinds: keys.map((key) => key.kind)
|
|
75436
|
+
});
|
|
75437
|
+
conditions.push(buildListKeysetCondition(keys, values));
|
|
75438
|
+
}
|
|
75439
|
+
const rows = await db.select({
|
|
75440
|
+
post: posts,
|
|
75441
|
+
sortKey: listSortKeyFields(keys)
|
|
75442
|
+
}).from(posts).where(and(...conditions)).orderBy(...listOrderBy(keys)).limit(limit + 1);
|
|
75443
|
+
const pageRows = rows.slice(0, limit);
|
|
75444
|
+
const lastRow = pageRows[pageRows.length - 1];
|
|
75445
|
+
return {
|
|
75446
|
+
posts: await hydratePosts(pageRows.map((row) => row.post)),
|
|
75447
|
+
nextCursor: rows.length > limit && lastRow ? encodePostListCursor(THREAD_POSTS_SORT_MODE, readListSortKeyValues(keys, lastRow.sortKey)) : null
|
|
75448
|
+
};
|
|
75449
|
+
},
|
|
75450
|
+
async countThreadPosts(threadIds) {
|
|
75451
|
+
const counts = /* @__PURE__ */ new Map();
|
|
75452
|
+
if (threadIds.length === 0) return counts;
|
|
75453
|
+
const rows = await batchQueryRows([...new Set(threadIds)], (chunk) => db.select({
|
|
75454
|
+
threadId: posts.threadId,
|
|
75455
|
+
count: sql`CAST(count(*) AS INTEGER)`.as("count")
|
|
75456
|
+
}).from(posts).where(and(eq(posts.siteId, siteId), inArray(posts.threadId, chunk), eq(posts.status, "published"))).groupBy(posts.threadId));
|
|
75457
|
+
for (const row of rows) counts.set(row.threadId, row.count);
|
|
75458
|
+
return counts;
|
|
75459
|
+
},
|
|
74750
75460
|
async getThreadPosition(postId) {
|
|
74751
75461
|
const target = (await db.select({
|
|
74752
75462
|
replyToId: posts.replyToId,
|
|
@@ -75041,28 +75751,30 @@ function createPostService(db, config, siteId, paths, databaseSchema = sqliteSch
|
|
|
75041
75751
|
},
|
|
75042
75752
|
async getThreadTimelineContext(rootIds) {
|
|
75043
75753
|
if (rootIds.length === 0) return /* @__PURE__ */ new Map();
|
|
75044
|
-
const
|
|
75045
|
-
|
|
75046
|
-
|
|
75047
|
-
|
|
75754
|
+
const contextRows = await batchQueryRows([...new Set(rootIds)], (chunk) => {
|
|
75755
|
+
const rankedReplies = db.select({
|
|
75756
|
+
id: posts.id,
|
|
75757
|
+
threadId: posts.threadId,
|
|
75758
|
+
firstReplyRank: sql`CAST(ROW_NUMBER() OVER (
|
|
75048
75759
|
PARTITION BY ${posts.threadId}
|
|
75049
75760
|
ORDER BY ${sql.join(threadOrder(), sql`, `)}
|
|
75050
75761
|
) AS INTEGER)`.as("first_reply_rank"),
|
|
75051
|
-
|
|
75762
|
+
latestReplyRank: sql`CAST(ROW_NUMBER() OVER (
|
|
75052
75763
|
PARTITION BY ${posts.threadId}
|
|
75053
75764
|
ORDER BY ${sql.join(threadOrder("desc"), sql`, `)}
|
|
75054
75765
|
) AS INTEGER)`.as("latest_reply_rank"),
|
|
75055
|
-
|
|
75766
|
+
totalReplyCount: sql`CAST(COUNT(*) OVER (
|
|
75056
75767
|
PARTITION BY ${posts.threadId}
|
|
75057
75768
|
) AS INTEGER)`.as("total_reply_count")
|
|
75058
|
-
|
|
75059
|
-
|
|
75060
|
-
|
|
75061
|
-
|
|
75062
|
-
|
|
75063
|
-
|
|
75064
|
-
|
|
75065
|
-
|
|
75769
|
+
}).from(posts).where(and(eq(posts.siteId, siteId), inArray(posts.threadId, chunk), eq(posts.status, "published"), isNotNull(posts.replyToId))).as("ranked_replies");
|
|
75770
|
+
return db.select({
|
|
75771
|
+
threadId: rankedReplies.threadId,
|
|
75772
|
+
id: rankedReplies.id,
|
|
75773
|
+
firstReplyRank: rankedReplies.firstReplyRank,
|
|
75774
|
+
latestReplyRank: rankedReplies.latestReplyRank,
|
|
75775
|
+
totalReplyCount: rankedReplies.totalReplyCount
|
|
75776
|
+
}).from(rankedReplies).where(or(lte(rankedReplies.firstReplyRank, 3), lte(rankedReplies.latestReplyRank, 3)));
|
|
75777
|
+
});
|
|
75066
75778
|
const hydratedPosts = await hydratePostsById(contextRows.map((row) => row.id));
|
|
75067
75779
|
const contextByThreadId = /* @__PURE__ */ new Map();
|
|
75068
75780
|
for (const row of contextRows) {
|
|
@@ -77162,6 +77874,98 @@ internalUploadsRoutes.post("/cleanup", requireInternalAdminApi(), async (c) => {
|
|
|
77162
77874
|
return c.json(result);
|
|
77163
77875
|
});
|
|
77164
77876
|
//#endregion
|
|
77877
|
+
//#region src/middleware/deprecation.ts
|
|
77878
|
+
/**
|
|
77879
|
+
* Deprecated API endpoints.
|
|
77880
|
+
*
|
|
77881
|
+
* A deprecated endpoint keeps answering exactly as before until the major
|
|
77882
|
+
* release that removes it, and says so on every response, errors included:
|
|
77883
|
+
* `Deprecation` (RFC 9745) carries when it was deprecated, and `Link` with
|
|
77884
|
+
* `rel="successor-version"` names what replaces it. The docs and the release
|
|
77885
|
+
* notes say the same thing in words.
|
|
77886
|
+
*/
|
|
77887
|
+
/**
|
|
77888
|
+
* When 0.9 deprecated the Thread lists that `/api/public/threads` replaces:
|
|
77889
|
+
* the `GET /api/public/posts` list and `GET /api/public/archive`.
|
|
77890
|
+
*/ var THREAD_LIST_DEPRECATED_AT = Date.UTC(2026, 8, 27) / 1e3;
|
|
77891
|
+
/**
|
|
77892
|
+
* Mark every response of a route as deprecated.
|
|
77893
|
+
*
|
|
77894
|
+
* @param deprecatedAt - Unix seconds the endpoint was deprecated
|
|
77895
|
+
* @param successor - The replacement, as a site path (the site path prefix is
|
|
77896
|
+
* added)
|
|
77897
|
+
* @returns Hono middleware that sets `Deprecation` and `Link`
|
|
77898
|
+
* @example
|
|
77899
|
+
* ```ts
|
|
77900
|
+
* routes.get("/", deprecated(THREAD_LIST_DEPRECATED_AT, "/api/public/threads"), handler);
|
|
77901
|
+
* ```
|
|
77902
|
+
*/ function deprecated(deprecatedAt, successor) {
|
|
77903
|
+
return async (c, next) => {
|
|
77904
|
+
await next();
|
|
77905
|
+
c.header("Deprecation", `@${deprecatedAt}`);
|
|
77906
|
+
c.header("Link", `<${toPublicPath(successor, c.var.appConfig.sitePathPrefix)}>; rel="successor-version"`);
|
|
77907
|
+
};
|
|
77908
|
+
}
|
|
77909
|
+
//#endregion
|
|
77910
|
+
//#region src/routes/api/public/archive.ts
|
|
77911
|
+
var publicArchiveApiRoutes = new Hono();
|
|
77912
|
+
publicArchiveApiRoutes.use("*", requirePublicApiEnabled());
|
|
77913
|
+
/**
|
|
77914
|
+
* The endpoint's own parameters — everything that is not a filter dimension.
|
|
77915
|
+
*
|
|
77916
|
+
* The dimensions themselves are read by the shared registry, so this endpoint
|
|
77917
|
+
* cannot drift from the page it mirrors. They are listed here only so the strict
|
|
77918
|
+
* parser can tell them apart from a parameter nobody understands.
|
|
77919
|
+
*/ var ListPublicArchiveQuerySchema = z.object({
|
|
77920
|
+
/** Restrict to one content language. See `/api/public/posts`. */ lang: ContentLanguageSchema.optional(),
|
|
77921
|
+
cursor: z.string().optional(),
|
|
77922
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(20),
|
|
77923
|
+
content: z.enum(["markdown"]).optional()
|
|
77924
|
+
});
|
|
77925
|
+
var ENDPOINT_PARAMS = [
|
|
77926
|
+
"lang",
|
|
77927
|
+
"cursor",
|
|
77928
|
+
"limit",
|
|
77929
|
+
"content"
|
|
77930
|
+
];
|
|
77931
|
+
var INVALID_VISIBILITY_MESSAGE = "Invalid visibility value. Allowed: " + PUBLIC_ARCHIVE_VISIBILITIES.map((value) => value === "latest_hidden" ? "hidden" : value).join(", ");
|
|
77932
|
+
/**
|
|
77933
|
+
* Deprecated in 0.9 for `GET /api/public/threads?visibility=any&sort=published`,
|
|
77934
|
+
* which takes the same filters. Answers as it always has until 1.0.1 removes it.
|
|
77935
|
+
*/ publicArchiveApiRoutes.get("/", deprecated(THREAD_LIST_DEPRECATED_AT, "/api/public/threads?visibility=any&sort=published"), async (c) => {
|
|
77936
|
+
const { lang, cursor, limit, content } = parseValidated(ListPublicArchiveQuerySchema, c.req.query());
|
|
77937
|
+
const read = (key) => c.req.query(key);
|
|
77938
|
+
const ctx = { collections: readCollectionSlugs(read).length > 0 ? buildCollectionVocabulary(await c.var.services.collections.list()) : EMPTY_COLLECTION_VOCABULARY };
|
|
77939
|
+
const parsed = parsePostFilterSelectionStrict(read, Object.keys(c.req.query()), ctx, { allow: ENDPOINT_PARAMS });
|
|
77940
|
+
if (!parsed.ok && parsed.issues.every((issue) => issue.param === "collection")) return c.json({
|
|
77941
|
+
posts: [],
|
|
77942
|
+
nextCursor: null
|
|
77943
|
+
});
|
|
77944
|
+
if (!parsed.ok) {
|
|
77945
|
+
const first = parsed.issues[0];
|
|
77946
|
+
throw new ValidationError(first?.message ?? "Validation failed");
|
|
77947
|
+
}
|
|
77948
|
+
const visibility = parsed.selection.visibility;
|
|
77949
|
+
if (visibility !== void 0 && !PUBLIC_ARCHIVE_VISIBILITIES.includes(visibility)) throw new ValidationError(INVALID_VISIBILITY_MESSAGE);
|
|
77950
|
+
const { posts, nextCursor } = await c.var.services.posts.listPage({
|
|
77951
|
+
lang,
|
|
77952
|
+
status: "published",
|
|
77953
|
+
excludePrivate: true,
|
|
77954
|
+
excludeLatestHidden: false,
|
|
77955
|
+
excludeReplies: true,
|
|
77956
|
+
...toPostFilters(parsed.selection, { yearAxis: "published" }),
|
|
77957
|
+
sortBy: "published",
|
|
77958
|
+
ignorePinnedSort: true
|
|
77959
|
+
}, {
|
|
77960
|
+
cursor,
|
|
77961
|
+
limit
|
|
77962
|
+
});
|
|
77963
|
+
return c.json({
|
|
77964
|
+
posts: await loadPublicPostResponses(c.var, posts, { content }),
|
|
77965
|
+
nextCursor
|
|
77966
|
+
});
|
|
77967
|
+
});
|
|
77968
|
+
//#endregion
|
|
77165
77969
|
//#region src/routes/api/public/posts.ts
|
|
77166
77970
|
var publicPostsApiRoutes = new Hono();
|
|
77167
77971
|
publicPostsApiRoutes.use("*", requirePublicApiEnabled());
|
|
@@ -77178,81 +77982,14 @@ var ListPublicPostsQuerySchema = z.object({
|
|
|
77178
77982
|
content: z.enum(["markdown"]).optional()
|
|
77179
77983
|
});
|
|
77180
77984
|
var PublicPostContentQuerySchema = z.object({ content: z.enum(["markdown"]).optional() });
|
|
77181
|
-
/**
|
|
77182
|
-
* The public Markdown for a post, or null for a historical body that isn't
|
|
77183
|
-
* TipTap JSON. One unreadable row answers null and is logged, rather than
|
|
77184
|
-
* failing the whole listing; `bodyHtml` still falls back to stored HTML.
|
|
77185
|
-
*/ function toPublicBodyMarkdown(postId, body) {
|
|
77186
|
-
try {
|
|
77187
|
-
return tiptapJsonToMarkdown(body);
|
|
77188
|
-
} catch (error) {
|
|
77189
|
-
console.error(`Couldn't convert the body of post ${postId} to Markdown`, error);
|
|
77190
|
-
return null;
|
|
77191
|
-
}
|
|
77192
|
-
}
|
|
77193
77985
|
function isPublicDetailVisible(post) {
|
|
77194
77986
|
return post !== null && post.status === "published" && post.visibility !== "private";
|
|
77195
77987
|
}
|
|
77196
|
-
|
|
77197
|
-
|
|
77198
|
-
|
|
77199
|
-
|
|
77200
|
-
|
|
77201
|
-
quality: 80,
|
|
77202
|
-
format: "auto",
|
|
77203
|
-
fit: "scale-down"
|
|
77204
|
-
}) : null;
|
|
77205
|
-
const base = {
|
|
77206
|
-
id: post.id,
|
|
77207
|
-
format: post.format,
|
|
77208
|
-
status: "published",
|
|
77209
|
-
visibility: post.visibility,
|
|
77210
|
-
slug: post.slug,
|
|
77211
|
-
permalink: toPublicPath(`/${post.slug}`, sitePathPrefix),
|
|
77212
|
-
quoteText: post.quoteText,
|
|
77213
|
-
summary: post.summary,
|
|
77214
|
-
rating: post.rating,
|
|
77215
|
-
previewKind: post.previewKind,
|
|
77216
|
-
previewProvider: post.previewProvider,
|
|
77217
|
-
previewImageUrl,
|
|
77218
|
-
replyToId: post.replyToId,
|
|
77219
|
-
threadId: post.threadId,
|
|
77220
|
-
language: post.language,
|
|
77221
|
-
translationGroupId: post.translationGroupId,
|
|
77222
|
-
quietReply: post.quietReply,
|
|
77223
|
-
pinnedAt: post.pinnedAt,
|
|
77224
|
-
featuredAt: post.featuredAt,
|
|
77225
|
-
publishedAt: post.publishedAt,
|
|
77226
|
-
lastActivityAt: post.lastActivityAt,
|
|
77227
|
-
threadUpdatedAt: post.threadUpdatedAt,
|
|
77228
|
-
createdAt: post.createdAt,
|
|
77229
|
-
updatedAt: post.updatedAt,
|
|
77230
|
-
attachments: mediaList.map((media) => toApiAttachment(media, r2PublicUrl, imageTransformUrl, s3PublicUrl, localPublicUrl, sitePathPrefix)),
|
|
77231
|
-
collections: threadCollections.map((collection) => ({
|
|
77232
|
-
id: collection.id,
|
|
77233
|
-
slug: collection.slug,
|
|
77234
|
-
title: collection.title,
|
|
77235
|
-
url: toPublicPath(getCollectionPagePath(collection.slug), sitePathPrefix)
|
|
77236
|
-
}))
|
|
77237
|
-
};
|
|
77238
|
-
const contentFields = options?.content === "markdown" ? { bodyMarkdown: post.body ? toPublicBodyMarkdown(post.id, post.body) : null } : {
|
|
77239
|
-
bodyHtml: post.bodyHtml,
|
|
77240
|
-
bodyText: post.bodyText
|
|
77241
|
-
};
|
|
77242
|
-
if (post.format === "quote") return {
|
|
77243
|
-
...base,
|
|
77244
|
-
...contentFields,
|
|
77245
|
-
sourceName: post.title,
|
|
77246
|
-
sourceUrl: post.url
|
|
77247
|
-
};
|
|
77248
|
-
return {
|
|
77249
|
-
...base,
|
|
77250
|
-
...contentFields,
|
|
77251
|
-
title: post.title,
|
|
77252
|
-
url: post.url
|
|
77253
|
-
};
|
|
77254
|
-
}
|
|
77255
|
-
publicPostsApiRoutes.get("/", async (c) => {
|
|
77988
|
+
/**
|
|
77989
|
+
* Deprecated in 0.9 for `GET /api/public/threads`, which lists the same Thread
|
|
77990
|
+
* roots with the archive's filters and the homepage's defaults. Answers as it
|
|
77991
|
+
* always has until 1.0.1 removes it.
|
|
77992
|
+
*/ publicPostsApiRoutes.get("/", deprecated(THREAD_LIST_DEPRECATED_AT, "/api/public/threads"), async (c) => {
|
|
77256
77993
|
const { format, lang, collection, sort, cursor, limit, content } = parseValidated(ListPublicPostsQuerySchema, c.req.query());
|
|
77257
77994
|
let collectionIds;
|
|
77258
77995
|
let sortOrder;
|
|
@@ -77301,10 +78038,8 @@ publicPostsApiRoutes.get("/", async (c) => {
|
|
|
77301
78038
|
cursor,
|
|
77302
78039
|
limit
|
|
77303
78040
|
});
|
|
77304
|
-
const postIds = posts.map((post) => post.id);
|
|
77305
|
-
const [mediaMap, collectionsMap] = await Promise.all([c.var.services.media.getByPostIds(postIds), c.var.services.collections.getCollectionsByPostIds(postIds)]);
|
|
77306
78041
|
return c.json({
|
|
77307
|
-
posts:
|
|
78042
|
+
posts: await loadPublicPostResponses(c.var, posts, { content }),
|
|
77308
78043
|
nextCursor
|
|
77309
78044
|
});
|
|
77310
78045
|
});
|
|
@@ -77313,64 +78048,93 @@ publicPostsApiRoutes.get("/:slug", async (c) => {
|
|
|
77313
78048
|
const slug = c.req.param("slug");
|
|
77314
78049
|
const post = await c.var.services.posts.getBySlug(slug);
|
|
77315
78050
|
if (!isPublicDetailVisible(post)) throw new NotFoundError("Post");
|
|
77316
|
-
const [
|
|
77317
|
-
return c.json(
|
|
78051
|
+
const [response] = await loadPublicPostResponses(c.var, [post], { content });
|
|
78052
|
+
return c.json(response);
|
|
77318
78053
|
});
|
|
77319
78054
|
//#endregion
|
|
77320
|
-
//#region src/routes/api/public/
|
|
77321
|
-
|
|
77322
|
-
|
|
77323
|
-
|
|
77324
|
-
* The
|
|
77325
|
-
*
|
|
77326
|
-
*
|
|
77327
|
-
*
|
|
77328
|
-
|
|
77329
|
-
|
|
77330
|
-
|
|
78055
|
+
//#region src/routes/api/public/threads.ts
|
|
78056
|
+
/**
|
|
78057
|
+
* Public Threads API Routes
|
|
78058
|
+
*
|
|
78059
|
+
* The reader's view of Threads: what the site shows anyone, in the reading
|
|
78060
|
+
* view. A list left unfiltered is the homepage's — Threads hidden from Latest
|
|
78061
|
+
* left out, newest activity first, pins on top — and takes the archive's
|
|
78062
|
+
* filters to narrow or widen it.
|
|
78063
|
+
*/ var publicThreadsApiRoutes = new Hono();
|
|
78064
|
+
publicThreadsApiRoutes.use("*", requirePublicApiEnabled());
|
|
78065
|
+
var ContentSchema = z.enum(["markdown"]).optional();
|
|
78066
|
+
/** The list's own parameters; everything else is a filter dimension. */ var ListThreadsQuerySchema = z.object({
|
|
78067
|
+
lang: ContentLanguageSchema.optional(),
|
|
78068
|
+
sort: z.enum(THREAD_SORTS).optional(),
|
|
78069
|
+
include: z.string().optional(),
|
|
77331
78070
|
cursor: z.string().optional(),
|
|
77332
78071
|
limit: z.coerce.number().int().min(1).max(100).optional().default(20),
|
|
77333
|
-
content:
|
|
78072
|
+
content: ContentSchema
|
|
77334
78073
|
});
|
|
77335
|
-
var
|
|
78074
|
+
var LIST_PARAMS = [
|
|
77336
78075
|
"lang",
|
|
78076
|
+
"sort",
|
|
78077
|
+
"include",
|
|
77337
78078
|
"cursor",
|
|
77338
78079
|
"limit",
|
|
77339
78080
|
"content"
|
|
77340
78081
|
];
|
|
77341
|
-
var
|
|
77342
|
-
|
|
77343
|
-
|
|
77344
|
-
|
|
77345
|
-
|
|
77346
|
-
|
|
77347
|
-
|
|
77348
|
-
|
|
78082
|
+
var GetThreadQuerySchema = z.object({
|
|
78083
|
+
include: z.string().optional(),
|
|
78084
|
+
content: ContentSchema
|
|
78085
|
+
});
|
|
78086
|
+
var ListThreadPostsQuerySchema = z.object({
|
|
78087
|
+
cursor: z.string().optional(),
|
|
78088
|
+
limit: z.coerce.number().int().min(1).max(100).optional().default(100),
|
|
78089
|
+
content: ContentSchema
|
|
78090
|
+
});
|
|
78091
|
+
publicThreadsApiRoutes.get("/", async (c) => {
|
|
78092
|
+
const query = parseValidated(ListThreadsQuerySchema, c.req.query());
|
|
78093
|
+
const { fold } = parseThreadInclude(query.include);
|
|
78094
|
+
const parsed = await parseThreadSelection((key) => c.req.query(key), Object.keys(c.req.query()), {
|
|
78095
|
+
allow: LIST_PARAMS,
|
|
78096
|
+
audience: "reader",
|
|
78097
|
+
loadCollections: () => c.var.services.collections.list()
|
|
78098
|
+
});
|
|
78099
|
+
if (parsed.kind === "empty") return c.json({
|
|
78100
|
+
threads: [],
|
|
77349
78101
|
nextCursor: null
|
|
77350
78102
|
});
|
|
77351
|
-
|
|
77352
|
-
|
|
77353
|
-
|
|
77354
|
-
|
|
77355
|
-
|
|
77356
|
-
|
|
77357
|
-
|
|
77358
|
-
lang,
|
|
77359
|
-
status: "published",
|
|
77360
|
-
excludePrivate: true,
|
|
77361
|
-
excludeLatestHidden: false,
|
|
77362
|
-
excludeReplies: true,
|
|
77363
|
-
...toPostFilters(parsed.selection, { yearAxis: "published" }),
|
|
77364
|
-
sortBy: "published",
|
|
77365
|
-
ignorePinnedSort: true
|
|
78103
|
+
const { threads, nextCursor } = await c.var.services.threads.listThreads({
|
|
78104
|
+
audience: "reader",
|
|
78105
|
+
selection: parsed.selection,
|
|
78106
|
+
includeHidden: parsed.includeHidden,
|
|
78107
|
+
lang: query.lang,
|
|
78108
|
+
sort: query.sort,
|
|
78109
|
+
fold
|
|
77366
78110
|
}, {
|
|
78111
|
+
cursor: query.cursor,
|
|
78112
|
+
limit: query.limit
|
|
78113
|
+
});
|
|
78114
|
+
return c.json({
|
|
78115
|
+
threads: await loadPublicThreadResponses(c.var, threads, { content: query.content }),
|
|
78116
|
+
nextCursor
|
|
78117
|
+
});
|
|
78118
|
+
});
|
|
78119
|
+
publicThreadsApiRoutes.get("/:slug", async (c) => {
|
|
78120
|
+
const { include, content } = parseValidated(GetThreadQuerySchema, c.req.query());
|
|
78121
|
+
const root = await c.var.services.threads.findRoot({ slug: c.req.param("slug") }, "reader");
|
|
78122
|
+
if (!root) throw new NotFoundError("Thread");
|
|
78123
|
+
const summaries = await c.var.services.threads.summarize([root], parseThreadInclude(include));
|
|
78124
|
+
const [thread] = await loadPublicThreadResponses(c.var, summaries, { content });
|
|
78125
|
+
if (!thread) throw new NotFoundError("Thread");
|
|
78126
|
+
return c.json(thread);
|
|
78127
|
+
});
|
|
78128
|
+
publicThreadsApiRoutes.get("/:slug/posts", async (c) => {
|
|
78129
|
+
const { cursor, limit, content } = parseValidated(ListThreadPostsQuerySchema, c.req.query());
|
|
78130
|
+
const root = await c.var.services.threads.findRoot({ slug: c.req.param("slug") }, "reader");
|
|
78131
|
+
if (!root) throw new NotFoundError("Thread");
|
|
78132
|
+
const { posts, nextCursor } = await c.var.services.threads.listPosts(root.id, { audience: "reader" }, {
|
|
77367
78133
|
cursor,
|
|
77368
78134
|
limit
|
|
77369
78135
|
});
|
|
77370
|
-
const postIds = posts.map((post) => post.id);
|
|
77371
|
-
const [mediaMap, collectionsMap] = await Promise.all([c.var.services.media.getByPostIds(postIds), c.var.services.collections.getCollectionsByPostIds(postIds)]);
|
|
77372
78136
|
return c.json({
|
|
77373
|
-
posts:
|
|
78137
|
+
posts: await loadPublicPostResponses(c.var, posts, { content }),
|
|
77374
78138
|
nextCursor
|
|
77375
78139
|
});
|
|
77376
78140
|
});
|
|
@@ -77786,7 +78550,7 @@ manifestRoutes.get("/manifest.webmanifest", (c) => {
|
|
|
77786
78550
|
});
|
|
77787
78551
|
//#endregion
|
|
77788
78552
|
//#region ../../docs/skill.md?raw
|
|
77789
|
-
var skill_default = "---\nname: jant-site\ndescription: >-\n Work with the Jant site identified in this document through its HTTP API or\n MCP interface. Use when the user asks an AI assistant to read, publish, edit,\n organize, search, or migrate content, upload media, manage Collections, or\n update site settings.\n---\n\n# Jant Site Skill\n\nThis page is written for AI assistants working with one Jant site. Use it when the user asks you to read, publish, edit, organize, search, or migrate site content through Jant's HTTP API or MCP interface.\n\nThe full HTTP API reference lives at <https://jant.me/docs/API.md>. This skill explains how to choose the right interface, work safely, understand Jant's content model, and run common workflows. Consult the reference for complete request and response schemas instead of guessing fields.\n\n---\n\n## Scope and Safety\n\n- Use this skill only for the target site identified below. Do not substitute another site without the user's confirmation.\n- Start with read-only inspection when the state of the site or the user's intent is unclear.\n- Get explicit confirmation before bulk publishing, bulk deletion, destructive settings changes, or any action that is difficult to reverse. A request to perform a specific ordinary write, such as publishing one post, already supplies that confirmation.\n- For uncertain or bulk content changes, ask whether to save posts as drafts or publish them immediately.\n- Treat API tokens like passwords. Never log, commit, or repeat a token back to the user after they provide it.\n- Use the public API or MCP interface. Do not edit the database directly and do not call `/api/internal/*`; those endpoints belong to the hosted control plane.\n- Keep bulk writes sequential. Save returned IDs after each successful write so interrupted work can resume without creating duplicates.\n\n---\n\n## Choose an Interface\n\nJant exposes the same site-owner capabilities through two interfaces:\n\n| Interface | Use it when |\n| ----------------------- | ---------------------------------------------------------------------------------------------------- |\n| HTTP JSON API | Writing scripts, making a few direct requests, or running a one-time migration. This is the default. |\n| MCP at `<site>/api/mcp` | The caller already supports MCP and benefits from tool discovery and structured tool calls. |\n\nFor MCP, call `initialize`, then `tools/list`, and use the returned schemas rather than assuming tool arguments. The tool groups cover posts, media, attachments, Collections, settings, and search.\n\nFor HTTP, these are the main entry points:\n\n| Task | Endpoint |\n| ---------------------------- | ---------------------------------------------------------------- |\n| Read public posts | `GET /api/public/posts`, `GET /api/public/posts/:slug` |\n| List or inspect all posts | `GET /api/posts`, `GET /api/posts/:id` |\n| Create, update, delete | `POST /api/posts`, `PUT /api/posts/:id`, `DELETE /api/posts/:id` |\n| Upload or manage media | `/api/upload` or `/api/uploads` |\n| Manage Collections | `/api/collections` |\n| Search published content | `GET /api/search` |\n| Read or update site settings | `GET /api/settings`, `PUT /api/settings` |\n\nPublic post, Collection, navigation, and search reads can work without a token. A site can disable anonymous API reads; `/api/public/*` then becomes unavailable, while Collection, navigation, and search JSON reads require a browser session or Bearer token. Private content and all writes always require authentication.\n\n---\n\n## Confirm the Target and Authenticate\n\nBefore an authenticated or multi-step operation, confirm:\n\n- The Jant site URL (e.g. `https://example.com`).\n- The exact outcome the user wants, including which content may change.\n- For bulk work, whether new posts should use `status: \"published\"` or `status: \"draft\"`.\n\nHave the user create an API token when the operation needs authentication:\n\n1. Sign in to Jant at `<site>/signin`.\n2. Open **Settings → API Tokens**.\n3. Create a token and copy it immediately. It is shown only once.\n\nSend the token as `Authorization: Bearer jnt_...`.\n\n```bash\nexport JANT_API_TOKEN=jnt_...\nexport JANT_SITE=https://example.com\n```\n\n---\n\n## Understand the Content Model\n\nJant is a single-author microblog. There are no users, comments, likes, followers, or social relationships to manage.\n\nThree concepts shape almost every content operation:\n\n1. **Posts have three formats** — `note`, `link`, and `quote`. Preserve the semantic format instead of coercing everything into `note`.\n2. **Threads connect posts** — a reply is a post whose `replyToId` points to another post. There is no separate comments table.\n3. **Collections curate Threads** — they are intentional groupings, not tags. A Thread can belong to multiple Collections; its root and replies share the same memberships.\n\n### `note` — original writing\n\nUse for essays, journal entries, status updates, photo posts with captions, and other content written by the site owner.\n\n- Required: `format: \"note\"`\n- Recommended: `bodyMarkdown`\n- Optional: `title`\n\n### `link` — a shared reference\n\nUse when the post is fundamentally pointing readers to another resource.\n\n- Required: `format: \"link\"`, `title`, `url`\n- Optional: `bodyMarkdown` for the owner's commentary\n\n### `quote` — a cited passage\n\nUse when the post is built around someone else's words.\n\n- Required: `format: \"quote\"`, `quoteText`\n- Optional: `sourceName`, `sourceUrl`, and `bodyMarkdown` for commentary\n- Do not send `title` or `url`; quote posts use `sourceName` and `sourceUrl` instead.\n\n---\n\n## Common Content Operations\n\nRead the current state before modifying existing content. Use `GET /api/posts/:id` when you need fields that may not appear in a list response, including Thread-level Collection memberships.\n\nCreate a note with an explicit status and visibility:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/posts\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"format\": \"note\",\n \"bodyMarkdown\": \"Hello from Jant.\",\n \"status\": \"published\",\n \"visibility\": \"public\"\n }'\n```\n\nUse `PUT /api/posts/:id` to update a post and `DELETE /api/posts/:id` to delete one. Fetch the post first, preserve fields the user did not ask to change, and confirm before deletion.\n\nUse `POST /api/upload` for an ordinary single-file script or one-time migration. Use the session-based `/api/uploads` flow for large files, unreliable connections, or clients that need resumable transport. Save the returned `med_*` ID before attaching media to a post.\n\nUse `GET /api/settings` before `PUT /api/settings`. Settings values are strings in the HTTP API; preserve settings outside the user's requested change.\n\nFor exact fields, filters, pagination, and response schemas, read the [full HTTP API reference](https://jant.me/docs/API.md).\n\n---\n\n## Import Content from Another Platform\n\nUse this workflow when the user wants to move an old blog, site, or archive into this Jant site. The request may arrive as one sentence, with no export and no token yet. Lead the user through the rest.\n\n### Lead the user\n\nAsk for one thing at a time, when the next step needs it. Name the menus the user clicks, not API endpoints.\n\n1. Check that you can send HTTP requests to `<site>` and read files the user gives you. If you cannot, say so first and suggest an assistant that can, such as a coding agent with shell access. Do not hand over a script unless the user asks for one.\n2. Ask which platform the old blog is on and where it lives.\n3. Get the content. Use an export if the user has one. If not, tell them where their platform exports it (the table under \"Read the source\" lists the usual places) and wait for the file. When the old blog is public and its feed carries full posts, you can read the feed instead. Feeds usually hold only recent posts, so compare the count with the old blog's archive before relying on one.\n4. Ask for the API token just before the first write, using the steps in \"Confirm the Target and Authenticate\". Do not ask for it at the start.\n\n### Plan before writing\n\n1. Inspect the target site so you know whether it already contains content.\n2. Inspect 3–5 representative source posts end to end before deciding how to transform anything.\n3. Report what you found: source formats, item counts, dates, media, internal links, categories, and anything unsupported.\n4. Ask how to handle ambiguous categories or tags. Map them to Collections, drop them, or fold them into post bodies only with the user's direction.\n5. Agree on draft versus published status and on a duplicate policy before creating posts.\n6. Build a resumable source-ID map and persist `{ sourceId -> jantId, slug }` after every successful write.\n\nA slug or path collision returns `409 CONFLICT`, but that does not make an import automatically idempotent. Items with new or generated slugs can still be duplicated, so use the source-ID map rather than relying on conflicts.\n\n### Read the source\n\nCommon source shapes include:\n\n| Source | Typical export |\n| --------------------- | ----------------------------------------------------------------------- |\n| WordPress | WXR XML (`Tools → Export`), with media URLs pointing at the source host |\n| Ghost | JSON export from `Settings → Labs → Export` |\n| Substack | ZIP with `posts.csv` and `posts/*.html` |\n| Medium | ZIP with `posts/*.html` |\n| Tumblr | API dump or `tumblr-utils` archive |\n| Hugo / Jekyll / Astro | Markdown files with YAML or TOML front matter |\n| Notion | Markdown plus a media ZIP |\n| Custom | SQL dump, HTML folder, RSS feed, or another structured source |\n\nDo not assume the source schema from the platform name alone. Check titles, bodies, dates, embedded media, internal links, categories, and source identifiers in real records.\n\n### Map source formats\n\nUse these heuristics as a starting point:\n\n- WordPress, Ghost, and Substack standard posts → `note` with `title` and `bodyMarkdown`.\n- Linklog posts that are primarily an external URL plus commentary → `link`.\n- WordPress or Tumblr quote posts → `quote`.\n- Tumblr photo posts with captions → `note` with uploaded images.\n- Tumblr link posts → `link`.\n- Reblogs or reposts → ask the user. Jant has no native reblog concept; `quote` with `sourceUrl` is often the closest representation.\n\nWhen uncertain, prefer `note`. Turning a real `link` or `quote` into a `note` loses semantic information, while turning original writing into a `link` or `quote` invents structure.\n\n### Convert bodies to Markdown\n\nSend `bodyMarkdown`, not `body`. The `body` field expects TipTap JSON and is intended for editor integrations.\n\n- Convert HTML with a real HTML-to-Markdown tool such as Turndown or Pandoc. Do not strip tags with regular expressions.\n- Preserve headings, lists, tables, fenced code blocks, blockquotes, and inline formatting.\n- A blank line starts a new paragraph. Use two trailing spaces or a backslash for a hard line break.\n- Preserve `<!--more-->` when the source has an intentional excerpt break.\n- Upload embedded media to Jant instead of leaving remote `<img>` references that may disappear with the old site.\n- Rewrite internal links after the destination slugs are known. Either build the slug map first or use a two-pass process: create posts, then update their bodies.\n\n### Upload media first\n\nPosts reference uploaded media by `med_*` ID. For a one-time migration, the one-shot endpoint is usually enough:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/upload\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -F \"file=@./photo.jpg\" \\\n -F \"alt=A red door\"\n# → { \"id\": \"med_...\", \"url\": \"/media/med_....jpg\", ... }\n```\n\nUse `/api/uploads` when a file is large or the connection is unreliable. Its session flow initializes the upload, transfers one or more parts, optionally adds a video poster, and completes the session to produce the final `med_*` record.\n\nPreserve source alt text. If the source has no alt text, leave it unset rather than inventing a description.\n\n### Create Collections when needed\n\nCreate approved Collections before the posts that use them:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/collections\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"slug\": \"reading\",\n \"title\": \"Reading\",\n \"description\": \"Books worth coming back to\",\n \"sortOrder\": \"newest\"\n }'\n```\n\nSave each returned `col_*` ID. Send `collectionIds` on standalone posts and Thread roots, not on replies.\n\n### Create posts\n\n`POST /api/posts` creates every post format. Send one post at a time and record the result before continuing.\n\nMinimal `note`:\n\n```json\n{\n \"format\": \"note\",\n \"title\": \"Hello world\",\n \"bodyMarkdown\": \"First post on the new site.\",\n \"publishedAt\": 1706000000,\n \"status\": \"draft\"\n}\n```\n\nMinimal `link`:\n\n```json\n{\n \"format\": \"link\",\n \"title\": \"An interesting article\",\n \"url\": \"https://example.com/post\",\n \"bodyMarkdown\": \"Worth your fifteen minutes.\"\n}\n```\n\nMinimal `quote`:\n\n```json\n{\n \"format\": \"quote\",\n \"quoteText\": \"What stands in the way becomes the way.\",\n \"sourceName\": \"Marcus Aurelius\",\n \"sourceUrl\": \"https://example.com/meditations\"\n}\n```\n\nFields commonly needed during migration:\n\n| Field | Purpose |\n| --------------- | ------------------------------------------------------------------------------------------ |\n| `publishedAt` | Original publication time as Unix seconds, preserving archive chronology. |\n| `slug` | Original stable slug when it should remain the canonical URL. |\n| `path` | Alternative to `slug` for an original path such as `2024/01/hello-world`; never send both. |\n| `status` | `published` or `draft`; set it explicitly according to the import plan. |\n| `visibility` | `public`, `latest_hidden`, or `private`. |\n| `pinned` | Preserve a pinned state when the source had one; replies cannot be pinned. |\n| `featured` | Preserve a featured or starred state when it has the same meaning. |\n| `collectionIds` | Approved `col_*` IDs on standalone posts and Thread roots. |\n| `attachments` | Ordered media or text attachments. |\n| `replyToId` | Destination `pst_*` ID of the parent when importing a Thread reply. |\n\nRemember these validation rules:\n\n- Send either `body` or `bodyMarkdown`, never both.\n- Send either `slug` or `path`, never both.\n- `note` rejects link- and quote-specific fields.\n- `link` requires `title` and `url`.\n- `quote` requires `quoteText`, uses `sourceName` and `sourceUrl`, and rejects `title` and `url`.\n\nA successful create returns `201` with the full post. Save `id`, `slug`, and `threadId` under the source ID for replies, link rewriting, verification, and recovery.\n\n### Rebuild Threads\n\n1. Import the Thread root first.\n2. Import replies in parent-first order with `replyToId` set to the destination parent's `pst_*` ID.\n3. Do not set `threadId`; Jant derives it from `replyToId`.\n4. Set `collectionIds` on the root only. Replies share the Thread's Collection memberships.\n5. Replies inherit root visibility and status unless explicitly created as drafts. They cannot be pinned or receive independent visibility changes.\n\n### Verify and report\n\nAfter the import:\n\n- Compare source and destination counts by format, media type, Collection, and Thread.\n- Fetch representative posts through `GET /api/posts/:id` and verify dates, slugs, bodies, attachments, Collection memberships, and reply relationships.\n- Open representative public URLs and verify rendered Markdown, media, and rewritten internal links.\n- Report anything skipped, transformed, duplicated, or unresolved, with a short list of URLs for manual review.\n\nIf an import stops partway through, resume from the persisted source-ID map. If cleanup is required, identify only the posts, media, and Collections created by that run, show the user the cleanup scope, and get confirmation before deleting them. Do not use account deletion as an automated recovery strategy.\n\n---\n\n## Handle Errors\n\nHTTP API errors use this shape:\n\n```json\n{ \"error\": \"...\", \"code\": \"VALIDATION_ERROR\", \"details\": {} }\n```\n\n| Code | Response |\n| --------------------- | ------------------------------------------------------------------------------------------------- |\n| `VALIDATION_ERROR` | Read `details.fieldErrors`, correct the request, and do not retry unchanged input. |\n| `UNAUTHORIZED` | Stop. The token is missing, invalid, or revoked; ask the user to create or provide a valid token. |\n| `FORBIDDEN` | Stop and explain which operation was denied. Do not look for an internal bypass. |\n| `NOT_FOUND` | Re-check the target site and resource ID before deciding whether the item was removed. |\n| `CONFLICT` | Resolve the reported state conflict; never silently change a user-selected canonical slug. |\n| `RATE_LIMIT` | Respect `Retry-After` when present, back off, and keep bulk writes sequential. |\n| `CONFIGURATION_ERROR` | Surface the server message; the site owner may need to correct deployment configuration. |\n\nFor MCP, transport and protocol failures use JSON-RPC errors. Tool validation and domain failures are returned as tool results with `isError: true`; inspect their structured content before retrying.\n\n---\n\n## Reference\n\n- Full HTTP API: <https://jant.me/docs/API.md> — endpoints, fields, filters, and response schemas.\n- Automation overview: <https://jant.me/docs/automation-and-api.md> — tokens, HTTP, MCP, and debugging.\n- Round-trip Jant exports: <https://jant.me/docs/export-and-import.md> — use `site export` and `site import` when both ends are Jant.\n- Public documentation index: <https://jant.me/docs/SUMMARY.md>.\n";
|
|
78553
|
+
var skill_default = "---\nname: jant-site\ndescription: >-\n Work with the Jant site identified in this document through its HTTP API or\n MCP interface. Use when the user asks an AI assistant to read, publish, edit,\n organize, search, or migrate content, upload media, manage Collections, or\n update site settings.\n---\n\n# Jant Site Skill\n\nThis page is written for AI assistants working with one Jant site. Use it when the user asks you to read, publish, edit, organize, search, or migrate site content through Jant's HTTP API or MCP interface.\n\nThe full HTTP API reference lives at <https://jant.me/docs/API.md>. This skill explains how to choose the right interface, work safely, understand Jant's content model, and run common workflows. Consult the reference for complete request and response schemas instead of guessing fields.\n\n---\n\n## Scope and Safety\n\n- Use this skill only for the target site identified below. Do not substitute another site without the user's confirmation.\n- Start with read-only inspection when the state of the site or the user's intent is unclear.\n- Get explicit confirmation before bulk publishing, bulk deletion, destructive settings changes, or any action that is difficult to reverse. A request to perform a specific ordinary write, such as publishing one post, already supplies that confirmation.\n- For uncertain or bulk content changes, ask whether to save posts as drafts or publish them immediately.\n- Treat API tokens like passwords. Never log, commit, or repeat a token back to the user after they provide it.\n- Use the public API or MCP interface. Do not edit the database directly and do not call `/api/internal/*`; those endpoints belong to the hosted control plane.\n- Keep bulk writes sequential. Save returned IDs after each successful write so interrupted work can resume without creating duplicates.\n\n---\n\n## Choose an Interface\n\nJant exposes the same site-owner capabilities through two interfaces:\n\n| Interface | Use it when |\n| ----------------------- | ---------------------------------------------------------------------------------------------------- |\n| HTTP JSON API | Writing scripts, making a few direct requests, or running a one-time migration. This is the default. |\n| MCP at `<site>/api/mcp` | The caller already supports MCP and benefits from tool discovery and structured tool calls. |\n\nFor MCP, call `initialize`, then `tools/list`, and use the returned schemas rather than assuming tool arguments. The tool groups cover posts, Threads, media, attachments, Collections, settings, and search.\n\nFor HTTP, these are the main entry points:\n\n| Task | Endpoint |\n| ---------------------------- | ---------------------------------------------------------------- |\n| Read public Threads | `GET /api/public/threads`, `GET /api/public/threads/:slug/posts` |\n| Read one public post | `GET /api/public/posts/:slug` |\n| List or inspect all posts | `GET /api/posts`, `GET /api/posts/:id` |\n| List or read whole Threads | `GET /api/threads`, `GET /api/threads/:id/posts` |\n| Create, update, delete | `POST /api/posts`, `PUT /api/posts/:id`, `DELETE /api/posts/:id` |\n| Upload or manage media | `/api/upload` or `/api/uploads` |\n| Manage Collections | `/api/collections` |\n| Search published content | `GET /api/search` |\n| Read or update site settings | `GET /api/settings`, `PUT /api/settings` |\n\nPublic post, Thread, Collection, navigation, and search reads can work without a token. A site can disable anonymous API reads; `/api/public/*` then becomes unavailable, while Collection, navigation, and search JSON reads require a browser session or Bearer token. Private content and all writes always require authentication.\n\n---\n\n## Confirm the Target and Authenticate\n\nBefore an authenticated or multi-step operation, confirm:\n\n- The Jant site URL (e.g. `https://example.com`).\n- The exact outcome the user wants, including which content may change.\n- For bulk work, whether new posts should use `status: \"published\"` or `status: \"draft\"`.\n\nHave the user create an API token when the operation needs authentication:\n\n1. Sign in to Jant at `<site>/signin`.\n2. Open **Settings → API Tokens**.\n3. Create a token and copy it immediately. It is shown only once.\n\nSend the token as `Authorization: Bearer jnt_...`.\n\n```bash\nexport JANT_API_TOKEN=jnt_...\nexport JANT_SITE=https://example.com\n```\n\n---\n\n## Understand the Content Model\n\nJant is a single-author microblog. There are no users, comments, likes, followers, or social relationships to manage.\n\nThree concepts shape almost every content operation:\n\n1. **Posts have three formats** — `note`, `link`, and `quote`. Preserve the semantic format instead of coercing everything into `note`.\n2. **Threads connect posts** — a reply is a post whose `replyToId` points to another post. There is no separate comments table. A post's `threadPostCount` says how many posts its Thread holds; read them all with `GET /api/threads/:id/posts`, passing any post's ID, rather than collecting replies from the post list.\n3. **Collections curate Threads** — they are intentional groupings, not tags. A Thread can belong to multiple Collections; its root and replies share the same memberships.\n\n### `note` — original writing\n\nUse for essays, journal entries, status updates, photo posts with captions, and other content written by the site owner.\n\n- Required: `format: \"note\"`\n- Recommended: `bodyMarkdown`\n- Optional: `title`\n\n### `link` — a shared reference\n\nUse when the post is fundamentally pointing readers to another resource.\n\n- Required: `format: \"link\"`, `title`, `url`\n- Optional: `bodyMarkdown` for the owner's commentary\n\n### `quote` — a cited passage\n\nUse when the post is built around someone else's words.\n\n- Required: `format: \"quote\"`, `quoteText`\n- Optional: `sourceName`, `sourceUrl`, and `bodyMarkdown` for commentary\n- Do not send `title` or `url`; quote posts use `sourceName` and `sourceUrl` instead.\n\n---\n\n## Common Content Operations\n\nRead the current state before modifying existing content. Use `GET /api/posts/:id` when you need fields that may not appear in a list response, including Thread-level Collection memberships.\n\nCreate a note with an explicit status and visibility:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/posts\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"format\": \"note\",\n \"bodyMarkdown\": \"Hello from Jant.\",\n \"status\": \"published\",\n \"visibility\": \"public\"\n }'\n```\n\nUse `PUT /api/posts/:id` to update a post and `DELETE /api/posts/:id` to delete one. Fetch the post first, preserve fields the user did not ask to change, and confirm before deletion.\n\nUse `POST /api/upload` for an ordinary single-file script or one-time migration. Use the session-based `/api/uploads` flow for large files, unreliable connections, or clients that need resumable transport. Save the returned `med_*` ID before attaching media to a post.\n\nUse `GET /api/settings` before `PUT /api/settings`. Settings values are strings in the HTTP API; preserve settings outside the user's requested change.\n\nFor exact fields, filters, pagination, and response schemas, read the [full HTTP API reference](https://jant.me/docs/API.md).\n\n---\n\n## Import Content from Another Platform\n\nUse this workflow when the user wants to move an old blog, site, or archive into this Jant site. The request may arrive as one sentence, with no export and no token yet. Lead the user through the rest.\n\n### Lead the user\n\nAsk for one thing at a time, when the next step needs it. Name the menus the user clicks, not API endpoints.\n\n1. Check that you can send HTTP requests to `<site>` and read files the user gives you. If you cannot, say so first and suggest an assistant that can, such as a coding agent with shell access. Do not hand over a script unless the user asks for one.\n2. Ask which platform the old blog is on and where it lives.\n3. Get the content. Use an export if the user has one. If not, tell them where their platform exports it (the table under \"Read the source\" lists the usual places) and wait for the file. When the old blog is public and its feed carries full posts, you can read the feed instead. Feeds usually hold only recent posts, so compare the count with the old blog's archive before relying on one.\n4. Ask for the API token just before the first write, using the steps in \"Confirm the Target and Authenticate\". Do not ask for it at the start.\n\n### Plan before writing\n\n1. Inspect the target site so you know whether it already contains content.\n2. Inspect 3–5 representative source posts end to end before deciding how to transform anything.\n3. Report what you found: source formats, item counts, dates, media, internal links, categories, and anything unsupported.\n4. Ask how to handle ambiguous categories or tags. Map them to Collections, drop them, or fold them into post bodies only with the user's direction.\n5. Agree on draft versus published status and on a duplicate policy before creating posts.\n6. Build a resumable source-ID map and persist `{ sourceId -> jantId, slug }` after every successful write.\n\nA slug or path collision returns `409 CONFLICT`, but that does not make an import automatically idempotent. Items with new or generated slugs can still be duplicated, so use the source-ID map rather than relying on conflicts.\n\n### Read the source\n\nCommon source shapes include:\n\n| Source | Typical export |\n| --------------------- | ----------------------------------------------------------------------- |\n| WordPress | WXR XML (`Tools → Export`), with media URLs pointing at the source host |\n| Ghost | JSON export from `Settings → Labs → Export` |\n| Substack | ZIP with `posts.csv` and `posts/*.html` |\n| Medium | ZIP with `posts/*.html` |\n| Tumblr | API dump or `tumblr-utils` archive |\n| Hugo / Jekyll / Astro | Markdown files with YAML or TOML front matter |\n| Notion | Markdown plus a media ZIP |\n| Custom | SQL dump, HTML folder, RSS feed, or another structured source |\n\nDo not assume the source schema from the platform name alone. Check titles, bodies, dates, embedded media, internal links, categories, and source identifiers in real records.\n\n### Map source formats\n\nUse these heuristics as a starting point:\n\n- WordPress, Ghost, and Substack standard posts → `note` with `title` and `bodyMarkdown`.\n- Linklog posts that are primarily an external URL plus commentary → `link`.\n- WordPress or Tumblr quote posts → `quote`.\n- Tumblr photo posts with captions → `note` with uploaded images.\n- Tumblr link posts → `link`.\n- Reblogs or reposts → ask the user. Jant has no native reblog concept; `quote` with `sourceUrl` is often the closest representation.\n\nWhen uncertain, prefer `note`. Turning a real `link` or `quote` into a `note` loses semantic information, while turning original writing into a `link` or `quote` invents structure.\n\n### Convert bodies to Markdown\n\nSend `bodyMarkdown`, not `body`. The `body` field expects TipTap JSON and is intended for editor integrations.\n\n- Convert HTML with a real HTML-to-Markdown tool such as Turndown or Pandoc. Do not strip tags with regular expressions.\n- Preserve headings, lists, tables, fenced code blocks, blockquotes, and inline formatting.\n- A blank line starts a new paragraph. Use two trailing spaces or a backslash for a hard line break.\n- Preserve `<!--more-->` when the source has an intentional excerpt break.\n- Upload embedded media to Jant instead of leaving remote `<img>` references that may disappear with the old site.\n- Rewrite internal links after the destination slugs are known. Either build the slug map first or use a two-pass process: create posts, then update their bodies.\n\n### Upload media first\n\nPosts reference uploaded media by `med_*` ID. For a one-time migration, the one-shot endpoint is usually enough:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/upload\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -F \"file=@./photo.jpg\" \\\n -F \"alt=A red door\"\n# → { \"id\": \"med_...\", \"url\": \"/media/med_....jpg\", ... }\n```\n\nUse `/api/uploads` when a file is large or the connection is unreliable. Its session flow initializes the upload, transfers one or more parts, optionally adds a video poster, and completes the session to produce the final `med_*` record.\n\nPreserve source alt text. If the source has no alt text, leave it unset rather than inventing a description.\n\n### Create Collections when needed\n\nCreate approved Collections before the posts that use them:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/collections\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"slug\": \"reading\",\n \"title\": \"Reading\",\n \"description\": \"Books worth coming back to\",\n \"sortOrder\": \"newest\"\n }'\n```\n\nSave each returned `col_*` ID. Send `collectionIds` on standalone posts and Thread roots, not on replies.\n\n### Create posts\n\n`POST /api/posts` creates every post format. Send one post at a time and record the result before continuing.\n\nMinimal `note`:\n\n```json\n{\n \"format\": \"note\",\n \"title\": \"Hello world\",\n \"bodyMarkdown\": \"First post on the new site.\",\n \"publishedAt\": 1706000000,\n \"status\": \"draft\"\n}\n```\n\nMinimal `link`:\n\n```json\n{\n \"format\": \"link\",\n \"title\": \"An interesting article\",\n \"url\": \"https://example.com/post\",\n \"bodyMarkdown\": \"Worth your fifteen minutes.\"\n}\n```\n\nMinimal `quote`:\n\n```json\n{\n \"format\": \"quote\",\n \"quoteText\": \"What stands in the way becomes the way.\",\n \"sourceName\": \"Marcus Aurelius\",\n \"sourceUrl\": \"https://example.com/meditations\"\n}\n```\n\nFields commonly needed during migration:\n\n| Field | Purpose |\n| --------------- | ------------------------------------------------------------------------------------------ |\n| `publishedAt` | Original publication time as Unix seconds, preserving archive chronology. |\n| `slug` | Original stable slug when it should remain the canonical URL. |\n| `path` | Alternative to `slug` for an original path such as `2024/01/hello-world`; never send both. |\n| `status` | `published` or `draft`; set it explicitly according to the import plan. |\n| `visibility` | `public`, `latest_hidden`, or `private`. |\n| `pinned` | Preserve a pinned state when the source had one; replies cannot be pinned. |\n| `featured` | Preserve a featured or starred state when it has the same meaning. |\n| `collectionIds` | Approved `col_*` IDs on standalone posts and Thread roots. |\n| `attachments` | Ordered media or text attachments. |\n| `replyToId` | Destination `pst_*` ID of the parent when importing a Thread reply. |\n\nRemember these validation rules:\n\n- Send either `body` or `bodyMarkdown`, never both.\n- Send either `slug` or `path`, never both.\n- `note` rejects link- and quote-specific fields.\n- `link` requires `title` and `url`.\n- `quote` requires `quoteText`, uses `sourceName` and `sourceUrl`, and rejects `title` and `url`.\n\nA successful create returns `201` with the full post. Save `id`, `slug`, and `threadId` under the source ID for replies, link rewriting, verification, and recovery.\n\n### Rebuild Threads\n\n1. Import the Thread root first.\n2. Import replies in parent-first order with `replyToId` set to the destination parent's `pst_*` ID.\n3. Do not set `threadId`; Jant derives it from `replyToId`.\n4. Set `collectionIds` on the root only. Replies share the Thread's Collection memberships.\n5. Replies inherit root visibility and status unless explicitly created as drafts. They cannot be pinned or receive independent visibility changes.\n\n### Verify and report\n\nAfter the import:\n\n- Compare source and destination counts by format, media type, Collection, and Thread.\n- Fetch representative posts through `GET /api/posts/:id` and verify dates, slugs, bodies, attachments, Collection memberships, and reply relationships.\n- Open representative public URLs and verify rendered Markdown, media, and rewritten internal links.\n- Report anything skipped, transformed, duplicated, or unresolved, with a short list of URLs for manual review.\n\nIf an import stops partway through, resume from the persisted source-ID map. If cleanup is required, identify only the posts, media, and Collections created by that run, show the user the cleanup scope, and get confirmation before deleting them. Do not use account deletion as an automated recovery strategy.\n\n---\n\n## Handle Errors\n\nHTTP API errors use this shape:\n\n```json\n{ \"error\": \"...\", \"code\": \"VALIDATION_ERROR\", \"details\": {} }\n```\n\n| Code | Response |\n| --------------------- | ------------------------------------------------------------------------------------------------- |\n| `VALIDATION_ERROR` | Read `details.fieldErrors`, correct the request, and do not retry unchanged input. |\n| `UNAUTHORIZED` | Stop. The token is missing, invalid, or revoked; ask the user to create or provide a valid token. |\n| `FORBIDDEN` | Stop and explain which operation was denied. Do not look for an internal bypass. |\n| `NOT_FOUND` | Re-check the target site and resource ID before deciding whether the item was removed. |\n| `CONFLICT` | Resolve the reported state conflict; never silently change a user-selected canonical slug. |\n| `RATE_LIMIT` | Respect `Retry-After` when present, back off, and keep bulk writes sequential. |\n| `CONFIGURATION_ERROR` | Surface the server message; the site owner may need to correct deployment configuration. |\n\nFor MCP, transport and protocol failures use JSON-RPC errors. Tool validation and domain failures are returned as tool results with `isError: true`; inspect their structured content before retrying.\n\n---\n\n## Reference\n\n- Full HTTP API: <https://jant.me/docs/API.md> — endpoints, fields, filters, and response schemas.\n- Automation overview: <https://jant.me/docs/automation-and-api.md> — tokens, HTTP, MCP, and debugging.\n- Round-trip Jant exports: <https://jant.me/docs/export-and-import.md> — use `site export` and `site import` when both ends are Jant.\n- Public documentation index: <https://jant.me/docs/SUMMARY.md>.\n";
|
|
77790
78554
|
//#endregion
|
|
77791
78555
|
//#region src/lib/site-skill.ts
|
|
77792
78556
|
var INTRODUCTION = "This page is written for AI assistants working with one Jant site. Use it when the user asks you to read, publish, edit, organize, search, or migrate site content through Jant's HTTP API or MCP interface.";
|
|
@@ -77815,7 +78579,7 @@ function replaceLiteral(content, search, replacement) {
|
|
|
77815
78579
|
const normalizedSiteUrl = normalizeSiteUrl(siteUrl);
|
|
77816
78580
|
if (!normalizedSiteUrl) throw new Error("A public site URL is required to render /skill.md");
|
|
77817
78581
|
const targetSiteUrl = normalizedSiteUrl.replace(/\/$/, "");
|
|
77818
|
-
if (!"---\nname: jant-site\ndescription: >-\n Work with the Jant site identified in this document through its HTTP API or\n MCP interface. Use when the user asks an AI assistant to read, publish, edit,\n organize, search, or migrate content, upload media, manage Collections, or\n update site settings.\n---\n\n# Jant Site Skill\n\nThis page is written for AI assistants working with one Jant site. Use it when the user asks you to read, publish, edit, organize, search, or migrate site content through Jant's HTTP API or MCP interface.\n\nThe full HTTP API reference lives at <https://jant.me/docs/API.md>. This skill explains how to choose the right interface, work safely, understand Jant's content model, and run common workflows. Consult the reference for complete request and response schemas instead of guessing fields.\n\n---\n\n## Scope and Safety\n\n- Use this skill only for the target site identified below. Do not substitute another site without the user's confirmation.\n- Start with read-only inspection when the state of the site or the user's intent is unclear.\n- Get explicit confirmation before bulk publishing, bulk deletion, destructive settings changes, or any action that is difficult to reverse. A request to perform a specific ordinary write, such as publishing one post, already supplies that confirmation.\n- For uncertain or bulk content changes, ask whether to save posts as drafts or publish them immediately.\n- Treat API tokens like passwords. Never log, commit, or repeat a token back to the user after they provide it.\n- Use the public API or MCP interface. Do not edit the database directly and do not call `/api/internal/*`; those endpoints belong to the hosted control plane.\n- Keep bulk writes sequential. Save returned IDs after each successful write so interrupted work can resume without creating duplicates.\n\n---\n\n## Choose an Interface\n\nJant exposes the same site-owner capabilities through two interfaces:\n\n| Interface | Use it when |\n| ----------------------- | ---------------------------------------------------------------------------------------------------- |\n| HTTP JSON API | Writing scripts, making a few direct requests, or running a one-time migration. This is the default. |\n| MCP at `<site>/api/mcp` | The caller already supports MCP and benefits from tool discovery and structured tool calls. |\n\nFor MCP, call `initialize`, then `tools/list`, and use the returned schemas rather than assuming tool arguments. The tool groups cover posts, media, attachments, Collections, settings, and search.\n\nFor HTTP, these are the main entry points:\n\n| Task | Endpoint |\n| ---------------------------- | ---------------------------------------------------------------- |\n| Read public posts | `GET /api/public/posts`, `GET /api/public/posts/:slug` |\n| List or inspect all posts | `GET /api/posts`, `GET /api/posts/:id` |\n| Create, update, delete | `POST /api/posts`, `PUT /api/posts/:id`, `DELETE /api/posts/:id` |\n| Upload or manage media | `/api/upload` or `/api/uploads` |\n| Manage Collections | `/api/collections` |\n| Search published content | `GET /api/search` |\n| Read or update site settings | `GET /api/settings`, `PUT /api/settings` |\n\nPublic post, Collection, navigation, and search reads can work without a token. A site can disable anonymous API reads; `/api/public/*` then becomes unavailable, while Collection, navigation, and search JSON reads require a browser session or Bearer token. Private content and all writes always require authentication.\n\n---\n\n## Confirm the Target and Authenticate\n\nBefore an authenticated or multi-step operation, confirm:\n\n- The Jant site URL (e.g. `https://example.com`).\n- The exact outcome the user wants, including which content may change.\n- For bulk work, whether new posts should use `status: \"published\"` or `status: \"draft\"`.\n\nHave the user create an API token when the operation needs authentication:\n\n1. Sign in to Jant at `<site>/signin`.\n2. Open **Settings → API Tokens**.\n3. Create a token and copy it immediately. It is shown only once.\n\nSend the token as `Authorization: Bearer jnt_...`.\n\n```bash\nexport JANT_API_TOKEN=jnt_...\nexport JANT_SITE=https://example.com\n```\n\n---\n\n## Understand the Content Model\n\nJant is a single-author microblog. There are no users, comments, likes, followers, or social relationships to manage.\n\nThree concepts shape almost every content operation:\n\n1. **Posts have three formats** — `note`, `link`, and `quote`. Preserve the semantic format instead of coercing everything into `note`.\n2. **Threads connect posts** — a reply is a post whose `replyToId` points to another post. There is no separate comments table.\n3. **Collections curate Threads** — they are intentional groupings, not tags. A Thread can belong to multiple Collections; its root and replies share the same memberships.\n\n### `note` — original writing\n\nUse for essays, journal entries, status updates, photo posts with captions, and other content written by the site owner.\n\n- Required: `format: \"note\"`\n- Recommended: `bodyMarkdown`\n- Optional: `title`\n\n### `link` — a shared reference\n\nUse when the post is fundamentally pointing readers to another resource.\n\n- Required: `format: \"link\"`, `title`, `url`\n- Optional: `bodyMarkdown` for the owner's commentary\n\n### `quote` — a cited passage\n\nUse when the post is built around someone else's words.\n\n- Required: `format: \"quote\"`, `quoteText`\n- Optional: `sourceName`, `sourceUrl`, and `bodyMarkdown` for commentary\n- Do not send `title` or `url`; quote posts use `sourceName` and `sourceUrl` instead.\n\n---\n\n## Common Content Operations\n\nRead the current state before modifying existing content. Use `GET /api/posts/:id` when you need fields that may not appear in a list response, including Thread-level Collection memberships.\n\nCreate a note with an explicit status and visibility:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/posts\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"format\": \"note\",\n \"bodyMarkdown\": \"Hello from Jant.\",\n \"status\": \"published\",\n \"visibility\": \"public\"\n }'\n```\n\nUse `PUT /api/posts/:id` to update a post and `DELETE /api/posts/:id` to delete one. Fetch the post first, preserve fields the user did not ask to change, and confirm before deletion.\n\nUse `POST /api/upload` for an ordinary single-file script or one-time migration. Use the session-based `/api/uploads` flow for large files, unreliable connections, or clients that need resumable transport. Save the returned `med_*` ID before attaching media to a post.\n\nUse `GET /api/settings` before `PUT /api/settings`. Settings values are strings in the HTTP API; preserve settings outside the user's requested change.\n\nFor exact fields, filters, pagination, and response schemas, read the [full HTTP API reference](https://jant.me/docs/API.md).\n\n---\n\n## Import Content from Another Platform\n\nUse this workflow when the user wants to move an old blog, site, or archive into this Jant site. The request may arrive as one sentence, with no export and no token yet. Lead the user through the rest.\n\n### Lead the user\n\nAsk for one thing at a time, when the next step needs it. Name the menus the user clicks, not API endpoints.\n\n1. Check that you can send HTTP requests to `<site>` and read files the user gives you. If you cannot, say so first and suggest an assistant that can, such as a coding agent with shell access. Do not hand over a script unless the user asks for one.\n2. Ask which platform the old blog is on and where it lives.\n3. Get the content. Use an export if the user has one. If not, tell them where their platform exports it (the table under \"Read the source\" lists the usual places) and wait for the file. When the old blog is public and its feed carries full posts, you can read the feed instead. Feeds usually hold only recent posts, so compare the count with the old blog's archive before relying on one.\n4. Ask for the API token just before the first write, using the steps in \"Confirm the Target and Authenticate\". Do not ask for it at the start.\n\n### Plan before writing\n\n1. Inspect the target site so you know whether it already contains content.\n2. Inspect 3–5 representative source posts end to end before deciding how to transform anything.\n3. Report what you found: source formats, item counts, dates, media, internal links, categories, and anything unsupported.\n4. Ask how to handle ambiguous categories or tags. Map them to Collections, drop them, or fold them into post bodies only with the user's direction.\n5. Agree on draft versus published status and on a duplicate policy before creating posts.\n6. Build a resumable source-ID map and persist `{ sourceId -> jantId, slug }` after every successful write.\n\nA slug or path collision returns `409 CONFLICT`, but that does not make an import automatically idempotent. Items with new or generated slugs can still be duplicated, so use the source-ID map rather than relying on conflicts.\n\n### Read the source\n\nCommon source shapes include:\n\n| Source | Typical export |\n| --------------------- | ----------------------------------------------------------------------- |\n| WordPress | WXR XML (`Tools → Export`), with media URLs pointing at the source host |\n| Ghost | JSON export from `Settings → Labs → Export` |\n| Substack | ZIP with `posts.csv` and `posts/*.html` |\n| Medium | ZIP with `posts/*.html` |\n| Tumblr | API dump or `tumblr-utils` archive |\n| Hugo / Jekyll / Astro | Markdown files with YAML or TOML front matter |\n| Notion | Markdown plus a media ZIP |\n| Custom | SQL dump, HTML folder, RSS feed, or another structured source |\n\nDo not assume the source schema from the platform name alone. Check titles, bodies, dates, embedded media, internal links, categories, and source identifiers in real records.\n\n### Map source formats\n\nUse these heuristics as a starting point:\n\n- WordPress, Ghost, and Substack standard posts → `note` with `title` and `bodyMarkdown`.\n- Linklog posts that are primarily an external URL plus commentary → `link`.\n- WordPress or Tumblr quote posts → `quote`.\n- Tumblr photo posts with captions → `note` with uploaded images.\n- Tumblr link posts → `link`.\n- Reblogs or reposts → ask the user. Jant has no native reblog concept; `quote` with `sourceUrl` is often the closest representation.\n\nWhen uncertain, prefer `note`. Turning a real `link` or `quote` into a `note` loses semantic information, while turning original writing into a `link` or `quote` invents structure.\n\n### Convert bodies to Markdown\n\nSend `bodyMarkdown`, not `body`. The `body` field expects TipTap JSON and is intended for editor integrations.\n\n- Convert HTML with a real HTML-to-Markdown tool such as Turndown or Pandoc. Do not strip tags with regular expressions.\n- Preserve headings, lists, tables, fenced code blocks, blockquotes, and inline formatting.\n- A blank line starts a new paragraph. Use two trailing spaces or a backslash for a hard line break.\n- Preserve `<!--more-->` when the source has an intentional excerpt break.\n- Upload embedded media to Jant instead of leaving remote `<img>` references that may disappear with the old site.\n- Rewrite internal links after the destination slugs are known. Either build the slug map first or use a two-pass process: create posts, then update their bodies.\n\n### Upload media first\n\nPosts reference uploaded media by `med_*` ID. For a one-time migration, the one-shot endpoint is usually enough:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/upload\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -F \"file=@./photo.jpg\" \\\n -F \"alt=A red door\"\n# → { \"id\": \"med_...\", \"url\": \"/media/med_....jpg\", ... }\n```\n\nUse `/api/uploads` when a file is large or the connection is unreliable. Its session flow initializes the upload, transfers one or more parts, optionally adds a video poster, and completes the session to produce the final `med_*` record.\n\nPreserve source alt text. If the source has no alt text, leave it unset rather than inventing a description.\n\n### Create Collections when needed\n\nCreate approved Collections before the posts that use them:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/collections\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"slug\": \"reading\",\n \"title\": \"Reading\",\n \"description\": \"Books worth coming back to\",\n \"sortOrder\": \"newest\"\n }'\n```\n\nSave each returned `col_*` ID. Send `collectionIds` on standalone posts and Thread roots, not on replies.\n\n### Create posts\n\n`POST /api/posts` creates every post format. Send one post at a time and record the result before continuing.\n\nMinimal `note`:\n\n```json\n{\n \"format\": \"note\",\n \"title\": \"Hello world\",\n \"bodyMarkdown\": \"First post on the new site.\",\n \"publishedAt\": 1706000000,\n \"status\": \"draft\"\n}\n```\n\nMinimal `link`:\n\n```json\n{\n \"format\": \"link\",\n \"title\": \"An interesting article\",\n \"url\": \"https://example.com/post\",\n \"bodyMarkdown\": \"Worth your fifteen minutes.\"\n}\n```\n\nMinimal `quote`:\n\n```json\n{\n \"format\": \"quote\",\n \"quoteText\": \"What stands in the way becomes the way.\",\n \"sourceName\": \"Marcus Aurelius\",\n \"sourceUrl\": \"https://example.com/meditations\"\n}\n```\n\nFields commonly needed during migration:\n\n| Field | Purpose |\n| --------------- | ------------------------------------------------------------------------------------------ |\n| `publishedAt` | Original publication time as Unix seconds, preserving archive chronology. |\n| `slug` | Original stable slug when it should remain the canonical URL. |\n| `path` | Alternative to `slug` for an original path such as `2024/01/hello-world`; never send both. |\n| `status` | `published` or `draft`; set it explicitly according to the import plan. |\n| `visibility` | `public`, `latest_hidden`, or `private`. |\n| `pinned` | Preserve a pinned state when the source had one; replies cannot be pinned. |\n| `featured` | Preserve a featured or starred state when it has the same meaning. |\n| `collectionIds` | Approved `col_*` IDs on standalone posts and Thread roots. |\n| `attachments` | Ordered media or text attachments. |\n| `replyToId` | Destination `pst_*` ID of the parent when importing a Thread reply. |\n\nRemember these validation rules:\n\n- Send either `body` or `bodyMarkdown`, never both.\n- Send either `slug` or `path`, never both.\n- `note` rejects link- and quote-specific fields.\n- `link` requires `title` and `url`.\n- `quote` requires `quoteText`, uses `sourceName` and `sourceUrl`, and rejects `title` and `url`.\n\nA successful create returns `201` with the full post. Save `id`, `slug`, and `threadId` under the source ID for replies, link rewriting, verification, and recovery.\n\n### Rebuild Threads\n\n1. Import the Thread root first.\n2. Import replies in parent-first order with `replyToId` set to the destination parent's `pst_*` ID.\n3. Do not set `threadId`; Jant derives it from `replyToId`.\n4. Set `collectionIds` on the root only. Replies share the Thread's Collection memberships.\n5. Replies inherit root visibility and status unless explicitly created as drafts. They cannot be pinned or receive independent visibility changes.\n\n### Verify and report\n\nAfter the import:\n\n- Compare source and destination counts by format, media type, Collection, and Thread.\n- Fetch representative posts through `GET /api/posts/:id` and verify dates, slugs, bodies, attachments, Collection memberships, and reply relationships.\n- Open representative public URLs and verify rendered Markdown, media, and rewritten internal links.\n- Report anything skipped, transformed, duplicated, or unresolved, with a short list of URLs for manual review.\n\nIf an import stops partway through, resume from the persisted source-ID map. If cleanup is required, identify only the posts, media, and Collections created by that run, show the user the cleanup scope, and get confirmation before deleting them. Do not use account deletion as an automated recovery strategy.\n\n---\n\n## Handle Errors\n\nHTTP API errors use this shape:\n\n```json\n{ \"error\": \"...\", \"code\": \"VALIDATION_ERROR\", \"details\": {} }\n```\n\n| Code | Response |\n| --------------------- | ------------------------------------------------------------------------------------------------- |\n| `VALIDATION_ERROR` | Read `details.fieldErrors`, correct the request, and do not retry unchanged input. |\n| `UNAUTHORIZED` | Stop. The token is missing, invalid, or revoked; ask the user to create or provide a valid token. |\n| `FORBIDDEN` | Stop and explain which operation was denied. Do not look for an internal bypass. |\n| `NOT_FOUND` | Re-check the target site and resource ID before deciding whether the item was removed. |\n| `CONFLICT` | Resolve the reported state conflict; never silently change a user-selected canonical slug. |\n| `RATE_LIMIT` | Respect `Retry-After` when present, back off, and keep bulk writes sequential. |\n| `CONFIGURATION_ERROR` | Surface the server message; the site owner may need to correct deployment configuration. |\n\nFor MCP, transport and protocol failures use JSON-RPC errors. Tool validation and domain failures are returned as tool results with `isError: true`; inspect their structured content before retrying.\n\n---\n\n## Reference\n\n- Full HTTP API: <https://jant.me/docs/API.md> — endpoints, fields, filters, and response schemas.\n- Automation overview: <https://jant.me/docs/automation-and-api.md> — tokens, HTTP, MCP, and debugging.\n- Round-trip Jant exports: <https://jant.me/docs/export-and-import.md> — use `site export` and `site import` when both ends are Jant.\n- Public documentation index: <https://jant.me/docs/SUMMARY.md>.\n".includes(INTRODUCTION)) throw new Error("The site skill template introduction could not be found");
|
|
78582
|
+
if (!"---\nname: jant-site\ndescription: >-\n Work with the Jant site identified in this document through its HTTP API or\n MCP interface. Use when the user asks an AI assistant to read, publish, edit,\n organize, search, or migrate content, upload media, manage Collections, or\n update site settings.\n---\n\n# Jant Site Skill\n\nThis page is written for AI assistants working with one Jant site. Use it when the user asks you to read, publish, edit, organize, search, or migrate site content through Jant's HTTP API or MCP interface.\n\nThe full HTTP API reference lives at <https://jant.me/docs/API.md>. This skill explains how to choose the right interface, work safely, understand Jant's content model, and run common workflows. Consult the reference for complete request and response schemas instead of guessing fields.\n\n---\n\n## Scope and Safety\n\n- Use this skill only for the target site identified below. Do not substitute another site without the user's confirmation.\n- Start with read-only inspection when the state of the site or the user's intent is unclear.\n- Get explicit confirmation before bulk publishing, bulk deletion, destructive settings changes, or any action that is difficult to reverse. A request to perform a specific ordinary write, such as publishing one post, already supplies that confirmation.\n- For uncertain or bulk content changes, ask whether to save posts as drafts or publish them immediately.\n- Treat API tokens like passwords. Never log, commit, or repeat a token back to the user after they provide it.\n- Use the public API or MCP interface. Do not edit the database directly and do not call `/api/internal/*`; those endpoints belong to the hosted control plane.\n- Keep bulk writes sequential. Save returned IDs after each successful write so interrupted work can resume without creating duplicates.\n\n---\n\n## Choose an Interface\n\nJant exposes the same site-owner capabilities through two interfaces:\n\n| Interface | Use it when |\n| ----------------------- | ---------------------------------------------------------------------------------------------------- |\n| HTTP JSON API | Writing scripts, making a few direct requests, or running a one-time migration. This is the default. |\n| MCP at `<site>/api/mcp` | The caller already supports MCP and benefits from tool discovery and structured tool calls. |\n\nFor MCP, call `initialize`, then `tools/list`, and use the returned schemas rather than assuming tool arguments. The tool groups cover posts, Threads, media, attachments, Collections, settings, and search.\n\nFor HTTP, these are the main entry points:\n\n| Task | Endpoint |\n| ---------------------------- | ---------------------------------------------------------------- |\n| Read public Threads | `GET /api/public/threads`, `GET /api/public/threads/:slug/posts` |\n| Read one public post | `GET /api/public/posts/:slug` |\n| List or inspect all posts | `GET /api/posts`, `GET /api/posts/:id` |\n| List or read whole Threads | `GET /api/threads`, `GET /api/threads/:id/posts` |\n| Create, update, delete | `POST /api/posts`, `PUT /api/posts/:id`, `DELETE /api/posts/:id` |\n| Upload or manage media | `/api/upload` or `/api/uploads` |\n| Manage Collections | `/api/collections` |\n| Search published content | `GET /api/search` |\n| Read or update site settings | `GET /api/settings`, `PUT /api/settings` |\n\nPublic post, Thread, Collection, navigation, and search reads can work without a token. A site can disable anonymous API reads; `/api/public/*` then becomes unavailable, while Collection, navigation, and search JSON reads require a browser session or Bearer token. Private content and all writes always require authentication.\n\n---\n\n## Confirm the Target and Authenticate\n\nBefore an authenticated or multi-step operation, confirm:\n\n- The Jant site URL (e.g. `https://example.com`).\n- The exact outcome the user wants, including which content may change.\n- For bulk work, whether new posts should use `status: \"published\"` or `status: \"draft\"`.\n\nHave the user create an API token when the operation needs authentication:\n\n1. Sign in to Jant at `<site>/signin`.\n2. Open **Settings → API Tokens**.\n3. Create a token and copy it immediately. It is shown only once.\n\nSend the token as `Authorization: Bearer jnt_...`.\n\n```bash\nexport JANT_API_TOKEN=jnt_...\nexport JANT_SITE=https://example.com\n```\n\n---\n\n## Understand the Content Model\n\nJant is a single-author microblog. There are no users, comments, likes, followers, or social relationships to manage.\n\nThree concepts shape almost every content operation:\n\n1. **Posts have three formats** — `note`, `link`, and `quote`. Preserve the semantic format instead of coercing everything into `note`.\n2. **Threads connect posts** — a reply is a post whose `replyToId` points to another post. There is no separate comments table. A post's `threadPostCount` says how many posts its Thread holds; read them all with `GET /api/threads/:id/posts`, passing any post's ID, rather than collecting replies from the post list.\n3. **Collections curate Threads** — they are intentional groupings, not tags. A Thread can belong to multiple Collections; its root and replies share the same memberships.\n\n### `note` — original writing\n\nUse for essays, journal entries, status updates, photo posts with captions, and other content written by the site owner.\n\n- Required: `format: \"note\"`\n- Recommended: `bodyMarkdown`\n- Optional: `title`\n\n### `link` — a shared reference\n\nUse when the post is fundamentally pointing readers to another resource.\n\n- Required: `format: \"link\"`, `title`, `url`\n- Optional: `bodyMarkdown` for the owner's commentary\n\n### `quote` — a cited passage\n\nUse when the post is built around someone else's words.\n\n- Required: `format: \"quote\"`, `quoteText`\n- Optional: `sourceName`, `sourceUrl`, and `bodyMarkdown` for commentary\n- Do not send `title` or `url`; quote posts use `sourceName` and `sourceUrl` instead.\n\n---\n\n## Common Content Operations\n\nRead the current state before modifying existing content. Use `GET /api/posts/:id` when you need fields that may not appear in a list response, including Thread-level Collection memberships.\n\nCreate a note with an explicit status and visibility:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/posts\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"format\": \"note\",\n \"bodyMarkdown\": \"Hello from Jant.\",\n \"status\": \"published\",\n \"visibility\": \"public\"\n }'\n```\n\nUse `PUT /api/posts/:id` to update a post and `DELETE /api/posts/:id` to delete one. Fetch the post first, preserve fields the user did not ask to change, and confirm before deletion.\n\nUse `POST /api/upload` for an ordinary single-file script or one-time migration. Use the session-based `/api/uploads` flow for large files, unreliable connections, or clients that need resumable transport. Save the returned `med_*` ID before attaching media to a post.\n\nUse `GET /api/settings` before `PUT /api/settings`. Settings values are strings in the HTTP API; preserve settings outside the user's requested change.\n\nFor exact fields, filters, pagination, and response schemas, read the [full HTTP API reference](https://jant.me/docs/API.md).\n\n---\n\n## Import Content from Another Platform\n\nUse this workflow when the user wants to move an old blog, site, or archive into this Jant site. The request may arrive as one sentence, with no export and no token yet. Lead the user through the rest.\n\n### Lead the user\n\nAsk for one thing at a time, when the next step needs it. Name the menus the user clicks, not API endpoints.\n\n1. Check that you can send HTTP requests to `<site>` and read files the user gives you. If you cannot, say so first and suggest an assistant that can, such as a coding agent with shell access. Do not hand over a script unless the user asks for one.\n2. Ask which platform the old blog is on and where it lives.\n3. Get the content. Use an export if the user has one. If not, tell them where their platform exports it (the table under \"Read the source\" lists the usual places) and wait for the file. When the old blog is public and its feed carries full posts, you can read the feed instead. Feeds usually hold only recent posts, so compare the count with the old blog's archive before relying on one.\n4. Ask for the API token just before the first write, using the steps in \"Confirm the Target and Authenticate\". Do not ask for it at the start.\n\n### Plan before writing\n\n1. Inspect the target site so you know whether it already contains content.\n2. Inspect 3–5 representative source posts end to end before deciding how to transform anything.\n3. Report what you found: source formats, item counts, dates, media, internal links, categories, and anything unsupported.\n4. Ask how to handle ambiguous categories or tags. Map them to Collections, drop them, or fold them into post bodies only with the user's direction.\n5. Agree on draft versus published status and on a duplicate policy before creating posts.\n6. Build a resumable source-ID map and persist `{ sourceId -> jantId, slug }` after every successful write.\n\nA slug or path collision returns `409 CONFLICT`, but that does not make an import automatically idempotent. Items with new or generated slugs can still be duplicated, so use the source-ID map rather than relying on conflicts.\n\n### Read the source\n\nCommon source shapes include:\n\n| Source | Typical export |\n| --------------------- | ----------------------------------------------------------------------- |\n| WordPress | WXR XML (`Tools → Export`), with media URLs pointing at the source host |\n| Ghost | JSON export from `Settings → Labs → Export` |\n| Substack | ZIP with `posts.csv` and `posts/*.html` |\n| Medium | ZIP with `posts/*.html` |\n| Tumblr | API dump or `tumblr-utils` archive |\n| Hugo / Jekyll / Astro | Markdown files with YAML or TOML front matter |\n| Notion | Markdown plus a media ZIP |\n| Custom | SQL dump, HTML folder, RSS feed, or another structured source |\n\nDo not assume the source schema from the platform name alone. Check titles, bodies, dates, embedded media, internal links, categories, and source identifiers in real records.\n\n### Map source formats\n\nUse these heuristics as a starting point:\n\n- WordPress, Ghost, and Substack standard posts → `note` with `title` and `bodyMarkdown`.\n- Linklog posts that are primarily an external URL plus commentary → `link`.\n- WordPress or Tumblr quote posts → `quote`.\n- Tumblr photo posts with captions → `note` with uploaded images.\n- Tumblr link posts → `link`.\n- Reblogs or reposts → ask the user. Jant has no native reblog concept; `quote` with `sourceUrl` is often the closest representation.\n\nWhen uncertain, prefer `note`. Turning a real `link` or `quote` into a `note` loses semantic information, while turning original writing into a `link` or `quote` invents structure.\n\n### Convert bodies to Markdown\n\nSend `bodyMarkdown`, not `body`. The `body` field expects TipTap JSON and is intended for editor integrations.\n\n- Convert HTML with a real HTML-to-Markdown tool such as Turndown or Pandoc. Do not strip tags with regular expressions.\n- Preserve headings, lists, tables, fenced code blocks, blockquotes, and inline formatting.\n- A blank line starts a new paragraph. Use two trailing spaces or a backslash for a hard line break.\n- Preserve `<!--more-->` when the source has an intentional excerpt break.\n- Upload embedded media to Jant instead of leaving remote `<img>` references that may disappear with the old site.\n- Rewrite internal links after the destination slugs are known. Either build the slug map first or use a two-pass process: create posts, then update their bodies.\n\n### Upload media first\n\nPosts reference uploaded media by `med_*` ID. For a one-time migration, the one-shot endpoint is usually enough:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/upload\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -F \"file=@./photo.jpg\" \\\n -F \"alt=A red door\"\n# → { \"id\": \"med_...\", \"url\": \"/media/med_....jpg\", ... }\n```\n\nUse `/api/uploads` when a file is large or the connection is unreliable. Its session flow initializes the upload, transfers one or more parts, optionally adds a video poster, and completes the session to produce the final `med_*` record.\n\nPreserve source alt text. If the source has no alt text, leave it unset rather than inventing a description.\n\n### Create Collections when needed\n\nCreate approved Collections before the posts that use them:\n\n```bash\ncurl -X POST \"$JANT_SITE/api/collections\" \\\n -H \"Authorization: Bearer $JANT_API_TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"slug\": \"reading\",\n \"title\": \"Reading\",\n \"description\": \"Books worth coming back to\",\n \"sortOrder\": \"newest\"\n }'\n```\n\nSave each returned `col_*` ID. Send `collectionIds` on standalone posts and Thread roots, not on replies.\n\n### Create posts\n\n`POST /api/posts` creates every post format. Send one post at a time and record the result before continuing.\n\nMinimal `note`:\n\n```json\n{\n \"format\": \"note\",\n \"title\": \"Hello world\",\n \"bodyMarkdown\": \"First post on the new site.\",\n \"publishedAt\": 1706000000,\n \"status\": \"draft\"\n}\n```\n\nMinimal `link`:\n\n```json\n{\n \"format\": \"link\",\n \"title\": \"An interesting article\",\n \"url\": \"https://example.com/post\",\n \"bodyMarkdown\": \"Worth your fifteen minutes.\"\n}\n```\n\nMinimal `quote`:\n\n```json\n{\n \"format\": \"quote\",\n \"quoteText\": \"What stands in the way becomes the way.\",\n \"sourceName\": \"Marcus Aurelius\",\n \"sourceUrl\": \"https://example.com/meditations\"\n}\n```\n\nFields commonly needed during migration:\n\n| Field | Purpose |\n| --------------- | ------------------------------------------------------------------------------------------ |\n| `publishedAt` | Original publication time as Unix seconds, preserving archive chronology. |\n| `slug` | Original stable slug when it should remain the canonical URL. |\n| `path` | Alternative to `slug` for an original path such as `2024/01/hello-world`; never send both. |\n| `status` | `published` or `draft`; set it explicitly according to the import plan. |\n| `visibility` | `public`, `latest_hidden`, or `private`. |\n| `pinned` | Preserve a pinned state when the source had one; replies cannot be pinned. |\n| `featured` | Preserve a featured or starred state when it has the same meaning. |\n| `collectionIds` | Approved `col_*` IDs on standalone posts and Thread roots. |\n| `attachments` | Ordered media or text attachments. |\n| `replyToId` | Destination `pst_*` ID of the parent when importing a Thread reply. |\n\nRemember these validation rules:\n\n- Send either `body` or `bodyMarkdown`, never both.\n- Send either `slug` or `path`, never both.\n- `note` rejects link- and quote-specific fields.\n- `link` requires `title` and `url`.\n- `quote` requires `quoteText`, uses `sourceName` and `sourceUrl`, and rejects `title` and `url`.\n\nA successful create returns `201` with the full post. Save `id`, `slug`, and `threadId` under the source ID for replies, link rewriting, verification, and recovery.\n\n### Rebuild Threads\n\n1. Import the Thread root first.\n2. Import replies in parent-first order with `replyToId` set to the destination parent's `pst_*` ID.\n3. Do not set `threadId`; Jant derives it from `replyToId`.\n4. Set `collectionIds` on the root only. Replies share the Thread's Collection memberships.\n5. Replies inherit root visibility and status unless explicitly created as drafts. They cannot be pinned or receive independent visibility changes.\n\n### Verify and report\n\nAfter the import:\n\n- Compare source and destination counts by format, media type, Collection, and Thread.\n- Fetch representative posts through `GET /api/posts/:id` and verify dates, slugs, bodies, attachments, Collection memberships, and reply relationships.\n- Open representative public URLs and verify rendered Markdown, media, and rewritten internal links.\n- Report anything skipped, transformed, duplicated, or unresolved, with a short list of URLs for manual review.\n\nIf an import stops partway through, resume from the persisted source-ID map. If cleanup is required, identify only the posts, media, and Collections created by that run, show the user the cleanup scope, and get confirmation before deleting them. Do not use account deletion as an automated recovery strategy.\n\n---\n\n## Handle Errors\n\nHTTP API errors use this shape:\n\n```json\n{ \"error\": \"...\", \"code\": \"VALIDATION_ERROR\", \"details\": {} }\n```\n\n| Code | Response |\n| --------------------- | ------------------------------------------------------------------------------------------------- |\n| `VALIDATION_ERROR` | Read `details.fieldErrors`, correct the request, and do not retry unchanged input. |\n| `UNAUTHORIZED` | Stop. The token is missing, invalid, or revoked; ask the user to create or provide a valid token. |\n| `FORBIDDEN` | Stop and explain which operation was denied. Do not look for an internal bypass. |\n| `NOT_FOUND` | Re-check the target site and resource ID before deciding whether the item was removed. |\n| `CONFLICT` | Resolve the reported state conflict; never silently change a user-selected canonical slug. |\n| `RATE_LIMIT` | Respect `Retry-After` when present, back off, and keep bulk writes sequential. |\n| `CONFIGURATION_ERROR` | Surface the server message; the site owner may need to correct deployment configuration. |\n\nFor MCP, transport and protocol failures use JSON-RPC errors. Tool validation and domain failures are returned as tool results with `isError: true`; inspect their structured content before retrying.\n\n---\n\n## Reference\n\n- Full HTTP API: <https://jant.me/docs/API.md> — endpoints, fields, filters, and response schemas.\n- Automation overview: <https://jant.me/docs/automation-and-api.md> — tokens, HTTP, MCP, and debugging.\n- Round-trip Jant exports: <https://jant.me/docs/export-and-import.md> — use `site export` and `site import` when both ends are Jant.\n- Public documentation index: <https://jant.me/docs/SUMMARY.md>.\n".includes(INTRODUCTION)) throw new Error("The site skill template introduction could not be found");
|
|
77819
78583
|
const missingMarker = GENERIC_SITE_MARKERS.find((marker) => !skill_default.includes(marker));
|
|
77820
78584
|
if (missingMarker) throw new Error(`The site skill template target marker could not be found: ${missingMarker}`);
|
|
77821
78585
|
let content = skill_default;
|
|
@@ -78753,7 +79517,12 @@ var cors = (options) => {
|
|
|
78753
79517
|
"Authorization",
|
|
78754
79518
|
"MCP-Protocol-Version"
|
|
78755
79519
|
],
|
|
78756
|
-
exposeHeaders: [
|
|
79520
|
+
exposeHeaders: [
|
|
79521
|
+
"Content-Type",
|
|
79522
|
+
"MCP-Protocol-Version",
|
|
79523
|
+
"Deprecation",
|
|
79524
|
+
"Link"
|
|
79525
|
+
],
|
|
78757
79526
|
credentials: origins !== "*",
|
|
78758
79527
|
maxAge: 86400
|
|
78759
79528
|
})(c, next);
|
|
@@ -81192,6 +81961,168 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
|
|
|
81192
81961
|
} };
|
|
81193
81962
|
}
|
|
81194
81963
|
//#endregion
|
|
81964
|
+
//#region src/services/thread.ts
|
|
81965
|
+
/**
|
|
81966
|
+
* Thread Service
|
|
81967
|
+
*
|
|
81968
|
+
* Threads as a resource of their own: a list of Thread roots in one of the
|
|
81969
|
+
* orders the site shows, each with its Post count and, on request, the fold the
|
|
81970
|
+
* homepage draws; one Thread by any of its Posts; and a Thread's Posts in Thread
|
|
81971
|
+
* order.
|
|
81972
|
+
*
|
|
81973
|
+
* Every read goes through `PostService`. What lives here is the choice of read:
|
|
81974
|
+
* which order a request names, when a collection's own order and pins apply,
|
|
81975
|
+
* and what a reader may see as opposed to the author.
|
|
81976
|
+
*/ var FEATURED_SORT_MESSAGE = "Featured posts are listed newest-published first. Leave sort out, or pass sort=published.";
|
|
81977
|
+
/**
|
|
81978
|
+
* How a plain Thread list orders each `ThreadSort`, as `PostFilters` fields.
|
|
81979
|
+
* Only `activity`, the homepage's order, puts pinned Threads first.
|
|
81980
|
+
*/ function toListOrder(sort) {
|
|
81981
|
+
switch (sort) {
|
|
81982
|
+
case "activity": return {
|
|
81983
|
+
sortBy: "activity",
|
|
81984
|
+
sortOrder: "newest"
|
|
81985
|
+
};
|
|
81986
|
+
case "published": return {
|
|
81987
|
+
sortBy: "published",
|
|
81988
|
+
sortOrder: "newest",
|
|
81989
|
+
ignorePinnedSort: true
|
|
81990
|
+
};
|
|
81991
|
+
case "updated": return {
|
|
81992
|
+
sortBy: "thread_updated",
|
|
81993
|
+
sortOrder: "newest",
|
|
81994
|
+
ignorePinnedSort: true
|
|
81995
|
+
};
|
|
81996
|
+
case "oldest": return {
|
|
81997
|
+
sortBy: "published",
|
|
81998
|
+
sortOrder: "oldest",
|
|
81999
|
+
ignorePinnedSort: true
|
|
82000
|
+
};
|
|
82001
|
+
case "rating": return {
|
|
82002
|
+
sortBy: "activity",
|
|
82003
|
+
sortOrder: "rating_desc",
|
|
82004
|
+
ignorePinnedSort: true
|
|
82005
|
+
};
|
|
82006
|
+
}
|
|
82007
|
+
}
|
|
82008
|
+
/**
|
|
82009
|
+
* The collection order a `ThreadSort` names, or null for the two that read a
|
|
82010
|
+
* collection as a plain filter.
|
|
82011
|
+
*/ function toCollectionOrder(sort) {
|
|
82012
|
+
switch (sort) {
|
|
82013
|
+
case "activity": return "newest";
|
|
82014
|
+
case "oldest": return "oldest";
|
|
82015
|
+
case "rating": return "rating_desc";
|
|
82016
|
+
case "published":
|
|
82017
|
+
case "updated": return null;
|
|
82018
|
+
}
|
|
82019
|
+
}
|
|
82020
|
+
/**
|
|
82021
|
+
* Create the Thread service.
|
|
82022
|
+
*
|
|
82023
|
+
* @param deps - The Post and collection services it reads through
|
|
82024
|
+
* @returns The Thread service
|
|
82025
|
+
* @example
|
|
82026
|
+
* const threads = createThreadService({ posts, collections });
|
|
82027
|
+
*/ function createThreadService(deps) {
|
|
82028
|
+
const { posts, collections } = deps;
|
|
82029
|
+
/**
|
|
82030
|
+
* The order a collection's page would use: its configured order when it is
|
|
82031
|
+
* the only one named, activity for several. A rating order with fewer than
|
|
82032
|
+
* two rated Threads falls back, as the page does — for the default only; a
|
|
82033
|
+
* caller who asks for `rating` gets it.
|
|
82034
|
+
*/ async function resolveDefaultCollectionOrder(collectionIds, options) {
|
|
82035
|
+
const [onlyId, ...others] = collectionIds;
|
|
82036
|
+
if (!onlyId || others.length > 0) return "newest";
|
|
82037
|
+
const collection = await collections.getById(onlyId);
|
|
82038
|
+
if (!collection) return "newest";
|
|
82039
|
+
const ratedThreadCount = await posts.countCollectionThreadRootsUpToForCollections([onlyId], {
|
|
82040
|
+
...options,
|
|
82041
|
+
hasRating: true
|
|
82042
|
+
}, 2);
|
|
82043
|
+
return resolveCollectionSortOrder(void 0, collection.sortOrder, supportsCollectionRatingSort(ratedThreadCount));
|
|
82044
|
+
}
|
|
82045
|
+
const service = {
|
|
82046
|
+
async listThreads(query, page) {
|
|
82047
|
+
const reader = query.audience === "reader";
|
|
82048
|
+
const { selection } = query;
|
|
82049
|
+
const visibility = selection.visibility;
|
|
82050
|
+
if (reader && visibility === "private") throw new ValidationError("Private posts aren't listed here.");
|
|
82051
|
+
if (visibility === "featured" && query.sort !== void 0 && query.sort !== "published") throw new ValidationError(FEATURED_SORT_MESSAGE);
|
|
82052
|
+
const base = {
|
|
82053
|
+
status: reader ? "published" : query.status ?? "published",
|
|
82054
|
+
excludePrivate: reader,
|
|
82055
|
+
excludeLatestHidden: reader && visibility === void 0 && !query.includeHidden,
|
|
82056
|
+
lang: query.lang
|
|
82057
|
+
};
|
|
82058
|
+
const collectionIds = selection.collection;
|
|
82059
|
+
if (collectionIds && visibility !== "featured") {
|
|
82060
|
+
const { collection: _named, ...rootSelection } = selection;
|
|
82061
|
+
const options = {
|
|
82062
|
+
...base,
|
|
82063
|
+
rootFilters: toPostFilters(rootSelection, { yearAxis: "published" })
|
|
82064
|
+
};
|
|
82065
|
+
const collectionOrder = query.sort === void 0 ? await resolveDefaultCollectionOrder(collectionIds, options) : toCollectionOrder(query.sort);
|
|
82066
|
+
if (collectionOrder) {
|
|
82067
|
+
const result = await posts.listCollectionThreadRootPage([...collectionIds], {
|
|
82068
|
+
...options,
|
|
82069
|
+
sortOrder: collectionOrder
|
|
82070
|
+
}, page);
|
|
82071
|
+
return {
|
|
82072
|
+
threads: await service.summarize(result.posts, query),
|
|
82073
|
+
nextCursor: result.nextCursor
|
|
82074
|
+
};
|
|
82075
|
+
}
|
|
82076
|
+
}
|
|
82077
|
+
const result = await posts.listPage({
|
|
82078
|
+
...base,
|
|
82079
|
+
excludeReplies: true,
|
|
82080
|
+
...toPostFilters(selection, { yearAxis: "published" }),
|
|
82081
|
+
...visibility === "featured" ? toListOrder("published") : toListOrder(query.sort ?? "activity")
|
|
82082
|
+
}, page);
|
|
82083
|
+
return {
|
|
82084
|
+
threads: await service.summarize(result.posts, query),
|
|
82085
|
+
nextCursor: result.nextCursor
|
|
82086
|
+
};
|
|
82087
|
+
},
|
|
82088
|
+
async findRoot(ref, audience) {
|
|
82089
|
+
const post = "id" in ref ? await posts.getById(ref.id) : await posts.getBySlug(ref.slug);
|
|
82090
|
+
if (!post) return null;
|
|
82091
|
+
if (audience === "reader" && post.status !== "published") return null;
|
|
82092
|
+
const root = post.threadId === post.id ? post : await posts.getById(post.threadId);
|
|
82093
|
+
if (!root) return null;
|
|
82094
|
+
if (audience === "reader" && (root.status !== "published" || root.visibility === "private")) return null;
|
|
82095
|
+
return root;
|
|
82096
|
+
},
|
|
82097
|
+
async summarize(roots, options) {
|
|
82098
|
+
if (roots.length === 0) return [];
|
|
82099
|
+
const rootIds = roots.map((root) => root.id);
|
|
82100
|
+
const [counts, contexts] = await Promise.all([posts.countThreadPosts(rootIds), options.fold ? posts.getThreadTimelineContext(rootIds) : Promise.resolve(null)]);
|
|
82101
|
+
return roots.map((root) => {
|
|
82102
|
+
const summary = {
|
|
82103
|
+
root,
|
|
82104
|
+
postCount: counts.get(root.id) ?? 0
|
|
82105
|
+
};
|
|
82106
|
+
if (contexts) {
|
|
82107
|
+
const context = contexts.get(root.id);
|
|
82108
|
+
summary.fold = context ? foldReplyWindows({
|
|
82109
|
+
leadingReplies: context.leadingReplies,
|
|
82110
|
+
trailingReplies: context.trailingReplies,
|
|
82111
|
+
latestReply: context.latestReply,
|
|
82112
|
+
nextReply: context.firstHiddenReply,
|
|
82113
|
+
totalReplyCount: context.totalReplyCount
|
|
82114
|
+
}) : null;
|
|
82115
|
+
}
|
|
82116
|
+
return summary;
|
|
82117
|
+
});
|
|
82118
|
+
},
|
|
82119
|
+
async listPosts(rootId, query, page) {
|
|
82120
|
+
return posts.listThreadPostsPage(rootId, { status: query.audience === "reader" ? "published" : query.status ?? "published" }, page);
|
|
82121
|
+
}
|
|
82122
|
+
};
|
|
82123
|
+
return service;
|
|
82124
|
+
}
|
|
82125
|
+
//#endregion
|
|
81195
82126
|
//#region src/services/navigation.ts
|
|
81196
82127
|
/**
|
|
81197
82128
|
* Nav Item Service (v2)
|
|
@@ -83313,6 +84244,10 @@ function createTelegramService(db, siteId, databaseSchema = sqliteSchemaBundle)
|
|
|
83313
84244
|
site,
|
|
83314
84245
|
paths,
|
|
83315
84246
|
posts,
|
|
84247
|
+
threads: createThreadService({
|
|
84248
|
+
posts,
|
|
84249
|
+
collections
|
|
84250
|
+
}),
|
|
83316
84251
|
customUrls: createCustomUrlService(db, siteId, paths, databaseSchema),
|
|
83317
84252
|
media,
|
|
83318
84253
|
uploads: createUploadSessionService(db, siteId, media, databaseSchema),
|
|
@@ -84113,9 +85048,11 @@ async function servePublicStorage(c) {
|
|
|
84113
85048
|
app.use("*", requireRssFeedsEnabled());
|
|
84114
85049
|
app.route("/", siteSkillRoutes);
|
|
84115
85050
|
app.route("/api/public/posts", publicPostsApiRoutes);
|
|
85051
|
+
app.route("/api/public/threads", publicThreadsApiRoutes);
|
|
84116
85052
|
app.route("/api/public/archive", publicArchiveApiRoutes);
|
|
84117
85053
|
app.route("/api/discover", discoverApiRoutes);
|
|
84118
85054
|
app.route("/api/posts", postsApiRoutes);
|
|
85055
|
+
app.route("/api/threads", threadsApiRoutes);
|
|
84119
85056
|
app.route("/api/nav-items", navItemsApiRoutes);
|
|
84120
85057
|
app.route("/api/collections", collectionsApiRoutes);
|
|
84121
85058
|
app.route("/api/smart-collections", smartCollectionsApiRoutes);
|