@tdacorp/hyle-sdk 0.23.0 → 0.24.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.
Files changed (36) hide show
  1. package/README.md +36 -18
  2. package/dist/check-routes-bin.js +34 -16
  3. package/dist/{chunk-UFMKLCXS.js → chunk-5TKJH2XC.js} +2 -2
  4. package/dist/{chunk-VXARM37R.js → chunk-BDFMNY76.js} +11 -5
  5. package/dist/{chunk-VUML2UPD.js → chunk-O4QWHXVH.js} +1 -1
  6. package/dist/{chunk-YHXE3TGS.js → chunk-RCK4NCYC.js} +33 -16
  7. package/dist/{chunk-JHZJOJDC.js → chunk-Y3BACEWA.js} +1 -1
  8. package/dist/{client-DK-S2580.d.cts → client-CI-3cHtc.d.cts} +13 -5
  9. package/dist/{client--ighAWaj.d.ts → client-DN38IP63.d.ts} +13 -5
  10. package/dist/comments.cjs +3 -2
  11. package/dist/comments.js +3 -2
  12. package/dist/{embed-g7NT1CyB.d.ts → embed-BaLQbE_n.d.ts} +1 -1
  13. package/dist/{embed-XT0x_Jaa.d.cts → embed-BrrGgkgQ.d.cts} +1 -1
  14. package/dist/html.cjs +3 -2
  15. package/dist/html.js +2 -2
  16. package/dist/index.cjs +34 -16
  17. package/dist/index.d.cts +3 -3
  18. package/dist/index.d.ts +3 -3
  19. package/dist/index.js +2 -2
  20. package/dist/next.cjs +316 -184
  21. package/dist/next.d.cts +46 -31
  22. package/dist/next.d.ts +46 -31
  23. package/dist/next.js +265 -154
  24. package/dist/react.cjs +3 -2
  25. package/dist/react.d.cts +3 -3
  26. package/dist/react.d.ts +3 -3
  27. package/dist/react.js +3 -3
  28. package/dist/{resolve-CiZCPysX.d.cts → resolve-Ce_yz8gC.d.cts} +1 -1
  29. package/dist/{resolve-BqC9l5RH.d.ts → resolve-DMHbYyTS.d.ts} +1 -1
  30. package/dist/{types-b9QbmEDd.d.cts → types-CxE8kLeo.d.cts} +30 -5
  31. package/dist/{types-b9QbmEDd.d.ts → types-CxE8kLeo.d.ts} +30 -5
  32. package/dist/use-cache.cjs +34 -16
  33. package/dist/use-cache.d.cts +3 -3
  34. package/dist/use-cache.d.ts +3 -3
  35. package/dist/use-cache.js +3 -3
  36. package/package.json +1 -1
package/dist/next.js CHANGED
@@ -19,15 +19,15 @@ import {
19
19
  readingMinutes,
20
20
  validOgImage,
21
21
  wordCountOf
22
- } from "./chunk-UFMKLCXS.js";
22
+ } from "./chunk-5TKJH2XC.js";
23
23
  import {
24
24
  stringsFor
25
- } from "./chunk-JHZJOJDC.js";
25
+ } from "./chunk-Y3BACEWA.js";
26
26
  import {
27
27
  DEFAULT_REVALIDATE,
28
28
  fetchResolver,
29
29
  workspaceTags
30
- } from "./chunk-VUML2UPD.js";
30
+ } from "./chunk-O4QWHXVH.js";
31
31
  import {
32
32
  Cp1ClientError,
33
33
  checkBaseUrl,
@@ -40,19 +40,20 @@ import {
40
40
  listPublicationPaths,
41
41
  readCapped,
42
42
  signReaderAssertion
43
- } from "./chunk-YHXE3TGS.js";
43
+ } from "./chunk-RCK4NCYC.js";
44
44
  import {
45
45
  ASSET_CONTENT_TYPES,
46
46
  ASSET_FILE,
47
47
  ASSET_ROUTE_PREFIX,
48
48
  PREVIEW_PARAM,
49
49
  PREVIEW_TOKEN,
50
- PROTECTED_ID,
50
+ PROTECTED_DOC_SLUG,
51
51
  PROTECTED_PARAM,
52
52
  PROTECTED_PASSWORD,
53
+ PROTECTED_SLUG,
53
54
  THEME_FILE,
54
55
  protectedCookieName
55
- } from "./chunk-VXARM37R.js";
56
+ } from "./chunk-BDFMNY76.js";
56
57
 
57
58
  // src/next/page.tsx
58
59
  import { notFound, permanentRedirect, redirect } from "next/navigation";
