@blogmcp/sdk 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,4 @@
1
- import { __require as r } from "../node_modules/semver/index.js";
2
- r();
1
+ var r = {};
2
+ export {
3
+ r as __exports
4
+ };
@@ -1,4 +1,2 @@
1
- var r = {};
2
- export {
3
- r as __exports
4
- };
1
+ import { __require as r } from "../node_modules/semver/index.js";
2
+ r();
@@ -33,6 +33,13 @@ export interface KbClientConfig {
33
33
  tokenStorage?: TokenStorage;
34
34
  /** Whether currently running on server (for endpoint selection). Defaults to false. */
35
35
  isServer?: boolean;
36
+ /**
37
+ * Extra headers sent with every request (e.g. `X-Blogmcp-Client-Ip` from a
38
+ * trusted server proxy). The protocol-critical pair is protected:
39
+ * `Content-Type` and `Authorization` (from tokenStorage) always win over
40
+ * anything in this bag.
41
+ */
42
+ headers?: Record<string, string>;
36
43
  }
37
44
  /** Generates HTML for images in markdown content. Pluggable for IPX, Cloudinary, etc. */
38
45
  export type ImageHtmlRenderer = (href: string, alt: string, title?: string | null) => string;
@@ -6,7 +6,7 @@
6
6
  * const data = await client.articles.list({ status: 'published', limit: 10 })
7
7
  */
8
8
  import type { KbClientConfig } from './client-types';
9
- import type { Article, ArticleWithTranslation, Tag, LocalizedTag, Language, SearchResult, KBContextChunk, Translation, Comment, CommentsConnection, CommentResult, AuthResult, RegisterResult, UpdateProfileResult, ReportSettings, UpdateReportSettingsInput } from './types';
9
+ import type { Article, ArticleWithTranslation, ArticleVersionContent, Tag, LocalizedTag, Language, SearchResult, KBContextChunk, Translation, Comment, CommentsConnection, CommentResult, AuthResult, RegisterResult, UpdateProfileResult, ReportSettings, UpdateReportSettingsInput } from './types';
10
10
  import type { NavNode } from './navigation';
