@jant/core 0.9.0 → 0.9.1

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.
@@ -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.9.0-f5f1d977f9cb3f8e";
5348
- var CLIENT_JS_FILE = "/_assets/client-S8oryJ0m.js";
5349
- var CLIENT_AUTH_JS_FILE = "/_assets/client-auth-Ds9G0IgR.js";
5347
+ */ var CORE_VERSION = "0.9.1-d7610f6379632ea6";
5348
+ var CLIENT_JS_FILE = "/_assets/client-nByuF0Ct.js";
5349
+ var CLIENT_AUTH_JS_FILE = "/_assets/client-auth-CeGBe0qG.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.9.0-f5f1d977f9cb3f8e";
5946
+ const faviconAssetVersion = resolvedFaviconVersion || "0.9.1-d7610f6379632ea6";
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) : "";
@@ -10273,6 +10273,36 @@ var DISCOVER_SETTINGS = [
10273
10273
  * directory never builds the address itself.
10274
10274
  */ var DISCOVER_STATUS_PATH = "/api/discover/posts";
10275
10275
  /**
10276
+ * Languages the jant.me directory lists, as primary language subtags.
10277
+ *
10278
+ * The directory's rule — its `accepted_languages` — stated here for the same
10279
+ * reason as `DISCOVER_MIN_PUBLIC_POSTS`, and read by setup alone: the Discover
10280
+ * question is asked there only when the answer can lead somewhere. An author
10281
+ * writing in a language the directory does not list would be handed a promise
10282
+ * nobody keeps, ticked in advance on hosted Jant.
10283
+ *
10284
+ * Nothing else reads it. The settings checkbox records consent rather than
10285
+ * applying for a listing, and a site can take on a listed language later
10286
+ * through multilingual content, so it stays for everyone.
10287
+ *
10288
+ * Simplified and Traditional Chinese are one list there, which is why the
10289
+ * match is on the primary subtag rather than on the script.
10290
+ */ var DISCOVER_LANGUAGES = ["zh"];
10291
+ /**
10292
+ * Whether the jant.me directory lists posts written in a language.
10293
+ *
10294
+ * @param tag - A BCP 47 language tag, as the content language is stored
10295
+ * @returns True when the tag's primary subtag is in `DISCOVER_LANGUAGES`
10296
+ * @example
10297
+ * ```ts
10298
+ * isDiscoverLanguage("zh-Hant"); // true
10299
+ * isDiscoverLanguage("en"); // false
10300
+ * ```
10301
+ */ function isDiscoverLanguage(tag) {
10302
+ const primary = tag.split("-")[0]?.toLowerCase() ?? "";
10303
+ return DISCOVER_LANGUAGES.includes(primary);
10304
+ }
10305
+ /**
10276
10306
  * The directory's names for its two format lists.
10277
10307
  *
10278
10308
  * Proper names that stay in English in every locale, as the directory's own
@@ -10654,6 +10684,12 @@ var DISCOVER_SETTINGS = [
10654
10684
  })] });
10655
10685
  };
10656
10686
  /**
10687
+ * `isDiscoverLanguage` as a Datastar expression over the language signal, so
10688
+ * the Discover question follows the picker without a round trip. The list is
10689
+ * the same constant the server reads, and a test holds the two readings of it
10690
+ * together.
10691
+ */ var DISCOVER_LANGUAGE_EXPRESSION = `${JSON.stringify(DISCOVER_LANGUAGES)}.includes($contentLanguage.split('-')[0].toLowerCase())`;
10692
+ /**
10657
10693
  * The one question setup asks about the world outside this site.
10658
10694
  *
10659
10695
  * It earns a place on a screen that asks as little as it can because the
@@ -10662,6 +10698,11 @@ var DISCOVER_SETTINGS = [
10662
10698
  * settings page's own: one control appearing twice should not describe itself
10663
10699
  * two ways.
10664
10700
  *
10701
+ * Only on screen while the chosen language is one the directory lists. For any
10702
+ * other, learning the directory exists leads nowhere, and on hosted Jant the box
10703
+ * would arrive ticked — a promise nobody keeps. It follows the language picker
10704
+ * above it, since both are answered on the same screen.
10705
+ *
10665
10706
  * The words come from the same `getDiscoverCopy` the settings page uses,
10666
10707
  * which is what keeps the two surfaces from drifting when either is edited.
10667
10708
  * The label is the settings page's; the help line is the settings page's
@@ -10670,10 +10711,12 @@ var DISCOVER_SETTINGS = [
10670
10711
  * first one — the directory's name links to the directory for anyone who wants
10671
10712
  * more. Where to find the setting again is left to the screen's footnote, which
10672
10713
  * says it once for every answer on it.
10673
- */ var DiscoverField = ({ copy, pages }) => {
10714
+ */ var DiscoverField = ({ copy, pages, shown }) => {
10674
10715
  const runs = discoverIntroRuns(copy.about, copy, pages);
10675
10716
  return /*#__PURE__*/ jsxDEV$1("div", {
10676
10717
  class: "field mt-2",
10718
+ "data-show": DISCOVER_LANGUAGE_EXPRESSION,
10719
+ style: shown ? void 0 : "display:none",
10677
10720
  children: [/*#__PURE__*/ jsxDEV$1("label", {
10678
10721
  class: "flex items-center gap-2 cursor-pointer",
10679
10722
  for: "setup-discover",
@@ -10831,7 +10874,8 @@ var SetupContent = (props) => {
10831
10874
  const emptyLabel = i18n._({ id: "Ox3+3h" });
10832
10875
  const discoverField = discoverAvailable ? /*#__PURE__*/ jsxDEV$1(DiscoverField, {
10833
10876
  copy: getDiscoverCopy(i18n),
10834
- pages: discoverPages
10877
+ pages: discoverPages,
10878
+ shown: isDiscoverLanguage(contentLanguage)
10835
10879
  }) : null;
10836
10880
  const signals = [
10837
10881
  askSiteName ? "siteName: ''" : null,
@@ -10912,6 +10956,12 @@ var SetupContent = (props) => {
10912
10956
  * is the whole point of asking. An absent field is not a refusal — an older
10913
10957
  * client or a scripted setup sends none — and leaves the default in force.
10914
10958
  *
10959
+ * Neither is a value sent with a language the directory does not list. The
10960
+ * question was not on screen for it, but the signal behind the hidden box still
10961
+ * went out holding its starting state, and storing that would record an answer
10962
+ * to a question nobody was asked. It is dropped, and the default stays in
10963
+ * force — the same as sending nothing.
10964
+ *
10915
10965
  * A yes is announced immediately, on the same terms as the settings page's own
10916
10966
  * switch. A directory decides eligibility for itself and re-reads the feed on
10917
10967
  * its own schedule, so a site with nothing published yet loses nothing by
@@ -10926,8 +10976,10 @@ var SetupContent = (props) => {
10926
10976
  * page's status block reads it back with a Retry beside it.
10927
10977
  *
10928
10978
  * @param c - The setup request, for its services and its config
10929
- * @param answer - The checkbox, or undefined when the form carried no field
10930
- */ async function storeDiscoverAnswer(c, answer) {
10979
+ * @param answers - The validated answers: the checkbox, or undefined when the
10980
+ * form carried no field, and the language it was answered for
10981
+ */ async function storeDiscoverAnswer(c, answers) {
10982
+ const answer = isDiscoverLanguage(answers.contentLanguage) ? answers.discover : void 0;
10931
10983
  if (answer === void 0) return;
10932
10984
  const stored = answer ? "latest" : "off";
10933
10985
  const { shouldAnnounce } = await c.var.services.settings.updateDiscoverSetting(stored, { demoMode: c.var.appConfig.demoMode });
@@ -11110,7 +11162,7 @@ setupRoutes.get("/setup", async (c) => {
11110
11162
  headers: c.req.raw.headers
11111
11163
  });
11112
11164
  } : null });
11113
- await storeDiscoverAnswer(c, answers.discover);
11165
+ await storeDiscoverAnswer(c, answers);
11114
11166
  return dsRedirect(toPublicPath("/", c.var.appConfig.sitePathPrefix));
11115
11167
  }
11116
11168
  setupRoutes.post("/setup", async (c) => {
@@ -27697,6 +27749,7 @@ var SearchPage = ({ query, results, error, hasMore, page, basePath = "", isAuthe
27697
27749
  limit: pageSize + 1,
27698
27750
  offset: (page - 1) * pageSize,
27699
27751
  status: ["published"],
27752
+ includePrivate: c.var.isAuthenticated,
27700
27753
  lang: getViewLang(c) ?? void 0
27701
27754
  });
27702
27755
  hasMore = results.length > pageSize;
@@ -38598,7 +38651,30 @@ function toSearchApiResult(post, snippet, sitePathPrefix) {
38598
38651
  //#region src/routes/api/search.ts
38599
38652
  /**
38600
38653
  * Search API Routes
38601
- */ var searchApiRoutes = new Hono();
38654
+ */ var DEFAULT_SEARCH_LIMIT = 20;
38655
+ var MAX_SEARCH_LIMIT = 50;
38656
+ /**
38657
+ * Read `limit` from the query string, clamped to 1–50.
38658
+ *
38659
+ * Clamped rather than rejected: the endpoint has always capped a large value
38660
+ * at 50, and a small one gets the same treatment. Anything that isn't a number
38661
+ * falls back to the default.
38662
+ *
38663
+ * @param value - Raw `limit` query parameter
38664
+ * @returns A page size between 1 and 50
38665
+ *
38666
+ * @example
38667
+ * ```ts
38668
+ * parseSearchLimit(undefined); // 20
38669
+ * parseSearchLimit("-1"); // 1
38670
+ * parseSearchLimit("500"); // 50
38671
+ * ```
38672
+ */ function parseSearchLimit(value) {
38673
+ const parsed = value === void 0 ? NaN : Number.parseInt(value, 10);
38674
+ if (Number.isNaN(parsed)) return DEFAULT_SEARCH_LIMIT;
38675
+ return Math.min(Math.max(parsed, 1), MAX_SEARCH_LIMIT);
38676
+ }
38677
+ var searchApiRoutes = new Hono();
38602
38678
  searchApiRoutes.use("*", requirePublicApiAccess());
38603
38679
  searchApiRoutes.use("*", async (c, next) => rateLimit({
38604
38680
  name: "search",
@@ -38609,12 +38685,12 @@ searchApiRoutes.get("/", async (c) => {
38609
38685
  const query = c.req.query("q");
38610
38686
  if (!query || query.trim().length === 0) throw new ValidationError("Query parameter 'q' is required");
38611
38687
  if (query.length > 200) throw new ValidationError("Query too long");
38612
- const limitParam = c.req.query("limit");
38613
- const limit = limitParam ? Math.min(parseInt(limitParam, 10) || 20, 50) : 20;
38688
+ const limit = parseSearchLimit(c.req.query("limit"));
38614
38689
  try {
38615
38690
  const results = await c.var.services.search.search(query, {
38616
38691
  limit,
38617
- status: ["published"]
38692
+ status: ["published"],
38693
+ includePrivate: false
38618
38694
  });
38619
38695
  return c.json({
38620
38696
  query,
@@ -39480,7 +39556,7 @@ var mcpTools = [
39480
39556
  },
39481
39557
  {
39482
39558
  name: "jant_search_posts",
39483
- description: "Search published posts.",
39559
+ description: "Search published posts, including private ones. Each result carries its visibility.",
39484
39560
  inputSchema: {
39485
39561
  type: "object",
39486
39562
  properties: {
@@ -39503,12 +39579,16 @@ var mcpTools = [
39503
39579
  const input = SearchPostsToolSchema.parse(args ?? {});
39504
39580
  const results = await context.services.search.search(input.query, {
39505
39581
  limit: input.limit,
39506
- status: ["published"]
39582
+ status: ["published"],
39583
+ includePrivate: true
39507
39584
  });
39508
39585
  return {
39509
39586
  count: results.length,
39510
39587
  query: input.query,
39511
- results: results.map((result) => toSearchApiResult(result.post, result.snippet, context.appConfig.sitePathPrefix))
39588
+ results: results.map((result) => ({
39589
+ ...toSearchApiResult(result.post, result.snippet, context.appConfig.sitePathPrefix),
39590
+ visibility: result.post.visibility
39591
+ }))
39512
39592
  };
39513
39593
  }
39514
39594
  }
@@ -78550,7 +78630,7 @@ manifestRoutes.get("/manifest.webmanifest", (c) => {
78550
78630
  });
78551
78631
  //#endregion
78552
78632
  //#region ../../docs/skill.md?raw
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";
78633
+ 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 public posts | `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";
78554
78634
  //#endregion
78555
78635
  //#region src/lib/site-skill.ts
78556
78636
  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.";
@@ -78579,7 +78659,7 @@ function replaceLiteral(content, search, replacement) {
78579
78659
  const normalizedSiteUrl = normalizeSiteUrl(siteUrl);
78580
78660
  if (!normalizedSiteUrl) throw new Error("A public site URL is required to render /skill.md");
78581
78661
  const targetSiteUrl = normalizedSiteUrl.replace(/\/$/, "");
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");
78662
+ 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 public posts | `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");
78583
78663
  const missingMarker = GENERIC_SITE_MARKERS.find((marker) => !skill_default.includes(marker));
78584
78664
  if (missingMarker) throw new Error(`The site skill template target marker could not be found: ${missingMarker}`);
78585
78665
  let content = skill_default;
@@ -81772,6 +81852,47 @@ function buildPgPrefixTsQuery(query) {
81772
81852
  if (terms.length === 0) return null;
81773
81853
  return terms.map((term) => `${term}:*`).join(" & ");
81774
81854
  }
81855
+ /**
81856
+ * A post's visibility after Thread-root inheritance, in the raw-SQL form every
81857
+ * search statement shares. Each one joins the root as `root_post`. This is the
81858
+ * same rule as `buildEffectiveVisibilityExpr` in `db/post-visibility.ts`.
81859
+ */ var EFFECTIVE_VISIBILITY_SQL = "COALESCE(post.visibility, root_post.visibility)";
81860
+ /**
81861
+ * The conditions every search statement applies after its own match clause:
81862
+ * site, status, audience, format, and language.
81863
+ *
81864
+ * Built once so that no statement can leave one out. Each dialect and each
81865
+ * match strategy has its own SQL, and a statement missing the visibility
81866
+ * clause does not fail — it returns private posts.
81867
+ *
81868
+ * @param siteId - Site the search is scoped to
81869
+ * @param options - Caller's search options
81870
+ * @returns `AND …` lines to follow the match clause, and their bound values in order
81871
+ *
81872
+ * @example
81873
+ * ```ts
81874
+ * const filters = buildSearchFilters(siteId, { status: ["published"] });
81875
+ * // filters.sql: "AND post.site_id = ?\nAND post.status IN (?)\nAND COALESCE(…) != 'private'"
81876
+ * // filters.params: [siteId, "published"]
81877
+ * ```
81878
+ */ function buildSearchFilters(siteId, options) {
81879
+ const status = options.status ?? ["published"];
81880
+ const conditions = ["post.site_id = ?", `post.status IN (${status.map(() => "?").join(", ")})`];
81881
+ const params = [siteId, ...status];
81882
+ if (!options.includePrivate) conditions.push(`${EFFECTIVE_VISIBILITY_SQL} != 'private'`);
81883
+ if (options.format) {
81884
+ conditions.push("post.format = ?");
81885
+ params.push(options.format);
81886
+ }
81887
+ if (options.lang) {
81888
+ conditions.push("post.language = ?");
81889
+ params.push(options.lang);
81890
+ }
81891
+ return {
81892
+ sql: conditions.map((condition) => `AND ${condition}`).join("\n"),
81893
+ params
81894
+ };
81895
+ }
81775
81896
  var PG_TS_HEADLINE_OPTIONS = [
81776
81897
  "MaxWords=18",
81777
81898
  "MinWords=6",
@@ -81785,19 +81906,14 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
81785
81906
  async function searchFts(query, options) {
81786
81907
  const limit = options.limit ?? 20;
81787
81908
  const offset = options.offset ?? 0;
81788
- const status = options.status ?? ["published"];
81789
- const statusPlaceholders = status.map(() => "?").join(", ");
81790
- const formatFilter = options.format ? "AND post.format = ?" : "";
81791
- const formatParams = options.format ? [options.format] : [];
81792
- const langFilter = options.lang ? "AND post.language = ?" : "";
81793
- const langParams = options.lang ? [options.lang] : [];
81909
+ const filters = buildSearchFilters(siteId, options);
81794
81910
  if (databaseDialect === "sqlite") {
81795
81911
  const ftsQuery = buildSqliteFtsQuery(query);
81796
81912
  if (!ftsQuery) return [];
81797
81913
  const { results } = await rawQuery.prepare(`
81798
81914
  SELECT
81799
81915
  post.*,
81800
- COALESCE(post.visibility, root_post.visibility) AS effective_visibility,
81916
+ ${EFFECTIVE_VISIBILITY_SQL} AS effective_visibility,
81801
81917
  path_registry.path AS slug,
81802
81918
  post_fts.rank AS rank,
81803
81919
  snippet(post_fts, 1, char(2), char(3), '...', 32) AS snippet
@@ -81809,13 +81925,10 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
81809
81925
  AND path_registry.site_id = post.site_id
81810
81926
  AND path_registry.kind = 'slug'
81811
81927
  WHERE post_fts MATCH ?
81812
- AND post.site_id = ?
81813
- AND post.status IN (${statusPlaceholders})
81814
- ${formatFilter}
81815
- ${langFilter}
81928
+ ${filters.sql}
81816
81929
  ORDER BY post_fts.rank
81817
81930
  LIMIT ? OFFSET ?
81818
- `).bind(ftsQuery, siteId, ...status, ...formatParams, ...langParams, limit, offset).all();
81931
+ `).bind(ftsQuery, ...filters.params, limit, offset).all();
81819
81932
  return withSnippetFallback((results || []).map(mapRow), query);
81820
81933
  }
81821
81934
  if (databaseDialect !== "pg") return [];
@@ -81827,7 +81940,7 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
81827
81940
  )
81828
81941
  SELECT
81829
81942
  post.*,
81830
- COALESCE(post.visibility, root_post.visibility) AS effective_visibility,
81943
+ ${EFFECTIVE_VISIBILITY_SQL} AS effective_visibility,
81831
81944
  path_registry.path AS slug,
81832
81945
  ts_rank_cd(post.search_document, search_query.tsq, 32) AS rank,
81833
81946
  NULLIF(
@@ -81874,30 +81987,22 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
81874
81987
  AND path_registry.site_id = post.site_id
81875
81988
  AND path_registry.kind = 'slug'
81876
81989
  WHERE post.search_document @@ search_query.tsq
81877
- AND post.site_id = ?
81878
- AND post.status IN (${statusPlaceholders})
81879
- ${formatFilter}
81880
- ${langFilter}
81990
+ ${filters.sql}
81881
81991
  ORDER BY rank DESC, post.published_at DESC NULLS LAST, post.id DESC
81882
81992
  LIMIT ? OFFSET ?
81883
- `).bind(tsQuery, siteId, ...status, ...formatParams, ...langParams, limit, offset).all();
81993
+ `).bind(tsQuery, ...filters.params, limit, offset).all();
81884
81994
  return withSnippetFallback((results || []).map(mapRow), query);
81885
81995
  }
81886
81996
  async function searchLike(query, options) {
81887
81997
  const limit = options.limit ?? 20;
81888
81998
  const offset = options.offset ?? 0;
81889
- const status = options.status ?? ["published"];
81890
81999
  const like = `%${query}%`;
81891
- const statusPlaceholders = status.map(() => "?").join(", ");
81892
- const formatFilter = options.format ? "AND post.format = ?" : "";
81893
- const formatParams = options.format ? [options.format] : [];
81894
- const langFilter = options.lang ? "AND post.language = ?" : "";
81895
- const langParams = options.lang ? [options.lang] : [];
82000
+ const filters = buildSearchFilters(siteId, options);
81896
82001
  if (databaseDialect === "pg") {
81897
82002
  const { results } = await rawQuery.prepare(`
81898
82003
  SELECT
81899
82004
  post.*,
81900
- COALESCE(post.visibility, root_post.visibility) AS effective_visibility,
82005
+ ${EFFECTIVE_VISIBILITY_SQL} AS effective_visibility,
81901
82006
  path_registry.path AS slug,
81902
82007
  GREATEST(
81903
82008
  similarity(coalesce(post.title, ''), ?),
@@ -81913,20 +82018,17 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
81913
82018
  AND path_registry.site_id = post.site_id
81914
82019
  AND path_registry.kind = 'slug'
81915
82020
  WHERE post.search_text ILIKE ?
81916
- AND post.site_id = ?
81917
- AND post.status IN (${statusPlaceholders})
81918
- ${formatFilter}
81919
- ${langFilter}
82021
+ ${filters.sql}
81920
82022
  ORDER BY rank DESC, post.published_at DESC NULLS LAST, post.id DESC
81921
82023
  LIMIT ? OFFSET ?
81922
- `).bind(query, query, query, query, like, siteId, ...status, ...formatParams, ...langParams, limit, offset).all();
82024
+ `).bind(query, query, query, query, like, ...filters.params, limit, offset).all();
81923
82025
  return withSnippetFallback((results || []).map(mapRow), query);
81924
82026
  }
81925
82027
  const likeOperator = "LIKE";
81926
82028
  const { results } = await rawQuery.prepare(`
81927
82029
  SELECT
81928
82030
  post.*,
81929
- COALESCE(post.visibility, root_post.visibility) AS effective_visibility,
82031
+ ${EFFECTIVE_VISIBILITY_SQL} AS effective_visibility,
81930
82032
  path_registry.path AS slug,
81931
82033
  0 AS rank,
81932
82034
  NULL AS snippet
@@ -81942,13 +82044,10 @@ function createSearchService(rawQuery, siteId, databaseDialect = "sqlite") {
81942
82044
  post.quote_text ${likeOperator} ? OR
81943
82045
  post.url ${likeOperator} ?
81944
82046
  )
81945
- AND post.site_id = ?
81946
- AND post.status IN (${statusPlaceholders})
81947
- ${formatFilter}
81948
- ${langFilter}
82047
+ ${filters.sql}
81949
82048
  ORDER BY post.published_at DESC
81950
82049
  LIMIT ? OFFSET ?
81951
- `).bind(like, like, like, like, siteId, ...status, ...formatParams, ...langParams, limit, offset).all();
82050
+ `).bind(like, like, like, like, ...filters.params, limit, offset).all();
81952
82051
  return withSnippetFallback((results || []).map(mapRow), query);
81953
82052
  }
81954
82053
  return { async search(query, options = {}) {
@@ -239,7 +239,7 @@
239
239
  ]
240
240
  },
241
241
  "src/client-auth.ts": {
242
- "file": "_assets/client-auth-Ds9G0IgR.js",
242
+ "file": "_assets/client-auth-CeGBe0qG.js",
243
243
  "name": "client-auth",
244
244
  "src": "src/client-auth.ts",
245
245
  "isEntry": true,
@@ -306,7 +306,7 @@
306
306
  ]
307
307
  },
308
308
  "src/client.ts": {
309
- "file": "_assets/client-S8oryJ0m.js",
309
+ "file": "_assets/client-nByuF0Ct.js",
310
310
  "name": "client",
311
311
  "src": "src/client.ts",
312
312
  "isEntry": true,
@@ -1,4 +1,4 @@
1
- import{T as e,g as t,h as n,i as r,m as i,n as a,t as o,u as s,x as ee,y as te}from"./chunks/lit-DW8VmJAT.js";import"./client-S8oryJ0m.js";import{n as c,t as ne}from"./chunks/confirm-D7GrwsCN.js";import{_ as l,a as re,d as u,f as d,g as f,h as p,i as ie,l as m,m as ae,n as oe,p as se,r as ce,t as h,u as g,v as _,y as le}from"./chunks/unsafe-svg-BkscJx69.js";import{r as v}from"./chunks/slug-format-CRXO1AL5.js";import{h as y,l as ue,u as b}from"./chunks/types-D5iF3H1a.js";import{t as de}from"./chunks/settings-paths-BcdySNx6.js";var x=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,fe=`M4 4 20 20`,pe=200,me=class extends o{static properties={_open:{state:!0},_query:{state:!0},_items:{state:!0},_note:{state:!0},_loading:{state:!0},_searched:{state:!0}};#e=null;#t=null;#n=0;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._query=``,this._items=[],this._note=``,this._loading=!1,this._searched=!1}disconnectedCallback(){super.disconnectedCallback();let e=this.#e;this.#e=null,e?.resolve(null)}pick(e){return this.#e?.resolve(null),this._query=``,this._items=[],this._note=``,this._loading=!1,this._searched=!1,this._open=!0,new Promise(t=>{this.#e={...e,resolve:t},this.updateComplete.then(()=>{let e=this.querySelector(`.picker-dialog`);e&&!e.open&&e.showModal(),this.querySelector(`.picker-dialog-input`)?.focus()})})}#r(e){this.#t&&clearTimeout(this.#t),this.#t=null,this.#n+=1;let t=this.querySelector(`.picker-dialog`);t?.open&&t.close();let n=this.#e;this.#e=null,this._open=!1,n?.resolve(e)}#i(e){let t=this.#e;if(!t)return;let n=e.target.value;this._query=n,this.#t&&clearTimeout(this.#t);let r=t.minQueryLength??2;if(n.trim().length<r){this.#n+=1,this._items=[],this._note=``,this._loading=!1,this._searched=!1;return}this._loading=!0,this.#t=setTimeout(()=>{this.#a(n,t)},pe)}async#a(e,t){let n=++this.#n;try{let r=await t.search(e);if(n!==this.#n)return;this._items=r.items,this._note=r.note??``}catch{if(n!==this.#n)return;this._items=[],this._note=``}finally{n===this.#n&&(this._loading=!1,this._searched=!0)}}#o(e){if(e.key===`Escape`){e.preventDefault(),this.#r(null);return}if(e.key!==`ArrowDown`&&e.key!==`ArrowUp`)return;let t=Array.from(this.querySelectorAll(`.picker-dialog-option`));if(t.length===0)return;e.preventDefault();let n=document.activeElement,r=t.findIndex(e=>e===n),i=e.key===`ArrowDown`?r<0?0:Math.min(r+1,t.length-1):r<=0?-1:r-1;if(i<0){this.querySelector(`.picker-dialog-input`)?.focus();return}t[i]?.focus()}#s(e){e.target===e.currentTarget&&this.#r(null)}render(){let e=this.#e;if(!this._open||!e)return a;let t=e.minQueryLength??2,n=this._query.trim().length<t;return r`
1
+ import{T as e,g as t,h as n,i as r,m as i,n as a,t as o,u as s,x as ee,y as te}from"./chunks/lit-DW8VmJAT.js";import"./client-nByuF0Ct.js";import{n as c,t as ne}from"./chunks/confirm-D7GrwsCN.js";import{_ as l,a as re,d as u,f as d,g as f,h as p,i as ie,l as m,m as ae,n as oe,p as se,r as ce,t as h,u as g,v as _,y as le}from"./chunks/unsafe-svg-BkscJx69.js";import{r as v}from"./chunks/slug-format-CRXO1AL5.js";import{h as y,l as ue,u as b}from"./chunks/types-D5iF3H1a.js";import{t as de}from"./chunks/settings-paths-BcdySNx6.js";var x=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,fe=`M4 4 20 20`,pe=200,me=class extends o{static properties={_open:{state:!0},_query:{state:!0},_items:{state:!0},_note:{state:!0},_loading:{state:!0},_searched:{state:!0}};#e=null;#t=null;#n=0;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._query=``,this._items=[],this._note=``,this._loading=!1,this._searched=!1}disconnectedCallback(){super.disconnectedCallback();let e=this.#e;this.#e=null,e?.resolve(null)}pick(e){return this.#e?.resolve(null),this._query=``,this._items=[],this._note=``,this._loading=!1,this._searched=!1,this._open=!0,new Promise(t=>{this.#e={...e,resolve:t},this.updateComplete.then(()=>{let e=this.querySelector(`.picker-dialog`);e&&!e.open&&e.showModal(),this.querySelector(`.picker-dialog-input`)?.focus()})})}#r(e){this.#t&&clearTimeout(this.#t),this.#t=null,this.#n+=1;let t=this.querySelector(`.picker-dialog`);t?.open&&t.close();let n=this.#e;this.#e=null,this._open=!1,n?.resolve(e)}#i(e){let t=this.#e;if(!t)return;let n=e.target.value;this._query=n,this.#t&&clearTimeout(this.#t);let r=t.minQueryLength??2;if(n.trim().length<r){this.#n+=1,this._items=[],this._note=``,this._loading=!1,this._searched=!1;return}this._loading=!0,this.#t=setTimeout(()=>{this.#a(n,t)},pe)}async#a(e,t){let n=++this.#n;try{let r=await t.search(e);if(n!==this.#n)return;this._items=r.items,this._note=r.note??``}catch{if(n!==this.#n)return;this._items=[],this._note=``}finally{n===this.#n&&(this._loading=!1,this._searched=!0)}}#o(e){if(e.key===`Escape`){e.preventDefault(),this.#r(null);return}if(e.key!==`ArrowDown`&&e.key!==`ArrowUp`)return;let t=Array.from(this.querySelectorAll(`.picker-dialog-option`));if(t.length===0)return;e.preventDefault();let n=document.activeElement,r=t.findIndex(e=>e===n),i=e.key===`ArrowDown`?r<0?0:Math.min(r+1,t.length-1):r<=0?-1:r-1;if(i<0){this.querySelector(`.picker-dialog-input`)?.focus();return}t[i]?.focus()}#s(e){e.target===e.currentTarget&&this.#r(null)}render(){let e=this.#e;if(!this._open||!e)return a;let t=e.minQueryLength??2,n=this._query.trim().length<t;return r`
2
2
  <dialog
3
3
  class="dialog picker-dialog"
4
4
  @cancel=${e=>{e.preventDefault(),this.#r(null)}}