@@ -382,9 +383,9 @@ function createEngagementRoute(options) {
382
383
  try {
383
384
  const early = await options.onRequest(req, { action: route.action(req.method) });
384
385
  if (early instanceof Response) {
385
- const headers = new Headers(early.headers);
386
- headers.set("cache-control", "no-store");
387
- return new Response(early.body, { status: early.status, headers });
386
+ const headers2 = new Headers(early.headers);
387
+ headers2.set("cache-control", "no-store");
388
+ return new Response(early.body, { status: early.status, headers: headers2 });
388
389
  }
389
390
  } catch {
390
391
  return refuse(502, "UPSTREAM_ERROR");
@@ -412,11 +413,11 @@ function createEngagementRoute(options) {
412
413
  if (built.body) baseHeaders.set("content-type", "application/json");
413
414
  const target = `${config.base}/cp1/engage${built.upstream}${built.query ? `?${built.query}` : ""}`;
414
415
  const call = async (withAssertion = assertion) => {
415
- const headers = new Headers(baseHeaders);
416
- if (withAssertion) headers.set("hyle-reader-assertion", withAssertion);
416
+ const headers2 = new Headers(baseHeaders);
417
+ if (withAssertion) headers2.set("hyle-reader-assertion", withAssertion);
417
418
  const res = await fetchImpl(target, {
418
419
  method: req.method,
419
- headers,
420
+ headers: headers2,
420
421
  ...built.body ? { body: JSON.stringify(built.body) } : {},
421
422
  redirect: "error",
422
423
  signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
@@ -738,7 +739,7 @@ function hyleMetadata(options) {
738
739
  import { unstable_rethrow as unstable_rethrow3 } from "next/navigation";
739
740
  var xml = (value) => value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
740
741
  var tag = (name, value) => `<${name}>${xml(value)}</${name}>`;
741
- var response = (body, status, headers) => new Response(body, { status, ...headers ? { headers } : {} });
742
+ var response = (body, status, headers2) => new Response(body, { status, ...headers2 ? { headers: headers2 } : {} });
742
743
  async function hyleFeed(options) {
743
744
  const origin = options.siteOrigin;
744
745
  if (!origin || !BARE_HTTPS_ORIGIN.test(origin)) {
@@ -798,7 +799,7 @@ function createRevalidateRoute(options) {
798
799
  }
799
800
 
800
801
  // src/next/root.ts
801
- import { notFound as notFound2, unstable_rethrow as unstable_rethrow4 } from "next/navigation";
802
+ import { notFound as notFound4, unstable_rethrow as unstable_rethrow4 } from "next/navigation";
802
803
 
803
804
  // src/next/mount-match.ts
804
805
  function activeMounts(mounts) {
@@ -824,24 +825,170 @@ function isReserved(path, reserved) {
824
825
  return reserved.some((entry) => entry.endsWith("/*") ? prefixMatches(entry.slice(0, -2), path) : entry === path);
825
826
  }
826
827
 
828
+ // src/next/protected.tsx
829
+ import { cookies } from "next/headers";
830
+ import { notFound as notFound3 } from "next/navigation";
831
+
832
+ // src/next/preview.tsx
833
+ import { notFound as notFound2 } from "next/navigation";
834
+ import { Fragment, jsx as jsx3, jsxs } from "react/jsx-runtime";
835
+ function drawArticle(article, options) {
836
+ const { locale } = article.publication;
837
+ const toHref = (sitePath, linkLocale = locale) => (options.localePrefix?.(linkLocale) ?? "") + sitePath;
838
+ const props = { article, components: options.components, slots: options.slots, locale, toHref };
839
+ return options.layout === "docs" ? /* @__PURE__ */ jsx3(DocsPage, { ...props }) : /* @__PURE__ */ jsx3(ArticlePage, { ...props });
840
+ }
841
+ var hylePreviewMetadata = { robots: { index: false, follow: false }, referrer: "no-referrer" };
842
+ var BANNER = {
843
+ position: "sticky",
844
+ top: 0,
845
+ zIndex: 2147483647,
846
+ padding: "8px 16px",
847
+ background: "#fde047",
848
+ color: "#1a1a1a",
849
+ font: "600 14px/1.4 system-ui, sans-serif",
850
+ textAlign: "center"
851
+ };
852
+ function hylePreviewPage(options) {
853
+ return async function HylePreviewPage({ searchParams }) {
854
+ const { token } = await searchParams ?? {};
855
+ const result = await createHyleClient(options).preview(typeof token === "string" ? token : void 0);
856
+ if (result.kind !== "preview") notFound2();
857
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
858
+ /* @__PURE__ */ jsx3("meta", { name: "robots", content: "noindex, nofollow" }),
859
+ /* @__PURE__ */ jsx3("meta", { name: "referrer", content: "no-referrer" }),
860
+ /* @__PURE__ */ jsx3("div", { role: "status", style: BANNER, children: "Unpublished draft preview" }),
861
+ drawArticle(result.article, options)
862
+ ] });
863
+ };
864
+ }
865
+
866
+ // src/next/protected.tsx
867
+ import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
868
+ var hyleProtectedMetadata = { robots: { index: false, follow: false }, referrer: "no-referrer" };
869
+ var COOKIE_MAX_AGE_SECONDS = 12 * 60 * 60;
870
+ var UNLOCK_MAX_BYTES = 1024;
871
+ var PRIVATE_HEADERS = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Robots-Tag": "noindex, nofollow" };
872
+ var UNLOCK_PATH = "/hyle-protected/unlock";
873
+ var PASSWORD_FIELD = "hyle-protected-password";
874
+ var ERROR_ID = "hyle-protected-error";
875
+ function PasswordForm({ slug, failed }) {
876
+ return /* @__PURE__ */ jsxs2("main", { children: [
877
+ /* @__PURE__ */ jsx4("h1", { children: "Password required" }),
878
+ /* @__PURE__ */ jsxs2("form", { method: "post", action: UNLOCK_PATH, autoComplete: "off", children: [
879
+ /* @__PURE__ */ jsx4("input", { type: "hidden", name: "slug", value: slug }),
880
+ /* @__PURE__ */ jsx4("label", { htmlFor: PASSWORD_FIELD, children: "Password" }),
881
+ /* @__PURE__ */ jsx4(
882
+ "input",
883
+ {
884
+ id: PASSWORD_FIELD,
885
+ name: "password",
886
+ type: "password",
887
+ autoComplete: "off",
888
+ spellCheck: false,
889
+ required: true,
890
+ minLength: 12,
891
+ maxLength: 128,
892
+ "aria-invalid": failed || void 0,
893
+ "aria-describedby": failed ? ERROR_ID : void 0
894
+ }
895
+ ),
896
+ /* @__PURE__ */ jsx4("button", { type: "submit", children: "Open" }),
897
+ failed ? /* @__PURE__ */ jsx4("p", { id: ERROR_ID, role: "alert", children: "Wrong or expired password." }) : null
898
+ ] })
899
+ ] });
900
+ }
901
+ function TooManyAttempts({ seconds }) {
902
+ return /* @__PURE__ */ jsxs2("main", { children: [
903
+ /* @__PURE__ */ jsx4("h1", { children: "Too many attempts, try again later" }),
904
+ /* @__PURE__ */ jsxs2("p", { role: "alert", children: [
905
+ "Try again in ",
906
+ seconds,
907
+ " ",
908
+ seconds === 1 ? "second" : "seconds",
909
+ "."
910
+ ] })
911
+ ] });
912
+ }
913
+ var PRIVATE_META = /* @__PURE__ */ jsxs2(Fragment2, { children: [
914
+ /* @__PURE__ */ jsx4("meta", { name: "robots", content: "noindex, nofollow" }),
915
+ /* @__PURE__ */ jsx4("meta", { name: "referrer", content: "no-referrer" })
916
+ ] });
917
+ async function drawProtectedShare(options, slug, docSlug, clientIp) {
918
+ const client = createHyleClient({ baseUrl: options.baseUrl, token: options.token });
919
+ const visitor = { clientIp };
920
+ const password = (await cookies()).get(await protectedCookieName(slug))?.value;
921
+ const share = password === void 0 ? void 0 : await client.protected(slug, password, docSlug, visitor);
922
+ if (share?.kind === "limited") return /* @__PURE__ */ jsxs2(Fragment2, { children: [
923
+ PRIVATE_META,
924
+ /* @__PURE__ */ jsx4(TooManyAttempts, { seconds: share.retryAfterSeconds })
925
+ ] });
926
+ if (share?.kind === "disabled") notFound3();
927
+ if (share?.kind === "protected") {
928
+ if (docSlug !== void 0 && share.doc_slug !== docSlug) notFound3();
929
+ const here = `/${slug}/${share.doc_slug}`;
930
+ const article = {
931
+ ...share.article,
932
+ publication: { ...share.article.publication, canonical_path: here },
933
+ nav: { truncated: false, items: share.documents.map((d) => ({ slug: d.doc_slug, title: d.title, canonical_path: `/${slug}/${d.doc_slug}`, children: [] })) }
934
+ };
935
+ return /* @__PURE__ */ jsxs2(Fragment2, { children: [
936
+ PRIVATE_META,
937
+ drawArticle(article, { ...options, layout: share.documents.length > 1 ? "docs" : "article" })
938
+ ] });
939
+ }
940
+ const gate = await client.protectedGate(slug, visitor);
941
+ if (gate.kind === "limited") return /* @__PURE__ */ jsxs2(Fragment2, { children: [
942
+ PRIVATE_META,
943
+ /* @__PURE__ */ jsx4(TooManyAttempts, { seconds: gate.retryAfterSeconds })
944
+ ] });
945
+ if (gate.kind !== "gate") notFound3();
946
+ return /* @__PURE__ */ jsxs2(Fragment2, { children: [
947
+ PRIVATE_META,
948
+ /* @__PURE__ */ jsx4(PasswordForm, { slug, failed: password !== void 0 })
949
+ ] });
950
+ }
951
+ function createProtectedUnlockRoute() {
952
+ return {
953
+ async POST(req) {
954
+ const site = req.headers.get("sec-fetch-site");
955
+ if (site === null ? originMismatch(req) : site !== "same-origin") return new Response(null, { status: 403, headers: PRIVATE_HEADERS });
956
+ if (!/^application\/x-www-form-urlencoded(\s*;|$)/i.test(req.headers.get("content-type") ?? "")) return new Response(null, { status: 415, headers: PRIVATE_HEADERS });
957
+ if (Number(req.headers.get("content-length")) > UNLOCK_MAX_BYTES) return new Response(null, { status: 413, headers: PRIVATE_HEADERS });
958
+ const form = await readCapped(new Response(req.body), UNLOCK_MAX_BYTES).catch(() => void 0);
959
+ if (form === void 0) return new Response(null, { status: 413, headers: PRIVATE_HEADERS });
960
+ const fields = new URLSearchParams(form);
961
+ const slug = fields.get("slug") ?? "";
962
+ if (!PROTECTED_SLUG.test(slug)) return new Response(null, { status: 404, headers: PRIVATE_HEADERS });
963
+ const password = fields.get("password") ?? "";
964
+ const headers2 = new Headers({ ...PRIVATE_HEADERS, Location: `/${slug}` });
965
+ if (PROTECTED_PASSWORD.test(password)) {
966
+ const name = await protectedCookieName(slug);
967
+ for (const path of [`/${slug}`, ASSET_ROUTE_PREFIX]) headers2.append("Set-Cookie", `${name}=${password}; Max-Age=${COOKIE_MAX_AGE_SECONDS}; Path=${path}; HttpOnly; Secure; SameSite=Lax`);
968
+ }
969
+ return new Response(null, { status: 303, headers: headers2 });
970
+ }
971
+ };
972
+ }
973
+
827
974
  // src/next/root.ts
828
975
  var MOUNTS_MAX_STALE_MS = 15 * 60 * 1e3;
829
976
  var SECTION_SLUG = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
830
- var NONE = { mounts: [], reserved: [], defaultLocale: "" };
977
+ var NONE = { mounts: [], reserved: [], defaultLocale: "", protected: [] };
831
978
  var lastKnownGood = /* @__PURE__ */ new Map();
832
- function mountsLoader(config) {
979
+ function mountsLoader(config, ttlMs) {
833
980
  if (!config.workspaceId) throw new TypeError("hyleRootPage: `workspaceId` is required for the fetch cache");
834
981
  const client = createHyleClient({ baseUrl: config.baseUrl, token: config.token });
835
982
  const init = { next: { revalidate: config.revalidate ?? DEFAULT_REVALIDATE, tags: workspaceTags(config.workspaceId).slice(0, 1) } };
836
983
  const key = `${new URL(config.baseUrl).origin}|${config.workspaceId}`;
837
- return async function load() {
984
+ async function fetchLoaded() {
838
985
  try {
839
986
  const result = await client.mounts({ init });
840
987
  if (result.kind !== "mounts") {
841
988
  lastKnownGood.delete(key);
842
989
  return NONE;
843
990
  }
844
- const loaded = { mounts: activeMounts(result.mounts), reserved: result.reserved, defaultLocale: result.default_locale };
991
+ const loaded = { mounts: activeMounts(result.mounts), reserved: result.reserved, defaultLocale: result.default_locale, protected: result.protected ?? [] };
845
992
  lastKnownGood.set(key, { loaded, at: Date.now() });
846
993
  return loaded;
847
994
  } catch (error) {
@@ -854,15 +1001,35 @@ function mountsLoader(config) {
854
1001
  if (kept && Date.now() - kept.at <= MOUNTS_MAX_STALE_MS) return kept.loaded;
855
1002
  throw error;
856
1003
  }
1004
+ }
1005
+ if (ttlMs === void 0) return fetchLoaded;
1006
+ let ready;
1007
+ let read;
1008
+ let until = 0;
1009
+ let pending = false;
1010
+ return function load() {
1011
+ if (until <= Date.now() && !pending) {
1012
+ pending = true;
1013
+ until = Date.now() + ttlMs;
1014
+ read = fetchLoaded().then(
1015
+ (loaded) => ready = loaded,
1016
+ (error) => {
1017
+ ready = void 0;
1018
+ throw error;
1019
+ }
1020
+ );
1021
+ read.then(() => pending = false, () => pending = false);
1022
+ }
1023
+ return ready ? Promise.resolve(ready) : read;
857
1024
  };
858
1025
  }
859
1026
  var asArray = (options) => Array.isArray(options) ? options : [options];
860
- function setup(options) {
1027
+ function setup(options, ttlMs) {
861
1028
  const configs = asArray(options);
862
1029
  if (configs.length === 0) throw new TypeError("hyleRootPage: pass at least one workspace config");
863
1030
  const param = configs[0].param ?? "hyle";
864
1031
  if (configs.some((c) => (c.param ?? "hyle") !== param)) throw new TypeError("hyleRootPage: every config must use the same `param`");
865
- return { configs, param, loaders: configs.map(mountsLoader) };
1032
+ return { configs, param, loaders: configs.map((config) => mountsLoader(config, ttlMs)) };
866
1033
  }
867
1034
  var sectionsOf = (config, mount) => [
868
1035
  ...config.sections ?? [],
@@ -872,20 +1039,33 @@ function mountOptionsOf(config, mount) {
872
1039
  const { mountOptions, ...rest } = config;
873
1040
  return { ...rest, ...mountOptions?.[mount.prefix === "" ? "/" : mount.prefix], basePath: mount.prefix, sections: sectionsOf(config, mount) };
874
1041
  }
875
- function rootMounts(options) {
876
- const { configs, param, loaders } = setup(options);
1042
+ function rootMounts(options, ttlMs) {
1043
+ const { configs, param, loaders } = setup(options, ttlMs);
877
1044
  return {
878
1045
  param,
879
1046
  async locate(path) {
880
1047
  const loaded = await Promise.all(loaders.map((load) => load()));
1048
+ let share;
1049
+ loaded.forEach(({ protected: slugs }, index) => {
1050
+ for (const slug of slugs) {
1051
+ const depth = slug.split("/").length;
1052
+ if (!prefixMatches(`/${slug}`, path) || share && depth <= share.depth) continue;
1053
+ const docSlug = path === `/${slug}` ? void 0 : path.slice(slug.length + 2);
1054
+ if (docSlug === void 0 || PROTECTED_DOC_SLUG.test(docSlug)) share = { index, slug, depth, docSlug };
1055
+ }
1056
+ });
881
1057
  let best;
882
- loaded.forEach(({ mounts, reserved }, index2) => {
1058
+ loaded.forEach(({ mounts, reserved }, index) => {
883
1059
  if (isReserved(path, reserved)) return;
884
- for (const mount2 of mounts) if (prefixMatches(mount2.prefix, path) && (!best || mount2.depth > best.mount.depth)) best = { index: index2, mount: mount2 };
1060
+ for (const mount of mounts) if (prefixMatches(mount.prefix, path) && (!best || mount.depth > best.mount.depth)) best = { index, mount };
885
1061
  });
886
- if (!best) return void 0;
887
- const { index, mount } = best;
888
- return { options: mountOptionsOf(configs[index], mount), mount, index };
1062
+ const won = share;
1063
+ const mounted = best;
1064
+ if (won && (!mounted || won.depth > mounted.mount.depth || won.depth === mounted.mount.depth && won.index === mounted.index)) {
1065
+ return { share: { config: configs[won.index], slug: won.slug, docSlug: won.docSlug } };
1066
+ }
1067
+ if (!mounted) return void 0;
1068
+ return { options: mountOptionsOf(configs[mounted.index], mounted.mount), mount: mounted.mount, index: mounted.index };
889
1069
  },
890
1070
  async all() {
891
1071
  const out = [];
@@ -897,7 +1077,7 @@ function rootMounts(options) {
897
1077
  }
898
1078
  };
899
1079
  }
900
- function createRouter(options, make) {
1080
+ function createRouter(options, make, share) {
901
1081
  const mounts = rootMounts(options);
902
1082
  const handlers = /* @__PURE__ */ new Map();
903
1083
  return async function route(params) {
@@ -907,6 +1087,7 @@ function createRouter(options, make) {
907
1087
  if (path === void 0 || path === "/" || !segments) return void 0;
908
1088
  const hit = await mounts.locate(path);
909
1089
  if (!hit) return void 0;
1090
+ if ("share" in hit) return { handler: share(hit.share), params };
910
1091
  const { mount, index } = hit;
911
1092
  const id = `${index}|${mount.prefix}|${mount.defaultSection}`;
912
1093
  let handler = handlers.get(id);
@@ -918,15 +1099,15 @@ function createRouter(options, make) {
918
1099
  };
919
1100
  }
920
1101
  function hyleRootPage(options) {
921
- const route = createRouter(options, hylePage);
1102
+ const route = createRouter(options, hylePage, () => async () => notFound4());
922
1103
  return async function HyleRootPage({ params, searchParams }) {
923
1104
  const hit = await route(await params ?? {});
924
- if (!hit) notFound2();
1105
+ if (!hit) notFound4();
925
1106
  return hit.handler({ params: Promise.resolve(hit.params), ...searchParams ? { searchParams } : {} });
926
1107
  };
927
1108
  }
928
1109
  function hyleRootMetadata(options) {
929
- const route = createRouter(options, hyleMetadata);
1110
+ const route = createRouter(options, hyleMetadata, () => async () => hyleProtectedMetadata);
930
1111
  return async function generateMetadata({ params, searchParams }, parent) {
931
1112
  const hit = await route(await params ?? {});
932
1113
  return hit ? hit.handler({ params: Promise.resolve(hit.params), ...searchParams ? { searchParams } : {} }, parent) : {};
@@ -948,9 +1129,9 @@ function markdownRewritePath(pathname) {
948
1129
  if (!pathname.startsWith("/") || !pathname.endsWith(".md") || pathname.endsWith("/.md") || pathname.startsWith("/api/")) return void 0;
949
1130
  return MD_ROUTE_PREFIX + pathname.slice(0, -3);
950
1131
  }
951
- var reply = (body, status, headers = {}) => (
1132
+ var reply = (body, status, headers2 = {}) => (
952
1133
  // noindex on every answer: the .md twin must never compete with the page it mirrors.
953
- new Response(body, { status, headers: { "X-Robots-Tag": "noindex", ...headers } })
1134
+ new Response(body, { status, headers: { "X-Robots-Tag": "noindex", ...headers2 } })
954
1135
  );
955
1136
  function createMarkdownRoute(options) {
956
1137
  const mounts = rootMounts(options);
@@ -962,7 +1143,7 @@ function createMarkdownRoute(options) {
962
1143
  if (path === void 0 || path === "/") return reply(null, 404);
963
1144
  try {
964
1145
  const hit = await mounts.locate(path);
965
- if (!hit) return reply(null, 404);
1146
+ if (!hit || "share" in hit) return reply(null, 404);
966
1147
  const { locale, toHref } = routeContext({ ...hit.options, basePath: "", param: "path" }, params);
967
1148
  const result = await resolverFor(hit.options)(path, locale, void 0, void 0, void 0, "md");
968
1149
  if (result.kind === "article" && result.content.format === "md") {
@@ -1028,8 +1209,8 @@ var DEFAULT_TIMEOUT_MS2 = 3e4;
1028
1209
  var CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400";
1029
1210
  var PARTIAL_CACHE_CONTROL = "no-store";
1030
1211
  var SAFE_HEADERS = { "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" };
1031
- var PRIVATE_HEADERS = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Robots-Tag": "noindex, nofollow" };
1032
- var empty = (status, headers = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers } });
1212
+ var PRIVATE_HEADERS2 = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Robots-Tag": "noindex, nofollow" };
1213
+ var empty = (status, headers2 = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers2 } });
1033
1214
  var isSwitchedOff3 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
1034
1215
  var THEME_CACHE_CONTROL = "public, max-age=31536000, immutable";
1035
1216
  var OUTDATED_THEME_CACHE_CONTROL = "public, max-age=60";
@@ -1050,17 +1231,17 @@ async function serveTheme(client, scope, hash, timeoutMs, head) {
1050
1231
  const current = await sha256Hex(css);
1051
1232
  if (current !== hash && upstream.headers.get(THEME_SCOPE_HEADER) !== scope) return empty(404);
1052
1233
  const cache = current === hash ? THEME_CACHE_CONTROL : OUTDATED_THEME_CACHE_CONTROL;
1053
- const headers = { "Content-Type": "text/css; charset=utf-8", "Cache-Control": cache, ETag: `"${current}"`, ...SAFE_HEADERS };
1054
- return new Response(head ? null : css, { status: 200, headers });
1234
+ const headers2 = { "Content-Type": "text/css; charset=utf-8", "Cache-Control": cache, ETag: `"${current}"`, ...SAFE_HEADERS };
1235
+ return new Response(head ? null : css, { status: 200, headers: headers2 });
1055
1236
  } catch {
1056
1237
  return empty(502);
1057
1238
  }
1058
1239
  }
1059
- function protectedAccessFor(req, pageId) {
1060
- if (!PROTECTED_ID.test(pageId)) return void 0;
1061
- const name = protectedCookieName(pageId);
1240
+ async function protectedAccessFor(req, slug) {
1241
+ if (!PROTECTED_SLUG.test(slug)) return void 0;
1242
+ const name = await protectedCookieName(slug);
1062
1243
  const password = req.headers.get("cookie")?.split(";").map((c) => c.trim()).find((c) => c.startsWith(`${name}=`))?.slice(name.length + 1);
1063
- return password !== void 0 && PROTECTED_PASSWORD.test(password) ? { pageId, password } : void 0;
1244
+ return password !== void 0 && PROTECTED_PASSWORD.test(password) ? { slug, password } : void 0;
1064
1245
  }
1065
1246
  function capped(body, max) {
1066
1247
  let seen = 0;
@@ -1080,19 +1261,19 @@ function createAssetRoute(options) {
1080
1261
  async function serve(req, ctx, head) {
1081
1262
  const query = new URL(req.url).searchParams;
1082
1263
  const previewToken = query.get(PREVIEW_PARAM);
1083
- const pageId = query.get(PROTECTED_PARAM);
1084
- const res = await relay(req, ctx, head, previewToken, pageId);
1085
- if (previewToken !== null || pageId !== null) for (const [name, value] of Object.entries(PRIVATE_HEADERS)) res.headers.set(name, value);
1264
+ const slug = query.get(PROTECTED_PARAM);
1265
+ const res = await relay(req, ctx, head, previewToken, slug);
1266
+ if (previewToken !== null || slug !== null) for (const [name, value] of Object.entries(PRIVATE_HEADERS2)) res.headers.set(name, value);
1086
1267
  return res;
1087
1268
  }
1088
- async function relay(req, ctx, head, previewToken, pageId) {
1269
+ async function relay(req, ctx, head, previewToken, slug) {
1089
1270
  if (isSwitchedOff3((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return empty(404);
1090
1271
  const file = (await ctx.params).file;
1091
1272
  const [, themeScope, themeHash] = typeof file === "string" ? THEME_FILE.exec(file) ?? [] : [];
1092
1273
  if (typeof file !== "string" || !themeHash && !ASSET_FILE.test(file)) return empty(404);
1093
1274
  if (previewToken !== null && !PREVIEW_TOKEN.test(previewToken)) return empty(404);
1094
- const protectedAccess = pageId === null ? void 0 : protectedAccessFor(req, pageId);
1095
- if (pageId !== null && protectedAccess === void 0) return empty(404);
1275
+ const protectedAccess = slug === null ? void 0 : await protectedAccessFor(req, slug);
1276
+ if (slug !== null && protectedAccess === void 0) return empty(404);
1096
1277
  try {
1097
1278
  client ??= createHyleClient({ baseUrl: options.baseUrl?.trim() ?? "", token: options.token?.trim() ?? "", ...options.fetch ? { fetch: options.fetch } : {} });
1098
1279
  } catch {
@@ -1123,7 +1304,7 @@ function createAssetRoute(options) {
1123
1304
  const range = upstream.headers.get("content-range");
1124
1305
  return empty(416, range ? { "Content-Range": range } : {});
1125
1306
  }
1126
- if (upstream.status === 429 && (previewToken !== null || pageId !== null)) {
1307
+ if (upstream.status === 429 && (previewToken !== null || slug !== null)) {
1127
1308
  drop();
1128
1309
  const wait = upstream.headers.get("retry-after");
1129
1310
  return empty(429, wait ? { "Retry-After": wait } : {});
@@ -1135,22 +1316,22 @@ function createAssetRoute(options) {
1135
1316
  drop();
1136
1317
  return empty(502);
1137
1318
  }
1138
- const headers = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
1139
- if (etag) headers.set("ETag", etag);
1319
+ const headers2 = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
1320
+ if (etag) headers2.set("ETag", etag);
1140
1321
  const contentRange = upstream.headers.get("content-range");
1141
- if (upstream.status === 206 && contentRange) headers.set("Content-Range", contentRange);
1142
- if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers.set("Content-Length", String(length));
1322
+ if (upstream.status === 206 && contentRange) headers2.set("Content-Range", contentRange);
1323
+ if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers2.set("Content-Length", String(length));
1143
1324
  if (head) {
1144
1325
  drop();
1145
- return new Response(null, { status: upstream.status, headers });
1326
+ return new Response(null, { status: upstream.status, headers: headers2 });
1146
1327
  }
1147
- return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers });
1328
+ return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers: headers2 });
1148
1329
  }
1149
1330
  return { GET: (req, ctx) => serve(req, ctx, false), HEAD: (req, ctx) => serve(req, ctx, true) };
1150
1331
  }
1151
1332
 
1152
1333
  // src/next/og.tsx
1153
- import { jsx as jsx3, jsxs } from "react/jsx-runtime";
1334
+ import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
1154
1335
  var SIZE = { width: 1200, height: 630 };
1155
1336
  var MAX_TITLE = 140;
1156
1337
  function createOgImageRoute(options) {
@@ -1180,9 +1361,9 @@ function createOgImageRoute(options) {
1180
1361
  const chars = [...title];
1181
1362
  const shown = chars.length > MAX_TITLE ? `${chars.slice(0, MAX_TITLE - 1).join("")}\u2026` : title;
1182
1363
  return new ImageResponse(
1183
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", flexDirection: "column", justifyContent: "space-between", width: "100%", height: "100%", padding: 80, background: "#111827", color: "#ffffff" }, children: [
1184
- /* @__PURE__ */ jsx3("div", { style: { fontSize: 64, fontWeight: 700, lineHeight: 1.2 }, children: shown }),
1185
- options.siteName ? /* @__PURE__ */ jsx3("div", { style: { fontSize: 32, color: "#9ca3af" }, children: options.siteName }) : null
1364
+ /* @__PURE__ */ jsxs3("div", { style: { display: "flex", flexDirection: "column", justifyContent: "space-between", width: "100%", height: "100%", padding: 80, background: "#111827", color: "#ffffff" }, children: [
1365
+ /* @__PURE__ */ jsx5("div", { style: { fontSize: 64, fontWeight: 700, lineHeight: 1.2 }, children: shown }),
1366
+ options.siteName ? /* @__PURE__ */ jsx5("div", { style: { fontSize: 32, color: "#9ca3af" }, children: options.siteName }) : null
1186
1367
  ] }),
1187
1368
  // shortcut: @vercel/og fetches Google Fonts / emoji assets at render time for non-Latin titles and emoji (no switch to disable it), upgrade to a satori render with bundled fonts if a host needs zero egress.
1188
1369
  { ...SIZE, headers: { "cache-control": "public, max-age=3600, s-maxage=31536000, immutable" } }
@@ -1191,104 +1372,33 @@ function createOgImageRoute(options) {
1191
1372
  };
1192
1373
  }
1193
1374
 
1194
- // src/next/preview.tsx
1195
- import { notFound as notFound3 } from "next/navigation";
1196
- import { Fragment, jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
1197
- function drawArticle(article, options) {
1198
- const { locale } = article.publication;
1199
- const toHref = (sitePath, linkLocale = locale) => (options.localePrefix?.(linkLocale) ?? "") + sitePath;
1200
- const props = { article, components: options.components, slots: options.slots, locale, toHref };
1201
- return options.layout === "docs" ? /* @__PURE__ */ jsx4(DocsPage, { ...props }) : /* @__PURE__ */ jsx4(ArticlePage, { ...props });
1202
- }
1203
- var hylePreviewMetadata = { robots: { index: false, follow: false }, referrer: "no-referrer" };
1204
- var BANNER = {
1205
- position: "sticky",
1206
- top: 0,
1207
- zIndex: 2147483647,
1208
- padding: "8px 16px",
1209
- background: "#fde047",
1210
- color: "#1a1a1a",
1211
- font: "600 14px/1.4 system-ui, sans-serif",
1212
- textAlign: "center"
1213
- };
1214
- function hylePreviewPage(options) {
1215
- return async function HylePreviewPage({ searchParams }) {
1216
- const { token } = await searchParams ?? {};
1217
- const result = await createHyleClient(options).preview(typeof token === "string" ? token : void 0);
1218
- if (result.kind !== "preview") notFound3();
1219
- return /* @__PURE__ */ jsxs2(Fragment, { children: [
1220
- /* @__PURE__ */ jsx4("meta", { name: "robots", content: "noindex, nofollow" }),
1221
- /* @__PURE__ */ jsx4("meta", { name: "referrer", content: "no-referrer" }),
1222
- /* @__PURE__ */ jsx4("div", { role: "status", style: BANNER, children: "Unpublished draft preview" }),
1223
- drawArticle(result.article, options)
1224
- ] });
1375
+ // src/next/protected-view.ts
1376
+ import { headers } from "next/headers";
1377
+ import { notFound as notFound5 } from "next/navigation";
1378
+ import { NextResponse } from "next/server";
1379
+ var VIEW_PATH = "/hyle-protected/view";
1380
+ var MOUNTS_SNAPSHOT_MS = 3e4;
1381
+ var DEFAULT_LOOKUP_TIMEOUT_MS = 1500;
1382
+ var SHARE_PATH = /^\/[a-z0-9-]+(?:\/[a-z0-9-]+){0,4}$/;
1383
+ function hyleProtectedProxy(options, { lookupTimeoutMs = DEFAULT_LOOKUP_TIMEOUT_MS } = {}) {
1384
+ const mounts = rootMounts(options, MOUNTS_SNAPSHOT_MS);
1385
+ return async function protectedProxy(req) {
1386
+ const path = req.nextUrl.pathname;
1387
+ if (!SHARE_PATH.test(path)) return void 0;
1388
+ let timer;
1389
+ const deadline = new Promise((resolve) => timer = setTimeout(resolve, lookupTimeoutMs));
1390
+ const hit = await Promise.race([mounts.locate(path).catch(() => void 0), deadline]).finally(() => clearTimeout(timer));
1391
+ return hit && "share" in hit ? NextResponse.rewrite(new URL(`${VIEW_PATH}${path}`, req.url)) : void 0;
1225
1392
  };
1226
1393
  }
1227
-
1228
- // src/next/protected.tsx
1229
- import { cookies } from "next/headers";
1230
- import { notFound as notFound4 } from "next/navigation";
1231
- import { Fragment as Fragment2, jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
1232
- var hyleProtectedMetadata = { robots: { index: false, follow: false }, referrer: "same-origin" };
1233
- var COOKIE_MAX_AGE_SECONDS = 12 * 60 * 60;
1234
- var UNLOCK_MAX_BYTES = 1024;
1235
- var PRIVATE_HEADERS2 = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Robots-Tag": "noindex, nofollow" };
1236
- var PASSWORD_FIELD = "hyle-protected-password";
1237
- var ERROR_ID = "hyle-protected-error";
1238
- function PasswordForm({ pageId, failed }) {
1239
- return /* @__PURE__ */ jsxs3("main", { children: [
1240
- /* @__PURE__ */ jsx5("h1", { children: "Protected page" }),
1241
- /* @__PURE__ */ jsxs3("form", { method: "post", action: `/p/${pageId}/unlock`, autoComplete: "off", children: [
1242
- /* @__PURE__ */ jsx5("label", { htmlFor: PASSWORD_FIELD, children: "Password" }),
1243
- /* @__PURE__ */ jsx5(
1244
- "input",
1245
- {
1246
- id: PASSWORD_FIELD,
1247
- name: "password",
1248
- type: "password",
1249
- autoComplete: "off",
1250
- spellCheck: false,
1251
- required: true,
1252
- pattern: "[A-Za-z0-9]{16}",
1253
- title: "16 letters or digits",
1254
- "aria-invalid": failed || void 0,
1255
- "aria-describedby": failed ? ERROR_ID : void 0
1256
- }
1257
- ),
1258
- /* @__PURE__ */ jsx5("button", { type: "submit", children: "Open" }),
1259
- failed ? /* @__PURE__ */ jsx5("p", { id: ERROR_ID, role: "alert", children: "Wrong or expired password." }) : null
1260
- ] })
1261
- ] });
1262
- }
1263
- function hyleProtectedPage(options) {
1394
+ var forwardedClientIp = (h) => h.get("x-forwarded-for")?.split(",")[0]?.trim() || h.get("x-real-ip")?.trim() || void 0;
1395
+ function hyleProtectedPage(options, { clientIp = forwardedClientIp } = {}) {
1396
+ const mounts = rootMounts(options);
1264
1397
  return async function HyleProtectedPage({ params }) {
1265
- const { id } = await params;
1266
- if (typeof id !== "string" || !PROTECTED_ID.test(id)) notFound4();
1267
- const password = (await cookies()).get(protectedCookieName(id))?.value;
1268
- const result = password === void 0 ? void 0 : await createHyleClient(options).protected(id, password);
1269
- if (result?.kind === "disabled") notFound4();
1270
- return /* @__PURE__ */ jsxs3(Fragment2, { children: [
1271
- /* @__PURE__ */ jsx5("meta", { name: "robots", content: "noindex, nofollow" }),
1272
- /* @__PURE__ */ jsx5("meta", { name: "referrer", content: "same-origin" }),
1273
- result?.kind === "protected" ? drawArticle(result.article, options) : /* @__PURE__ */ jsx5(PasswordForm, { pageId: id, failed: result !== void 0 })
1274
- ] });
1275
- };
1276
- }
1277
- function createProtectedUnlockRoute() {
1278
- return {
1279
- async POST(req, ctx) {
1280
- const { id } = await ctx.params;
1281
- if (typeof id !== "string" || !PROTECTED_ID.test(id)) return new Response(null, { status: 404, headers: PRIVATE_HEADERS2 });
1282
- const site = req.headers.get("sec-fetch-site");
1283
- if (site === null ? originMismatch(req) : site !== "same-origin") return new Response(null, { status: 403, headers: PRIVATE_HEADERS2 });
1284
- if (!/^application\/x-www-form-urlencoded(\s*;|$)/i.test(req.headers.get("content-type") ?? "")) return new Response(null, { status: 415, headers: PRIVATE_HEADERS2 });
1285
- if (Number(req.headers.get("content-length")) > UNLOCK_MAX_BYTES) return new Response(null, { status: 413, headers: PRIVATE_HEADERS2 });
1286
- const form = await readCapped(new Response(req.body), UNLOCK_MAX_BYTES).catch(() => void 0);
1287
- if (form === void 0) return new Response(null, { status: 413, headers: PRIVATE_HEADERS2 });
1288
- const password = new URLSearchParams(form).get("password") ?? "";
1289
- const cookie = PROTECTED_PASSWORD.test(password) ? { "Set-Cookie": `${protectedCookieName(id)}=${password}; Max-Age=${COOKIE_MAX_AGE_SECONDS}; Path=/; HttpOnly; Secure; SameSite=Lax` } : {};
1290
- return new Response(null, { status: 303, headers: { ...PRIVATE_HEADERS2, Location: `/p/${id}`, ...cookie } });
1291
- }
1398
+ const path = `/${((await params).path ?? []).join("/")}`;
1399
+ const hit = SHARE_PATH.test(path) ? await mounts.locate(path) : void 0;
1400
+ if (!hit || !("share" in hit)) notFound5();
1401
+ return drawProtectedShare(hit.share.config, hit.share.slug, hit.share.docSlug, clientIp(await headers()));
1292
1402
  };
1293
1403
  }
1294
1404
  export {
@@ -1314,6 +1424,7 @@ export {
1314
1424
  hylePreviewPage,
1315
1425
  hyleProtectedMetadata,
1316
1426
  hyleProtectedPage,
1427
+ hyleProtectedProxy,
1317
1428
  hyleRootMetadata,
1318
1429
  hyleRootPage,
1319
1430
  hyleRootSitemap,