11
11
  export interface KbClient {
12
12
  articles: {
@@ -44,6 +44,20 @@ export interface KbClient {
44
44
  resolveAlias(filename: string): Promise<{
45
45
  articleAliasTarget: string | null;
46
46
  }>;
47
+ /**
48
+ * Fetch ONE article version's content by its STABLE version id, for headless
49
+ * preview / A/B (test-before-publish, multi-variant serving). Bypasses publish
50
+ * status, so the server returns it only to an INTERNAL caller (server client
51
+ * holding the api token) OR a caller passing a valid `previewKey` minted for
52
+ * this exact versionId. Returns `{ articleVersion: null }` when missing or
53
+ * unauthorized. Versions are per-language; the returned `languageCode` is the
54
+ * version's own translation — no language argument is taken.
55
+ */
56
+ getVersion(versionId: string, opts?: {
57
+ previewKey?: string;
58
+ }): Promise<{
59
+ articleVersion: ArticleVersionContent | null;
60
+ }>;
47
61
  };
48
62
  search: {
49
63
  query(params: {
@@ -1,6 +1,6 @@
1
- import { UPDATE_MY_PROFILE as A, UPDATE_MY_REPORT_SETTINGS as i, MY_REPORT_SETTINGS as S, CHANGE_PASSWORD as _, RESEND_VERIFICATION as I, RESET_PASSWORD as l, FORGOT_PASSWORD as R, VERIFY_EMAIL as c, REGISTER as d, LOGIN as N, DELETE_COMMENT as O, UPDATE_COMMENT as C, CREATE_COMMENT as L, GET_COMMENT as h, ARTICLE_COMMENTS as u, GET_TRANSLATION as p, ARTICLE_TRANSLATIONS as G, KB_NAVIGATION as g, KB_LANGUAGES as m, LOCALIZED_TAGS as M, ACCESSIBLE_TAGS as P, GET_KB_CONTEXT as D, SEARCH_KNOWLEDGE_BASE as f, ARTICLE_ALIAS_TARGET as y, ARTICLE_WITH_TRANSLATION_BY_ID as B, ARTICLE_WITH_TRANSLATION as W, ACCESSIBLE_ARTICLES as w } from "./queries.js";
2
- import { createMemoryTokenStorage as k } from "./auth.js";
3
- function v() {
1
+ import { UPDATE_MY_PROFILE as A, ARTICLE_VERSION as i, UPDATE_MY_REPORT_SETTINGS as S, MY_REPORT_SETTINGS as _, CHANGE_PASSWORD as I, RESEND_VERIFICATION as l, RESET_PASSWORD as R, FORGOT_PASSWORD as d, VERIFY_EMAIL as N, REGISTER as O, LOGIN as c, DELETE_COMMENT as C, UPDATE_COMMENT as L, CREATE_COMMENT as h, GET_COMMENT as u, ARTICLE_COMMENTS as p, GET_TRANSLATION as G, ARTICLE_TRANSLATIONS as g, KB_NAVIGATION as m, KB_LANGUAGES as M, LOCALIZED_TAGS as P, ACCESSIBLE_TAGS as y, GET_KB_CONTEXT as D, SEARCH_KNOWLEDGE_BASE as f, ARTICLE_ALIAS_TARGET as w, ARTICLE_WITH_TRANSLATION_BY_ID as B, ARTICLE_WITH_TRANSLATION as v, ACCESSIBLE_ARTICLES as W } from "./queries.js";
2
+ import { createMemoryTokenStorage as K } from "./auth.js";
3
+ function k() {
4
4
  return async (n, o) => (await fetch(n, {
5
5
  method: o.method,
6
6
  headers: o.headers,
@@ -9,6 +9,7 @@ function v() {
9
9
  }
10
10
  async function x(n, o, a) {
11
11
  const E = {
12
+ ...n.headers ?? {},
12
13
  "Content-Type": "application/json"
13
14
  }, s = n.tokenStorage.getToken();
14
15
  s && (E.Authorization = `Bearer ${s}`);
@@ -22,58 +23,59 @@ async function x(n, o, a) {
22
23
  return t.data;
23
24
  }
24
25
  function Y(n) {
25
- const o = n.fetcher || v(), a = n.tokenStorage || k(), s = { endpoint: n.isServer && n.serverEndpoint ? n.serverEndpoint : n.endpoint, fetcher: o, tokenStorage: a };
26
+ const o = n.fetcher || k(), a = n.tokenStorage || K(), s = { endpoint: n.isServer && n.serverEndpoint ? n.serverEndpoint : n.endpoint, fetcher: o, tokenStorage: a, headers: n.headers };
26
27
  function t(e, r) {
27
28
  return x(s, e, r);
28
29
  }
29
30
  return {
30
31
  articles: {
31
- list: (e) => t(w, e),
32
- getWithTranslation: (e, r) => t(W, { filename: e, languageCode: r }),
32
+ list: (e) => t(W, e),
33
+ getWithTranslation: (e, r) => t(v, { filename: e, languageCode: r }),
33
34
  getWithTranslationById: (e, r) => t(B, { id: e, languageCode: r }),
34
- resolveAlias: (e) => t(y, { filename: e })
35
+ resolveAlias: (e) => t(w, { filename: e }),
36
+ getVersion: (e, r) => t(i, { versionId: e, previewKey: r?.previewKey ?? null })
35
37
  },
36
38
  search: {
37
39
  query: (e) => t(f, e),
38
40
  getContext: (e, r) => t(D, { query: e, maxChunks: r })
39
41
  },
40
42
  tags: {
41
- list: () => t(P),
42
- listLocalized: (e) => t(M, { languageCode: e })
43
+ list: () => t(y),
44
+ listLocalized: (e) => t(P, { languageCode: e })
43
45
  },
44
46
  languages: {
45
- list: () => t(m)
47
+ list: () => t(M)
46
48
  },
47
49
  navigation: {
48
- get: (e) => t(g, e ?? {})
50
+ get: (e) => t(m, e ?? {})
49
51
  },
50
52
  translations: {
51
- list: (e) => t(G, { sourceFilename: e }),
52
- get: (e, r) => t(p, { sourceFilename: e, languageCode: r })
53
+ list: (e) => t(g, { sourceFilename: e }),
54
+ get: (e, r) => t(G, { sourceFilename: e, languageCode: r })
53
55
  },
54
56
  comments: {
55
- list: (e, r) => t(u, { articleId: e, languageCode: r }),
56
- get: (e, r) => t(h, { commentId: e, languageCode: r }),
57
- create: (e) => t(L, e),
58
- update: (e, r) => t(C, { commentId: e, content: r }),
59
- delete: (e) => t(O, { commentId: e })
57
+ list: (e, r) => t(p, { articleId: e, languageCode: r }),
58
+ get: (e, r) => t(u, { commentId: e, languageCode: r }),
59
+ create: (e) => t(h, e),
60
+ update: (e, r) => t(L, { commentId: e, content: r }),
61
+ delete: (e) => t(C, { commentId: e })
60
62
  },
61
63
  auth: {
62
- login: (e, r) => t(N, { email: e, password: r }),
63
- register: (e, r, T) => t(d, { email: e, password: r, name: T }),
64
- verifyEmail: (e) => t(c, { token: e }),
65
- forgotPassword: (e) => t(R, { email: e }),
66
- resetPassword: (e, r) => t(l, { token: e, password: r }),
67
- resendVerification: (e) => t(I, { email: e }),
68
- changePassword: (e, r) => t(_, { currentPassword: e, newPassword: r }),
64
+ login: (e, r) => t(c, { email: e, password: r }),
65
+ register: (e, r, T) => t(O, { email: e, password: r, name: T }),
66
+ verifyEmail: (e) => t(N, { token: e }),
67
+ forgotPassword: (e) => t(d, { email: e }),
68
+ resetPassword: (e, r) => t(R, { token: e, password: r }),
69
+ resendVerification: (e) => t(l, { email: e }),
70
+ changePassword: (e, r) => t(I, { currentPassword: e, newPassword: r }),
69
71
  updateProfile: (e) => t(A, {
70
72
  name: e.name ?? null,
71
73
  email: e.email ?? null
72
74
  })
73
75
  },
74
76
  reportSettings: {
75
- get: () => t(S),
76
- update: (e) => t(i, e)
77
+ get: () => t(_),
78
+ update: (e) => t(S, e)
77
79
  },
78
80
  executeGraphQL: t
79
81
  };
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Delegated identity for headless storefronts ("external login").
3
+ *
4
+ * A trusted storefront server that has ALREADY authenticated its own user
5
+ * (a Vendure customer, a Shopify account, any bring-your-own-login) exchanges
6
+ * its internal `kb_*` API key plus the user's email/name for a short-lived,
7
+ * user-scoped KB JWT via `POST {api}/auth/delegated-token`. Requests made with
8
+ * that token author comments and feedback as a real per-user KB identity —
9
+ * ownership, edit/delete-own, and quotas all apply per end user instead of
10
+ * collapsing onto the shared service key.
11
+ *
12
+ * The minted token is deliberately narrow: `accessLevel: 'public'` always and
13
+ * `scope: 'delegated'` (profile/password mutations are rejected server-side).
14
+ *
15
+ * SERVER-ONLY: `createDelegatedTokenMinter` throws when called in a browser
16
+ * context — the internal key must never ship in a client bundle. Keep usage
17
+ * inside server-only modules (e.g. React Router `*.server.ts`, Nuxt server
18
+ * routes).
19
+ */
20
+ export interface DelegatedTokenMinterConfig {
21
+ /**
22
+ * Full URL of the delegated-token endpoint, e.g.
23
+ * `${BLOGMCP_API_URL}/api/auth/delegated-token`.
24
+ */
25
+ endpoint: string;
26
+ /** Internal-access `kb_*` API key. Server-side secret. */
27
+ internalKey: string;
28
+ /**
29
+ * Refresh a cached token this many ms before its expiry. Default 5 minutes
30
+ * (clamped to a non-negative value).
31
+ */
32
+ ttlSkewMs?: number;
33
+ /** Custom fetch implementation (tests / non-global-fetch runtimes). */
34
+ fetchImpl?: typeof fetch;
35
+ }
36
+ export interface DelegatedMintInput {
37
+ /** End-user email as verified by the delegating storefront. */
38
+ email: string;
39
+ /** Display name shown as the comment author (e.g. "Jana N."). */
40
+ name?: string;
41
+ /**
42
+ * Stable caller-side user reference, e.g. `vendure:customer:42`. Stored for
43
+ * audit on the kb user row and used as the cache key (falls back to the
44
+ * normalized email when omitted).
45
+ */
46
+ externalRef?: string;
47
+ }
48
+ export interface DelegatedIdentity {
49
+ /** Short-lived user-scoped KB JWT — send as `Authorization: Bearer <token>`. */
50
+ token: string;
51
+ /** The kb user id the token acts as (matches `Comment.userId`). */
52
+ kbUserId: string;
53
+ email: string;
54
+ name: string | null;
55
+ /** True when this mint created the kb user row (first visit). */
56
+ created: boolean;
57
+ /** Epoch ms when the token expires. */
58
+ expiresAt: number;
59
+ }
60
+ /** Thrown on a non-2xx or malformed response from the delegated-token endpoint. */
61
+ export declare class DelegatedTokenError extends Error {
62
+ readonly status: number;
63
+ constructor(status: number, message: string);
64
+ }
65
+ export interface DelegatedTokenMinter {
66
+ /**
67
+ * Return a fresh identity for the given end user. Cached per
68
+ * `externalRef` (or normalized email) until close to expiry; concurrent
69
+ * mints for the same user share one request.
70
+ */
71
+ mint(input: DelegatedMintInput): Promise<DelegatedIdentity>;
72
+ /**
73
+ * Drop a cached identity — pass the cache key (the `externalRef`, or the
74
+ * normalized email when no ref was used) or nothing to clear all.
75
+ */
76
+ invalidate(key?: string): void;
77
+ }
78
+ export declare function createDelegatedTokenMinter(config: DelegatedTokenMinterConfig): DelegatedTokenMinter;
@@ -0,0 +1,79 @@
1
+ class m extends Error {
2
+ status;
3
+ constructor(l, d) {
4
+ super(d), this.name = "DelegatedTokenError", this.status = l;
5
+ }
6
+ }
7
+ const p = 300 * 1e3, k = 1024;
8
+ function u(n) {
9
+ return n.toLowerCase().trim();
10
+ }
11
+ function y(n) {
12
+ if (typeof window < "u" && typeof window.document < "u")
13
+ throw new Error(
14
+ "[blogmcp-sdk] createDelegatedTokenMinter is server-only — it holds an internal API key that must never reach the browser."
15
+ );
16
+ if (!n.endpoint) throw new Error("[blogmcp-sdk] delegated-token endpoint is required");
17
+ if (!n.internalKey) throw new Error("[blogmcp-sdk] internalKey is required");
18
+ const l = Math.max(0, n.ttlSkewMs ?? p), d = n.fetchImpl ?? globalThis.fetch, o = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map();
19
+ async function w(t) {
20
+ const r = await d(n.endpoint, {
21
+ method: "POST",
22
+ headers: {
23
+ "Content-Type": "application/json",
24
+ Authorization: `Bearer ${n.internalKey}`
25
+ },
26
+ body: JSON.stringify({
27
+ email: t.email,
28
+ name: t.name,
29
+ externalRef: t.externalRef
30
+ })
31
+ });
32
+ if (!r.ok) {
33
+ let s = `delegated-token request failed with status ${r.status}`;
34
+ try {
35
+ const a = await r.json();
36
+ a?.error && (s = a.error);
37
+ } catch {
38
+ }
39
+ throw new m(r.status, s);
40
+ }
41
+ const e = await r.json();
42
+ if (typeof e?.token != "string" || typeof e.expiresIn != "number" || typeof e.user?.id != "string")
43
+ throw new m(r.status, "delegated-token response is malformed");
44
+ return {
45
+ token: e.token,
46
+ kbUserId: e.user.id,
47
+ email: e.user.email ?? u(t.email),
48
+ name: e.user.name ?? null,
49
+ created: e.user.created === !0,
50
+ expiresAt: Date.now() + e.expiresIn * 1e3
51
+ };
52
+ }
53
+ return {
54
+ async mint(t) {
55
+ if (!t?.email) throw new Error("[blogmcp-sdk] mint() requires an email");
56
+ const r = t.externalRef ?? u(t.email), e = o.get(r);
57
+ if (e && e.expiresAt - Date.now() > l)
58
+ return e;
59
+ const s = c.get(r);
60
+ if (s) return s;
61
+ if (o.size >= k) {
62
+ const i = Date.now();
63
+ for (const [f, h] of o)
64
+ h.expiresAt <= i && o.delete(f);
65
+ }
66
+ const a = w(t).then((i) => (o.set(r, i), i)).finally(() => {
67
+ c.delete(r);
68
+ });
69
+ return c.set(r, a), a;
70
+ },
71
+ invalidate(t) {
72
+ t === void 0 ? o.clear() : o.delete(t);
73
+ }
74
+ };
75
+ }
76
+ export {
77
+ m as DelegatedTokenError,
78
+ y as createDelegatedTokenMinter
79
+ };
@@ -1,4 +1,4 @@
1
- export type { Article, ArticleWithTranslation, MediaGeo, ContentImageGeo, Tag, LocalizedTag, SearchResult, KBContextChunk, Translation, Language, AccessLevel, Comment, CommentSubscriptionEvent, CommentsConnection, CommentResult, AuthUser, AuthResult, RegisterResult, UpdateProfileResult, ReportSettings, ReportPolicyValue, EmailNotificationFrequency, FeedbackNotificationFrequency, UpdateReportSettingsInput, PaginatedResponse, } from './types';
1
+ export type { Article, ArticleWithTranslation, ArticleVersionContent, MediaGeo, ContentImageGeo, Tag, LocalizedTag, SearchResult, KBContextChunk, Translation, Language, AccessLevel, Comment, CommentSubscriptionEvent, CommentsConnection, CommentResult, AuthUser, AuthResult, RegisterResult, UpdateProfileResult, ReportSettings, ReportPolicyValue, EmailNotificationFrequency, FeedbackNotificationFrequency, UpdateReportSettingsInput, PaginatedResponse, } from './types';
2
2
  export { ACCESS_LEVEL_ORDER } from './types';
3
3
  export type { KbClientConfig, Fetcher, TokenStorage, ImageHtmlRenderer, SanitizeFn, } from './client-types';
4
4
  export type { KbClient } from './client';
@@ -7,6 +7,8 @@ export type { NavNode, NavNodeType, NavBadge, NavGroupLink, NavNextPrev, FlatNav
7
7
  export { navWalk, findNavNode, navBreadcrumbs, navSiblings, navSubtree, navNextPrev, isNavigable, flattenNav, } from './navigation';
8
8
  export type { AuthManager } from './auth';
9
9
  export { createAuthManager, createMemoryTokenStorage, createLocalStorageTokenStorage, decodeJwtUser, hasAccessLevel, } from './auth';
10
+ export { createDelegatedTokenMinter, DelegatedTokenError, } from './delegated-identity';
11
+ export type { DelegatedTokenMinter, DelegatedTokenMinterConfig, DelegatedMintInput, DelegatedIdentity, } from './delegated-identity';
10
12
  export { stripLeadingH1, generateDescription } from './article-seo';
11
13
  export { createMarkedInstance, defaultImageHtml, parseMarkdownSafe } from './markdown';
12
14
  export type { CreateMarkedOptions } from './markdown';
@@ -1,67 +1,70 @@
1
1
  import { ACCESS_LEVEL_ORDER as t } from "./types.js";
2
- import { createKbClient as s } from "./client.js";
3
- import { findNavNode as n, flattenNav as i, isNavigable as m, navBreadcrumbs as p, navNextPrev as f, navSiblings as c, navSubtree as d, navWalk as x } from "./navigation.js";
4
- import { createAuthManager as b, createLocalStorageTokenStorage as u, createMemoryTokenStorage as v, decodeJwtUser as S, hasAccessLevel as T } from "./auth.js";
5
- import { generateDescription as h, stripLeadingH1 as A } from "./article-seo.js";
6
- import { createMarkedInstance as k, defaultImageHtml as M, parseMarkdownSafe as N } from "./markdown.js";
7
- import { deepMerge as I } from "./blog-config.js";
8
- import { retryWithBackoff as E } from "./retry.js";
9
- import { buildThemeCssVars as R, darkenColor as w, hexToHsl as y, hexToRgb as B, hslToRgb as K, lightenColor as U, rgbTriplet as V } from "./theme.js";
10
- import { buildArticleSeo as _, buildHomeSeo as q, buildListPageSeo as z, localizedHref as J, pageUrl as O, stripLocalePrefix as j } from "./seo.js";
11
- import { buildArticleListItem as G, formatArticleDate as Q, resolveArticleAccessLevel as X, toIsoDate as Y } from "./view-model.js";
12
- import { createKbI18n as $, mergeTranslations as ee } from "./i18n.js";
2
+ import { createKbClient as l } from "./client.js";
3
+ import { findNavNode as s, flattenNav as i, isNavigable as m, navBreadcrumbs as p, navNextPrev as f, navSiblings as c, navSubtree as d, navWalk as x } from "./navigation.js";
4
+ import { createAuthManager as b, createLocalStorageTokenStorage as u, createMemoryTokenStorage as v, decodeJwtUser as T, hasAccessLevel as S } from "./auth.js";
5
+ import { DelegatedTokenError as L, createDelegatedTokenMinter as h } from "./delegated-identity.js";
6
+ import { generateDescription as C, stripLeadingH1 as M } from "./article-seo.js";
7
+ import { createMarkedInstance as N, defaultImageHtml as E, parseMarkdownSafe as H } from "./markdown.js";
8
+ import { deepMerge as P } from "./blog-config.js";
9
+ import { retryWithBackoff as w } from "./retry.js";
10
+ import { buildThemeCssVars as B, darkenColor as K, hexToHsl as U, hexToRgb as V, hslToRgb as W, lightenColor as _, rgbTriplet as q } from "./theme.js";
11
+ import { buildArticleSeo as J, buildHomeSeo as O, buildListPageSeo as j, localizedHref as F, pageUrl as G, stripLocalePrefix as Q } from "./seo.js";
12
+ import { buildArticleListItem as Y, formatArticleDate as Z, resolveArticleAccessLevel as $, toIsoDate as ee } from "./view-model.js";
13
+ import { createKbI18n as oe, mergeTranslations as te } from "./i18n.js";
13
14
  import * as e from "./queries.js";
14
- import { prepareProps as oe } from "../packages/mdx-schema/dist/prepareProps.js";
15
- import { componentMetadata as ae, getComponentMetadata as se, getComponentNames as le } from "../packages/mdx-schema/dist/metadata/index.js";
16
- import { default as ie } from "./translations/cs.json.js";
17
- import { default as pe } from "./translations/en.json.js";
15
+ import { prepareProps as le } from "../packages/mdx-schema/dist/prepareProps.js";
16
+ import { componentMetadata as se, getComponentMetadata as ie, getComponentNames as me } from "../packages/mdx-schema/dist/metadata/index.js";
17
+ import { default as fe } from "./translations/cs.json.js";
18
+ import { default as de } from "./translations/en.json.js";
18
19
  export {
19
20
  t as ACCESS_LEVEL_ORDER,
20
- G as buildArticleListItem,
21
- _ as buildArticleSeo,
22
- q as buildHomeSeo,
23
- z as buildListPageSeo,
24
- R as buildThemeCssVars,
25
- ae as componentMetadata,
21
+ L as DelegatedTokenError,
22
+ Y as buildArticleListItem,
23
+ J as buildArticleSeo,
24
+ O as buildHomeSeo,
25
+ j as buildListPageSeo,
26
+ B as buildThemeCssVars,
27
+ se as componentMetadata,
26
28
  b as createAuthManager,
27
- s as createKbClient,
28
- $ as createKbI18n,
29
+ h as createDelegatedTokenMinter,
30
+ l as createKbClient,
31
+ oe as createKbI18n,
29
32
  u as createLocalStorageTokenStorage,
30
- k as createMarkedInstance,
33
+ N as createMarkedInstance,
31
34
  v as createMemoryTokenStorage,
32
- ie as csTranslations,
33
- w as darkenColor,
34
- S as decodeJwtUser,
35
- I as deepMerge,
36
- M as defaultImageHtml,
37
- pe as enTranslations,
38
- n as findNavNode,
35
+ fe as csTranslations,
36
+ K as darkenColor,
37
+ T as decodeJwtUser,
38
+ P as deepMerge,
39
+ E as defaultImageHtml,
40
+ de as enTranslations,
41
+ s as findNavNode,
39
42
  i as flattenNav,
40
- Q as formatArticleDate,
41
- h as generateDescription,
42
- se as getComponentMetadata,
43
- le as getComponentNames,
44
- T as hasAccessLevel,
45
- y as hexToHsl,
46
- B as hexToRgb,
47
- K as hslToRgb,
43
+ Z as formatArticleDate,
44
+ C as generateDescription,
45
+ ie as getComponentMetadata,
46
+ me as getComponentNames,
47
+ S as hasAccessLevel,
48
+ U as hexToHsl,
49
+ V as hexToRgb,
50
+ W as hslToRgb,
48
51
  m as isNavigable,
49
- U as lightenColor,
50
- J as localizedHref,
51
- ee as mergeTranslations,
52
+ _ as lightenColor,
53
+ F as localizedHref,
54
+ te as mergeTranslations,
52
55
  p as navBreadcrumbs,
53
56
  f as navNextPrev,
54
57
  c as navSiblings,
55
58
  d as navSubtree,
56
59
  x as navWalk,
57
- O as pageUrl,
58
- N as parseMarkdownSafe,
59
- oe as prepareProps,
60
+ G as pageUrl,
61
+ H as parseMarkdownSafe,
62
+ le as prepareProps,
60
63
  e as queries,
61
- X as resolveArticleAccessLevel,
62
- E as retryWithBackoff,
63
- V as rgbTriplet,
64
- A as stripLeadingH1,
65
- j as stripLocalePrefix,
66
- Y as toIsoDate
64
+ $ as resolveArticleAccessLevel,
65
+ w as retryWithBackoff,
66
+ q as rgbTriplet,
67
+ M as stripLeadingH1,
68
+ Q as stripLocalePrefix,
69
+ ee as toIsoDate
67
70
  };
@@ -9,6 +9,7 @@ export declare const ACCESSIBLE_ARTICLES = "\n query AccessibleArticles($status
9
9
  export declare const ARTICLE_WITH_TRANSLATION = "\n query ArticleWithTranslation($filename: String!, $languageCode: String!) {\n articleWithTranslation(filename: $filename, languageCode: $languageCode) {\n id\n filename\n contentType\n status\n description\n sourceLanguageCode\n createdAt\n updatedAt\n publishedAt\n title\n content\n languageCode\n isSource\n isFallback\n featuredImageUrl\n featuredImageGeo {\n latitude\n longitude\n altitude\n placeName\n }\n contentImagesGeo {\n url\n latitude\n longitude\n altitude\n placeName\n }\n accessRights\n}\n }\n";
10
10
  export declare const ARTICLE_WITH_TRANSLATION_BY_ID = "\n query ArticleWithTranslationById($id: ID!, $languageCode: String!) {\n articleWithTranslationById(id: $id, languageCode: $languageCode) {\n id\n filename\n contentType\n status\n description\n sourceLanguageCode\n createdAt\n updatedAt\n publishedAt\n title\n content\n languageCode\n isSource\n isFallback\n featuredImageUrl\n featuredImageGeo {\n latitude\n longitude\n altitude\n placeName\n }\n contentImagesGeo {\n url\n latitude\n longitude\n altitude\n placeName\n }\n accessRights\n}\n }\n";
11
11
  export declare const ARTICLE_ALIAS_TARGET = "\n query ArticleAliasTarget($filename: String!) {\n articleAliasTarget(filename: $filename)\n }\n";
12
+ export declare const ARTICLE_VERSION = "\n query ArticleVersion($versionId: ID!, $previewKey: String) {\n articleVersion(versionId: $versionId, previewKey: $previewKey) {\n versionId\n articleId\n filename\n versionNumber\n title\n content\n languageCode\n schemaVersion\n createdAt\n }\n }\n";
12
13
  export declare const SEARCH_KNOWLEDGE_BASE = "\n query SearchKnowledgeBase($query: String!, $tags: [String!], $contentType: String, $limit: Int, $minSimilarity: Float, $searchMode: SearchMode) {\n searchKnowledgeBase(query: $query, tags: $tags, contentType: $contentType, limit: $limit, minSimilarity: $minSimilarity, searchMode: $searchMode) {\n articleId\n filename\n title\n chunkText\n similarity\n }\n }\n";
13
14
  export declare const GET_KB_CONTEXT = "\n query GetKBContext($query: String!, $maxChunks: Int) {\n getKBContext(query: $query, maxChunks: $maxChunks) {\n chunks {\n filename\n title\n text\n similarity\n }\n totalChunks\n }\n }\n";
14
15
  export declare const KB_NAVIGATION = "\n query KbNavigation($scope: String, $locale: String) {\n kbNavigation(scope: $scope, locale: $locale)\n }\n";
@@ -59,6 +59,20 @@ const a = `
59
59
  articleAliasTarget(filename: $filename)
60
60
  }
61
61
  `, r = `
62
+ query ArticleVersion($versionId: ID!, $previewKey: String) {
63
+ articleVersion(versionId: $versionId, previewKey: $previewKey) {
64
+ versionId
65
+ articleId
66
+ filename
67
+ versionNumber
68
+ title
69
+ content
70
+ languageCode
71
+ schemaVersion
72
+ createdAt
73
+ }
74
+ }
75
+ `, s = `
62
76
  query SearchKnowledgeBase($query: String!, $tags: [String!], $contentType: String, $limit: Int, $minSimilarity: Float, $searchMode: SearchMode) {
63
77
  searchKnowledgeBase(query: $query, tags: $tags, contentType: $contentType, limit: $limit, minSimilarity: $minSimilarity, searchMode: $searchMode) {
64
78
  articleId
@@ -68,7 +82,7 @@ const a = `
68
82
  similarity
69
83
  }
70
84
  }
71
- `, s = `
85
+ `, c = `
72
86
  query GetKBContext($query: String!, $maxChunks: Int) {
73
87
  getKBContext(query: $query, maxChunks: $maxChunks) {
74
88
  chunks {
@@ -80,11 +94,11 @@ const a = `
80
94
  totalChunks
81
95
  }
82
96
  }
83
- `, c = `
97
+ `, l = `
84
98
  query KbNavigation($scope: String, $locale: String) {
85
99
  kbNavigation(scope: $scope, locale: $locale)
86
100
  }
87
- `, l = `
101
+ `, d = `
88
102
  query AccessibleTags {
89
103
  accessibleKbTags {
90
104
  tags {
@@ -97,7 +111,7 @@ const a = `
97
111
  totalCount
98
112
  }
99
113
  }
100
- `, d = `
114
+ `, m = `
101
115
  query LocalizedTags($languageCode: String!) {
102
116
  localizedTags(languageCode: $languageCode) {
103
117
  id
@@ -110,7 +124,7 @@ const a = `
110
124
  isFallback
111
125
  }
112
126
  }
113
- `, m = `
127
+ `, u = `
114
128
  query KBLanguages {
115
129
  kbLanguages {
116
130
  id
@@ -122,7 +136,7 @@ const a = `
122
136
  sortOrder
123
137
  }
124
138
  }
125
- `, u = `
139
+ `, g = `
126
140
  query ArticleTranslations($sourceFilename: String!) {
127
141
  listArticleTranslations(sourceFilename: $sourceFilename) {
128
142
  id
@@ -133,7 +147,7 @@ const a = `
133
147
  updatedAt
134
148
  }
135
149
  }
136
- `, g = `
150
+ `, $ = `
137
151
  query GetTranslation($sourceFilename: String!, $languageCode: String!) {
138
152
  getTranslation(sourceFilename: $sourceFilename, languageCode: $languageCode) {
139
153
  id
@@ -161,7 +175,7 @@ const a = `
161
175
  isTranslated
162
176
  isEdited
163
177
  createdAt
164
- `, $ = `
178
+ `, C = `
165
179
  query ArticleComments($articleId: ID!, $languageCode: String!) {
166
180
  articleComments(articleId: $articleId, languageCode: $languageCode) {
167
181
  comments {
@@ -179,7 +193,7 @@ const a = `
179
193
  totalCount
180
194
  }
181
195
  }
182
- `, C = `
196
+ `, S = `
183
197
  query GetComment($commentId: ID!, $languageCode: String!) {
184
198
  comment(commentId: $commentId, languageCode: $languageCode) {
185
199
  ${e}
@@ -188,7 +202,7 @@ const a = `
188
202
  }
189
203
  }
190
204
  }
191
- `, S = `
205
+ `, I = `
192
206
  mutation CreateComment($articleId: ID!, $content: String!, $sourceLanguageCode: String!, $parentCommentId: ID) {
193
207
  createComment(articleId: $articleId, content: $content, sourceLanguageCode: $sourceLanguageCode, parentCommentId: $parentCommentId) {
194
208
  success
@@ -198,7 +212,7 @@ const a = `
198
212
  }
199
213
  }
200
214
  }
201
- `, I = `
215
+ `, T = `
202
216
  mutation UpdateComment($commentId: ID!, $content: String!) {
203
217
  updateComment(commentId: $commentId, content: $content) {
204
218
  success
@@ -208,21 +222,21 @@ const a = `
208
222
  }
209
223
  }
210
224
  }
211
- `, T = `
225
+ `, p = `
212
226
  mutation DeleteComment($commentId: ID!) {
213
227
  deleteComment(commentId: $commentId) {
214
228
  success
215
229
  error
216
230
  }
217
231
  }
218
- `, p = `
232
+ `, E = `
219
233
  subscription CommentUpdates($articleId: ID!) {
220
234
  commentUpdates(articleId: $articleId) {
221
235
  type
222
236
  commentId
223
237
  }
224
238
  }
225
- `, E = `
239
+ `, A = `
226
240
  mutation Login($email: String!, $password: String!) {
227
241
  login(email: $email, password: $password) {
228
242
  success
@@ -236,7 +250,7 @@ const a = `
236
250
  error
237
251
  }
238
252
  }
239
- `, A = `
253
+ `, R = `
240
254
  mutation Register($email: String!, $password: String!, $name: String) {
241
255
  register(email: $email, password: $password, name: $name) {
242
256
  success
@@ -244,14 +258,14 @@ const a = `
244
258
  error
245
259
  }
246
260
  }
247
- `, R = `
261
+ `, y = `
248
262
  mutation VerifyEmail($token: String!) {
249
263
  verifyEmail(token: $token) {
250
264
  success
251
265
  error
252
266
  }
253
267
  }
254
- `, y = `
268
+ `, f = `
255
269
  mutation ForgotPassword($email: String!) {
256
270
  forgotPassword(email: $email) {
257
271
  success
@@ -259,14 +273,14 @@ const a = `
259
273
  error
260
274
  }
261
275
  }
262
- `, f = `
276
+ `, N = `
263
277
  mutation ResetPassword($token: String!, $password: String!) {
264
278
  resetPassword(token: $token, password: $password) {
265
279
  success
266
280
  error
267
281
  }
268
282
  }
269
- `, N = `
283
+ `, L = `
270
284
  mutation ResendVerification($email: String!) {
271
285
  resendVerification(email: $email) {
272
286
  success
@@ -274,14 +288,14 @@ const a = `
274
288
  error
275
289
  }
276
290
  }
277
- `, L = `
291
+ `, _ = `
278
292
  mutation ChangePassword($currentPassword: String!, $newPassword: String!) {
279
293
  changePassword(currentPassword: $currentPassword, newPassword: $newPassword) {
280
294
  success
281
295
  error
282
296
  }
283
297
  }
284
- `, _ = `
298
+ `, P = `
285
299
  mutation UpdateMyProfile($name: String, $email: String) {
286
300
  updateMyProfile(name: $name, email: $email) {
287
301
  success
@@ -295,7 +309,7 @@ const a = `
295
309
  error
296
310
  }
297
311
  }
298
- `, P = `
312
+ `, w = `
299
313
  query MyReportSettings {
300
314
  myReportSettings {
301
315
  autoReportErrors
@@ -338,31 +352,32 @@ const a = `
338
352
  `;
339
353
  export {
340
354
  a as ACCESSIBLE_ARTICLES,
341
- l as ACCESSIBLE_TAGS,
355
+ d as ACCESSIBLE_TAGS,
342
356
  i as ARTICLE_ALIAS_TARGET,
343
- $ as ARTICLE_COMMENTS,
344
- u as ARTICLE_TRANSLATIONS,
357
+ C as ARTICLE_COMMENTS,
358
+ g as ARTICLE_TRANSLATIONS,
359
+ r as ARTICLE_VERSION,
345
360
  n as ARTICLE_WITH_TRANSLATION,
346
361
  o as ARTICLE_WITH_TRANSLATION_BY_ID,
347
- L as CHANGE_PASSWORD,
348
- p as COMMENT_UPDATES_SUBSCRIPTION,
349
- S as CREATE_COMMENT,
350
- T as DELETE_COMMENT,
351
- y as FORGOT_PASSWORD,
352
- C as GET_COMMENT,
353
- s as GET_KB_CONTEXT,
354
- g as GET_TRANSLATION,
355
- m as KB_LANGUAGES,
356
- c as KB_NAVIGATION,
357
- d as LOCALIZED_TAGS,
358
- E as LOGIN,
359
- P as MY_REPORT_SETTINGS,
360
- A as REGISTER,
361
- N as RESEND_VERIFICATION,
362
- f as RESET_PASSWORD,
363
- r as SEARCH_KNOWLEDGE_BASE,
364
- I as UPDATE_COMMENT,
365
- _ as UPDATE_MY_PROFILE,
362
+ _ as CHANGE_PASSWORD,
363
+ E as COMMENT_UPDATES_SUBSCRIPTION,
364
+ I as CREATE_COMMENT,
365
+ p as DELETE_COMMENT,
366
+ f as FORGOT_PASSWORD,
367
+ S as GET_COMMENT,
368
+ c as GET_KB_CONTEXT,
369
+ $ as GET_TRANSLATION,
370
+ u as KB_LANGUAGES,
371
+ l as KB_NAVIGATION,
372
+ m as LOCALIZED_TAGS,
373
+ A as LOGIN,
374
+ w as MY_REPORT_SETTINGS,
375
+ R as REGISTER,
376
+ L as RESEND_VERIFICATION,
377
+ N as RESET_PASSWORD,
378
+ s as SEARCH_KNOWLEDGE_BASE,
379
+ T as UPDATE_COMMENT,
380
+ P as UPDATE_MY_PROFILE,
366
381
  M as UPDATE_MY_REPORT_SETTINGS,
367
- R as VERIFY_EMAIL
382
+ y as VERIFY_EMAIL
368
383
  };
@@ -51,6 +51,25 @@ export interface ArticleWithTranslation {
51
51
  contentImagesGeo?: ContentImageGeo[] | null;
52
52
  accessRights: string[];
53
53
  }
54
+ /**
55
+ * A single immutable article version's content, addressed by its STABLE version
56
+ * id. Returned by `client.articles.getVersion`. Generic preview / A/B exposure —
57
+ * the server bypasses publish status, so the fetch requires either an internal
58
+ * token or a valid `previewKey` for this exact versionId. Versions are
59
+ * per-language; `languageCode` is the version's own translation language.
60
+ */
61
+ export interface ArticleVersionContent {
62
+ versionId: string;
63
+ articleId: string;
64
+ filename: string;
65
+ versionNumber: number;
66
+ title: string;
67
+ content: string;
68
+ languageCode: string;
69
+ /** SCHEMA_VERSION the snapshot was authored under (lets consumers detect staleness). */
70
+ schemaVersion: string | null;
71
+ createdAt: string;
72
+ }
54
73
  export interface Tag {
55
74
  id: string;
56
75
  slug: string;
@@ -1,4 +1,4 @@
1
- import { __exports as s } from "../../../../_virtual/index3.js";
1
+ import { __exports as s } from "../../../../_virtual/index2.js";
2
2
  import { __require as v } from "./constants.js";
3
3
  var m;
4
4
  function U() {
@@ -2,7 +2,7 @@ import { defineAsyncComponent as m, defineComponent as u, h as f } from "vue";
2
2
  import { componentMetadata as b } from "../../mdx-schema/dist/metadata/index.js";
3
3
  import { getComponentMetadata as T, getComponentNames as W } from "../../mdx-schema/dist/metadata/index.js";
4
4
  import { prepareProps as g } from "../../mdx-schema/dist/prepareProps.js";
5
- import "../../../_virtual/index2.js";
5
+ import "../../../_virtual/index3.js";
6
6
  const s = "__mdxPreparePropsAppliedFor", C = {
7
7
  Callout: {
8
8
  editor: { icon: "info", color: "#569cd6", borderColor: "#569cd6", bgColor: "rgba(86, 156, 214, 0.08)" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blogmcp/sdk",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Headless SDK for Knowledge Base blog — core client, Vue composables, Nuxt adapter",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -61,8 +61,8 @@
61
61
  }
62
62
  },
63
63
  "dependencies": {
64
- "@blogmcp/mdx-schema": "^0.1.2",
65
- "@blogmcp/sanitize": "^0.1.2",
64
+ "@blogmcp/mdx-schema": "^0.2.0",
65
+ "@blogmcp/sanitize": "^0.2.0",
66
66
  "marked": "^15.0.7"
67
67
  },
68
68
  "optionalDependencies": {
@@ -34,6 +34,13 @@ export interface KbClientConfig {
34
34
  tokenStorage?: TokenStorage
35
35
  /** Whether currently running on server (for endpoint selection). Defaults to false. */
36
36
  isServer?: boolean
37
+ /**
38
+ * Extra headers sent with every request (e.g. `X-Blogmcp-Client-Ip` from a
39
+ * trusted server proxy). The protocol-critical pair is protected:
40
+ * `Content-Type` and `Authorization` (from tokenStorage) always win over
41
+ * anything in this bag.
42
+ */
43
+ headers?: Record<string, string>
37
44
  }
38
45
 
39
46
  /** Generates HTML for images in markdown content. Pluggable for IPX, Cloudinary, etc. */
@@ -10,6 +10,7 @@ import type { KbClientConfig, Fetcher, TokenStorage } from './client-types'
10
10
  import type {
11
11
  Article,
12
12
  ArticleWithTranslation,
13
+ ArticleVersionContent,
13
14
  Tag,
14
15
  LocalizedTag,
15
16
  Language,
@@ -43,11 +44,19 @@ function createDefaultFetcher(): Fetcher {
43
44
 
44
45
  /** Execute a GraphQL query and return typed data */
45
46
  async function executeGraphQL<T>(
46
- config: { endpoint: string; fetcher: Fetcher; tokenStorage: TokenStorage },
47
+ config: {
48
+ endpoint: string
49
+ fetcher: Fetcher
50
+ tokenStorage: TokenStorage
51
+ headers?: Record<string, string>
52
+ },
47
53
  query: string,
48
54
  variables?: Record<string, unknown>,
49
55
  ): Promise<T> {
56
+ // Extra headers first; the protocol-critical pair (Content-Type,
57
+ // Authorization) is applied after so a headers bag can never displace them.
50
58
  const headers: Record<string, string> = {
59
+ ...(config.headers ?? {}),
51
60
  'Content-Type': 'application/json',
52
61
  }
53
62
 
@@ -110,6 +119,19 @@ export interface KbClient {
110
119
  resolveAlias(
111
120
  filename: string,
112
121
  ): Promise<{ articleAliasTarget: string | null }>
122
+ /**
123
+ * Fetch ONE article version's content by its STABLE version id, for headless
124
+ * preview / A/B (test-before-publish, multi-variant serving). Bypasses publish
125
+ * status, so the server returns it only to an INTERNAL caller (server client
126
+ * holding the api token) OR a caller passing a valid `previewKey` minted for
127
+ * this exact versionId. Returns `{ articleVersion: null }` when missing or
128
+ * unauthorized. Versions are per-language; the returned `languageCode` is the
129
+ * version's own translation — no language argument is taken.
130
+ */
131
+ getVersion(
132
+ versionId: string,
133
+ opts?: { previewKey?: string },
134
+ ): Promise<{ articleVersion: ArticleVersionContent | null }>
113
135
  }
114
136
  search: {
115
137
  query(params: {
@@ -225,7 +247,7 @@ export function createKbClient(config: KbClientConfig): KbClient {
225
247
  ? config.serverEndpoint
226
248
  : config.endpoint
227
249
 
228
- const ctx = { endpoint, fetcher, tokenStorage }
250
+ const ctx = { endpoint, fetcher, tokenStorage, headers: config.headers }
229
251
 
230
252
  function exec<T>(query: string, variables?: Record<string, unknown>) {
231
253
  return executeGraphQL<T>(ctx, query, variables)
@@ -240,6 +262,8 @@ export function createKbClient(config: KbClientConfig): KbClient {
240
262
  exec(Q.ARTICLE_WITH_TRANSLATION_BY_ID, { id, languageCode }),
241
263
  resolveAlias: (filename) =>
242
264
  exec(Q.ARTICLE_ALIAS_TARGET, { filename }),
265
+ getVersion: (versionId, opts) =>
266
+ exec(Q.ARTICLE_VERSION, { versionId, previewKey: opts?.previewKey ?? null }),
243
267
  },
244
268
  search: {
245
269
  query: (params) => exec(Q.SEARCH_KNOWLEDGE_BASE, params),
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Delegated identity for headless storefronts ("external login").
3
+ *
4
+ * A trusted storefront server that has ALREADY authenticated its own user
5
+ * (a Vendure customer, a Shopify account, any bring-your-own-login) exchanges
6
+ * its internal `kb_*` API key plus the user's email/name for a short-lived,
7
+ * user-scoped KB JWT via `POST {api}/auth/delegated-token`. Requests made with
8
+ * that token author comments and feedback as a real per-user KB identity —
9
+ * ownership, edit/delete-own, and quotas all apply per end user instead of
10
+ * collapsing onto the shared service key.
11
+ *
12
+ * The minted token is deliberately narrow: `accessLevel: 'public'` always and
13
+ * `scope: 'delegated'` (profile/password mutations are rejected server-side).
14
+ *
15
+ * SERVER-ONLY: `createDelegatedTokenMinter` throws when called in a browser
16
+ * context — the internal key must never ship in a client bundle. Keep usage
17
+ * inside server-only modules (e.g. React Router `*.server.ts`, Nuxt server
18
+ * routes).
19
+ */
20
+
21
+ export interface DelegatedTokenMinterConfig {
22
+ /**
23
+ * Full URL of the delegated-token endpoint, e.g.
24
+ * `${BLOGMCP_API_URL}/api/auth/delegated-token`.
25
+ */
26
+ endpoint: string
27
+ /** Internal-access `kb_*` API key. Server-side secret. */
28
+ internalKey: string
29
+ /**
30
+ * Refresh a cached token this many ms before its expiry. Default 5 minutes
31
+ * (clamped to a non-negative value).
32
+ */
33
+ ttlSkewMs?: number
34
+ /** Custom fetch implementation (tests / non-global-fetch runtimes). */
35
+ fetchImpl?: typeof fetch
36
+ }
37
+
38
+ export interface DelegatedMintInput {
39
+ /** End-user email as verified by the delegating storefront. */
40
+ email: string
41
+ /** Display name shown as the comment author (e.g. "Jana N."). */
42
+ name?: string
43
+ /**
44
+ * Stable caller-side user reference, e.g. `vendure:customer:42`. Stored for
45
+ * audit on the kb user row and used as the cache key (falls back to the
46
+ * normalized email when omitted).
47
+ */
48
+ externalRef?: string
49
+ }
50
+
51
+ export interface DelegatedIdentity {
52
+ /** Short-lived user-scoped KB JWT — send as `Authorization: Bearer <token>`. */
53
+ token: string
54
+ /** The kb user id the token acts as (matches `Comment.userId`). */
55
+ kbUserId: string
56
+ email: string
57
+ name: string | null
58
+ /** True when this mint created the kb user row (first visit). */
59
+ created: boolean
60
+ /** Epoch ms when the token expires. */
61
+ expiresAt: number
62
+ }
63
+
64
+ /** Thrown on a non-2xx or malformed response from the delegated-token endpoint. */
65
+ export class DelegatedTokenError extends Error {
66
+ readonly status: number
67
+
68
+ constructor(status: number, message: string) {
69
+ super(message)
70
+ this.name = 'DelegatedTokenError'
71
+ this.status = status
72
+ }
73
+ }
74
+
75
+ export interface DelegatedTokenMinter {
76
+ /**
77
+ * Return a fresh identity for the given end user. Cached per
78
+ * `externalRef` (or normalized email) until close to expiry; concurrent
79
+ * mints for the same user share one request.
80
+ */
81
+ mint(input: DelegatedMintInput): Promise<DelegatedIdentity>
82
+ /**
83
+ * Drop a cached identity — pass the cache key (the `externalRef`, or the
84
+ * normalized email when no ref was used) or nothing to clear all.
85
+ */
86
+ invalidate(key?: string): void
87
+ }
88
+
89
+ const DEFAULT_TTL_SKEW_MS = 5 * 60 * 1000
90
+
91
+ /**
92
+ * Cache-size threshold that triggers a sweep of expired identities. Without
93
+ * it, one entry per distinct end user would accumulate for the lifetime of
94
+ * the server process (unbounded heap growth on large storefronts). Entries
95
+ * are tiny, so the sweep is deliberately lazy — amortized into mint() rather
96
+ * than a timer.
97
+ */
98
+ const CACHE_SWEEP_THRESHOLD = 1024
99
+
100
+ interface DelegatedTokenResponse {
101
+ token: string
102
+ /** Token lifetime in seconds. */
103
+ expiresIn: number
104
+ user: { id: string; email: string; name: string | null; created: boolean }
105
+ }
106
+
107
+ function normalizeEmail(email: string): string {
108
+ return email.toLowerCase().trim()
109
+ }
110
+
111
+ export function createDelegatedTokenMinter(
112
+ config: DelegatedTokenMinterConfig,
113
+ ): DelegatedTokenMinter {
114
+ if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
115
+ throw new Error(
116
+ '[blogmcp-sdk] createDelegatedTokenMinter is server-only — it holds an ' +
117
+ 'internal API key that must never reach the browser.',
118
+ )
119
+ }
120
+ if (!config.endpoint) throw new Error('[blogmcp-sdk] delegated-token endpoint is required')
121
+ if (!config.internalKey) throw new Error('[blogmcp-sdk] internalKey is required')
122
+
123
+ const ttlSkewMs = Math.max(0, config.ttlSkewMs ?? DEFAULT_TTL_SKEW_MS)
124
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch
125
+ const cache = new Map<string, DelegatedIdentity>()
126
+ const inFlight = new Map<string, Promise<DelegatedIdentity>>()
127
+
128
+ async function requestToken(input: DelegatedMintInput): Promise<DelegatedIdentity> {
129
+ const res = await fetchImpl(config.endpoint, {
130
+ method: 'POST',
131
+ headers: {
132
+ 'Content-Type': 'application/json',
133
+ Authorization: `Bearer ${config.internalKey}`,
134
+ },
135
+ body: JSON.stringify({
136
+ email: input.email,
137
+ name: input.name,
138
+ externalRef: input.externalRef,
139
+ }),
140
+ })
141
+
142
+ if (!res.ok) {
143
+ let message = `delegated-token request failed with status ${res.status}`
144
+ try {
145
+ const body = (await res.json()) as { error?: string }
146
+ if (body?.error) message = body.error
147
+ } catch {
148
+ // Non-JSON error body — keep the status message.
149
+ }
150
+ throw new DelegatedTokenError(res.status, message)
151
+ }
152
+
153
+ const body = (await res.json()) as Partial<DelegatedTokenResponse>
154
+ if (
155
+ typeof body?.token !== 'string' ||
156
+ typeof body.expiresIn !== 'number' ||
157
+ typeof body.user?.id !== 'string'
158
+ ) {
159
+ throw new DelegatedTokenError(res.status, 'delegated-token response is malformed')
160
+ }
161
+
162
+ return {
163
+ token: body.token,
164
+ kbUserId: body.user.id,
165
+ email: body.user.email ?? normalizeEmail(input.email),
166
+ name: body.user.name ?? null,
167
+ created: body.user.created === true,
168
+ expiresAt: Date.now() + body.expiresIn * 1000,
169
+ }
170
+ }
171
+
172
+ return {
173
+ async mint(input: DelegatedMintInput): Promise<DelegatedIdentity> {
174
+ if (!input?.email) throw new Error('[blogmcp-sdk] mint() requires an email')
175
+ const key = input.externalRef ?? normalizeEmail(input.email)
176
+
177
+ const cached = cache.get(key)
178
+ if (cached && cached.expiresAt - Date.now() > ttlSkewMs) {
179
+ return cached
180
+ }
181
+
182
+ const pending = inFlight.get(key)
183
+ if (pending) return pending
184
+
185
+ // Lazy eviction: once the cache is large, drop everything already
186
+ // expired so long-lived processes don't pin one entry per user forever.
187
+ if (cache.size >= CACHE_SWEEP_THRESHOLD) {
188
+ const now = Date.now()
189
+ for (const [k, v] of cache) {
190
+ if (v.expiresAt <= now) cache.delete(k)
191
+ }
192
+ }
193
+
194
+ const promise = requestToken(input)
195
+ .then((identity) => {
196
+ cache.set(key, identity)
197
+ return identity
198
+ })
199
+ .finally(() => {
200
+ inFlight.delete(key)
201
+ })
202
+ inFlight.set(key, promise)
203
+ return promise
204
+ },
205
+
206
+ invalidate(key?: string): void {
207
+ if (key === undefined) {
208
+ cache.clear()
209
+ } else {
210
+ cache.delete(key)
211
+ }
212
+ },
213
+ }
214
+ }
package/src/core/index.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  export type {
3
3
  Article,
4
4
  ArticleWithTranslation,
5
+ ArticleVersionContent,
5
6
  MediaGeo,
6
7
  ContentImageGeo,
7
8
  Tag,
@@ -64,6 +65,18 @@ export {
64
65
  hasAccessLevel,
65
66
  } from './auth'
66
67
 
68
+ // Delegated identity (server-only — headless storefront "external login")
69
+ export {
70
+ createDelegatedTokenMinter,
71
+ DelegatedTokenError,
72
+ } from './delegated-identity'
73
+ export type {
74
+ DelegatedTokenMinter,
75
+ DelegatedTokenMinterConfig,
76
+ DelegatedMintInput,
77
+ DelegatedIdentity,
78
+ } from './delegated-identity'
79
+
67
80
  // Content utilities
68
81
  export { stripLeadingH1, generateDescription } from './article-seo'
69
82
  export { createMarkedInstance, defaultImageHtml, parseMarkdownSafe } from './markdown'
@@ -82,6 +82,25 @@ export const ARTICLE_ALIAS_TARGET = `
82
82
  }
83
83
  `
84
84
 
85
+ // Fetch ONE article version's content by its stable version id, for headless
86
+ // preview / A/B. Bypasses publish status, so the server serves it only to an
87
+ // internal caller OR a caller presenting a valid `previewKey` for this versionId.
88
+ export const ARTICLE_VERSION = `
89
+ query ArticleVersion($versionId: ID!, $previewKey: String) {
90
+ articleVersion(versionId: $versionId, previewKey: $previewKey) {
91
+ versionId
92
+ articleId
93
+ filename
94
+ versionNumber
95
+ title
96
+ content
97
+ languageCode
98
+ schemaVersion
99
+ createdAt
100
+ }
101
+ }
102
+ `
103
+
85
104
  // ==================== Search ====================
86
105
 
87
106
  export const SEARCH_KNOWLEDGE_BASE = `
package/src/core/types.ts CHANGED
@@ -57,6 +57,26 @@ export interface ArticleWithTranslation {
57
57
  accessRights: string[]
58
58
  }
59
59
 
60
+ /**
61
+ * A single immutable article version's content, addressed by its STABLE version
62
+ * id. Returned by `client.articles.getVersion`. Generic preview / A/B exposure —
63
+ * the server bypasses publish status, so the fetch requires either an internal
64
+ * token or a valid `previewKey` for this exact versionId. Versions are
65
+ * per-language; `languageCode` is the version's own translation language.
66
+ */
67
+ export interface ArticleVersionContent {
68
+ versionId: string
69
+ articleId: string
70
+ filename: string
71
+ versionNumber: number
72
+ title: string
73
+ content: string
74
+ languageCode: string
75
+ /** SCHEMA_VERSION the snapshot was authored under (lets consumers detect staleness). */
76
+ schemaVersion: string | null
77
+ createdAt: string
78
+ }
79
+
60
80
  // ==================== Tag Types ====================
61
81
 
62
82
  export interface Tag {