@redocly/revel 0.141.0-next.0 → 0.141.0-next.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +171 -0
- package/dist/cli/develop.js +1 -1
- package/dist/cli/utils/react-pages-check.d.ts +11 -0
- package/dist/cli/utils/react-pages-check.js +1 -0
- package/dist/client/App.js +1 -1
- package/dist/client/app/Sidebar/useSidebarItems.js +1 -1
- package/dist/client/app/hooks/useBanner.js +1 -1
- package/dist/client/app/hooks/useUserClaims.js +1 -1
- package/dist/client/app/webmcp/tools/shared.d.ts +2 -3
- package/dist/client/app/webmcp/tools/shared.js +1 -1
- package/dist/client/runtime/errors/page-async-component-error.d.ts +4 -0
- package/dist/client/runtime/errors/page-async-component-error.js +1 -0
- package/dist/client/runtime/loader.js +1 -1
- package/dist/constants/common.d.ts +2 -0
- package/dist/constants/common.js +1 -1
- package/dist/constants/l10n/langs/ar.js +1 -1
- package/dist/constants/l10n/langs/de.js +1 -1
- package/dist/constants/l10n/langs/en.js +1 -1
- package/dist/constants/l10n/langs/es.js +1 -1
- package/dist/constants/l10n/langs/fr.js +1 -1
- package/dist/constants/l10n/langs/hi.js +1 -1
- package/dist/constants/l10n/langs/it.js +1 -1
- package/dist/constants/l10n/langs/ja.js +1 -1
- package/dist/constants/l10n/langs/ko.js +1 -1
- package/dist/constants/l10n/langs/pl.js +1 -1
- package/dist/constants/l10n/langs/pt-BR.js +1 -1
- package/dist/constants/l10n/langs/pt.js +1 -1
- package/dist/constants/l10n/langs/ru.js +1 -1
- package/dist/constants/l10n/langs/uk.js +1 -1
- package/dist/constants/l10n/langs/zh.js +1 -1
- package/dist/markdoc/nodes/table.js +1 -1
- package/dist/markdoc/tags/index.d.ts +6 -18
- package/dist/server/api-routes/run-api-routes-worker.js +1 -1
- package/dist/server/constants/entitlements.js +1 -1
- package/dist/server/entitlements/entitlements-provider.d.ts +4 -0
- package/dist/server/entitlements/entitlements-provider.js +1 -1
- package/dist/server/entitlements/plan-denied-markdoc-tags.d.ts +6 -0
- package/dist/server/entitlements/plan-denied-markdoc-tags.js +1 -0
- package/dist/server/fs/fast-mtime.js +3 -3
- package/dist/server/fs/fs.js +1 -1
- package/dist/server/plugins/api-docs/index.js +1 -1
- package/dist/server/plugins/api-docs/options.js +1 -1
- package/dist/server/plugins/api-docs/search/get-ai-search-documents.js +64 -64
- package/dist/server/plugins/api-docs/spec-download.api.js +1 -1
- package/dist/server/plugins/config-parser/format-error.js +2 -2
- package/dist/server/plugins/config-parser/loaders/utils/read-and-validate-config.js +1 -1
- package/dist/server/plugins/markdown/attribute-resolvers/resolve-code-snippet-from-file.js +7 -6
- package/dist/server/plugins/markdown/compiler.d.ts +3 -3
- package/dist/server/plugins/markdown/compiler.js +1 -1
- package/dist/server/plugins/markdown/index.js +1 -1
- package/dist/server/plugins/markdown/markdoc/markdoc-options.d.ts +2 -0
- package/dist/server/plugins/markdown/markdoc/markdoc-options.js +1 -1
- package/dist/server/plugins/mcp/custom-tools/scan-custom-tools.d.ts +4 -1
- package/dist/server/plugins/mcp/custom-tools/scan-custom-tools.js +1 -1
- package/dist/server/plugins/mcp/index.js +1 -1
- package/dist/server/plugins/mcp/types.d.ts +1 -0
- package/dist/server/plugins/pages/index.js +1 -1
- package/dist/server/plugins/pages/validators/validate-react-pages.d.ts +8 -1
- package/dist/server/plugins/pages/validators/validate-react-pages.js +1 -1
- package/dist/server/plugins/search/ai-indexer/prepare-semantic-documents.js +1 -1
- package/dist/server/plugins/search/llmstxt/create-llms-txt-generator.js +1 -1
- package/dist/server/plugins/search/llmstxt/index.js +4 -4
- package/dist/server/ssr/server-side-props/get-default-static-props.d.ts +1 -0
- package/dist/server/ssr/utils.js +11 -9
- package/dist/server/store.d.ts +1 -0
- package/dist/server/store.js +1 -1
- package/dist/server/types/plugins/common.d.ts +13 -1
- package/dist/server/types/web-server.d.ts +5 -0
- package/dist/server/utils/errors.d.ts +2 -1
- package/dist/server/utils/errors.js +1 -1
- package/dist/server/utils/llmstxt/resolve-llms-txt-md.d.ts +5 -0
- package/dist/server/utils/llmstxt/resolve-llms-txt-md.js +1 -1
- package/dist/server/web-server/auth.js +3 -3
- package/dist/server/web-server/routes/dynamic-route.js +1 -1
- package/dist/server/web-server/routes/error.js +1 -1
- package/dist/server/web-server/routes/helpers/process-redirects.d.ts +6 -4
- package/dist/server/web-server/routes/helpers/process-redirects.js +1 -1
- package/dist/server/web-server/routes/index.js +1 -1
- package/dist/server/web-server/routes/page-data.d.ts +2 -1
- package/dist/server/web-server/routes/page-data.js +1 -1
- package/dist/server/web-server/utils.d.ts +1 -1
- package/dist/server/web-server/utils.js +1 -1
- package/dist/types/entitlements.d.ts +4 -0
- package/package.json +10 -10
- package/dist/server/utils/llmstxt/get-llms-txt-md-path-by-slug.d.ts +0 -19
- package/dist/server/utils/llmstxt/get-llms-txt-md-path-by-slug.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import u from"node:path";import{existsSync as O}from"node:fs";import{writeFile as h,access as y,rm as v,constants as b}from"fs/promises";import{REDOCLY_TEAMS_RBAC as N}from"@redocly/config";import{DEFAULT_LOCALE_PLACEHOLDER as S}from"../../../../constants/common.js";import{AI_INDEX_EXPORT_FOLDER as X}from"../../../constants/plugins/search.js";import{LLMS_TXT_FILE_NAME as $}from"../../../constants/common.js";import{envConfig as j}from"../../../config/env-config.js";import{logger as n}from"../../../tools/notifiers/logger.js";import{shaHexShort as G}from"../../../utils/crypto/sha-hex-short.js";import{promiseMapLimit as D}from"../../../utils/async/promise-map-limit.js";import{getMarkdownCopyPath as U}from"@redocly/theme/core/utils";import{validateLLMsTxtConfig as k,generateLLMsTxt as B}from"../llmstxt/index.js";import{buildPageLlmsTxtMd as H}from"../llmstxt/build-page-llms-txt-md.js";import{getLlmsTxtExcludeMatcher as J}from"../llmstxt/get-llms-txt-exclude-matcher.js";import{isIncludedInLlmsTxt as K}from"../llmstxt/is-included-in-llms-txt.js";import{getRouteStaticData as V}from"../../../utils/get-route-static-data.js";import{getRouteAiDocumentsStore as W}from"../../../utils/get-route-ai-documents-store.js";import{ensureDir as R}from"../../../utils/fs.js";import{extractTeamsFromScopeItems as Y,getRbacTeamsListForResource as q}from"../../../utils/rbac.js";const _=20,P="llms.txt:";async function ht(t,c,{embeddingsEnabled:e,writeLlmstxtFiles:l}){const m=u.join(t.outdir,$);if(!l){try{await y(m,b.W_OK),await v(m)}catch{}if(!e)return}e&&n.info("Preparing semantic documents..."),l&&n.info(`${P} Generating llms.txt files...`);const g=n.startTiming(),s=n.startTiming(),i=t.getGlobalConfig("seo"),f=i?.llmstxt,T=u.resolve(t.outdir,X),p=t.getConfig(),A=p.access?.rbac??{},C=t.getAllRoutes(),M=p?.l10n?.defaultLocale||p?.i18n?.defaultLocale||S,w=J(i),L=[];if(await D(C,_,async o=>{if(o.excludeFromSearch)return;const E=await V(o,t),x=await W(o,E,c,t);if(x){if(l)for(const r of await x.getLLMsTxts()){if(w(r.fsPath))continue;const d=U(r.slug),a=u.join(t.outdir,d);R(a),await h(a,H(r,i)),K(r,o,p)&&L.push(r)}if(e&&j.isBuildMode){const r=await x.getSearchDocuments();if(!r.length)return;const d=z(o,A),a=o.versions?.find(({active:F})=>F),I=a&&{folder:a.folderId,label:a.label,default:a.default};await Q(r,o.fsPath,d,T,M,I)}}}),e&&n.infoTime(s,"Semantic search documents prepared"),L.length)try{k(f);const o=await B(L,f,{title:i?.title,description:i?.description,siteUrl:i?.siteUrl},c);R(m),await h(m,o),n.infoTime(g,`${P} files generated`)}catch(o){n.error(`${P} Failed to generate llms.txt file. ${o.message}`)}}function z(t,c){const e=Y(t?.[N]);return e?.length?e:q(t,c)}async function Q(t,c,e,l,m,g){await D(t,_,async s=>{const i=`${G(c+s.content)}.json`,f=R(u.join(l,i)),T=s.locale===S?m:s.locale;O(f)||await h(f,JSON.stringify({...s,rbacTeams:s.rbacTeams??e??[],version:g,locale:T}),"utf-8")})}export{ht as prepareSemanticDocuments};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import m from"node:path";import{logger as p}from"../../../tools/notifiers/logger.js";import{promiseMapLimit as w}from"../../../utils/async/promise-map-limit.js";import{getMarkdownCopyPath as R,getSlugFromMarkdownCopyPath as x}from"@redocly/theme/core/utils";import{getRouteStaticData as S}from"../../../utils/get-route-static-data.js";import{getRouteAiDocumentsStore as T}from"../../../utils/get-route-ai-documents-store.js";import{generateLLMsTxt as C,validateLLMsTxtConfig as M}from"./index.js";import{buildPageLlmsTxtMd as P}from"./build-page-llms-txt-md.js";import{getLlmsTxtExcludeMatcher as a}from"./get-llms-txt-exclude-matcher.js";import{isIncludedInLlmsTxt as y}from"./is-included-in-llms-txt.js";import{EntitlementsProvider as A}from"../../../entitlements/entitlements-provider.js";const E=20;function W(r,c){const u=new WeakMap,l=()=>{const e=r.getGlobalConfig("seo");return A.instance().canAccessFeature("seo")===!0&&r.getConfig().search?.hide!==!0&&e?.llmstxt?.hide!==!0},L=async e=>{if(e.excludeFromSearch)return[];const t=r,n=await S(e,t);return await(await T(e,n,c,t))?.getLLMsTxts()??[]},d=e=>{const t=u.get(e);if(t)return t;const n=L(e).catch(o=>(u.delete(e),p.warn(`Failed to generate Markdown for LLMs of "${e.slug}". ${o}`),[]));return u.set(e,n),n},h=e=>{const t=x(e);if(t===null||R(t)!==e)return;const n=r.getRouteBySlug(t,{followRedirect:!1});if(n?.getAiDocumentsStore)return n;for(let o=m.posix.dirname(t);o.startsWith("/");){const i=r.getRouteBySlug(o,{followRedirect:!1});if(i?.hasClientRoutes&&i.getAiDocumentsStore)return i;const s=m.posix.dirname(o);if(s===o)return;o=s}},f=e=>{if(!l())return;const t=h(e);if(!t||t.excludeFromSearch)return;const n=a(r.getGlobalConfig("seo"));return t.fsPath!==void 0&&n(t.fsPath)?void 0:t};return{hasPageMarkdown(e){return f(e)!==void 0},async getPageMarkdown(e){const t=f(e);if(!t)return;const n=r.getGlobalConfig("seo"),o=a(n),i=x(e),s=(await d(t)).find(g=>g.slug===i&&!o(g.fsPath));if(s)return{route:t,content:P(s,n)}},async getLlmsTxt(){if(!l())return;const e=r.getConfig(),t=r.getGlobalConfig("seo"),n=a(t),o=[];if(await w(r.getAllRoutes(),E,async i=>{for(const s of await d(i))!n(s.fsPath)&&y(s,i,e)&&o.push(s)}),!!o.length)try{return M(t?.llmstxt),await C(o,t?.llmstxt,{title:t?.title,description:t?.description,siteUrl:t?.siteUrl},c)}catch(i){p.error(`Failed to generate llms.txt. ${i}`);return}}}}export{W as createLlmsTxtGenerator};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import d from"picomatch";import{dirname as T,resolve as $}from"node:path";import{access as
|
|
1
|
+
import d from"picomatch";import{dirname as T,resolve as $}from"node:path";import{access as w,readFile as x,constants as E}from"fs/promises";import{removeTrailingSlash as F}from"../../../../utils/url/remove-trailing-slash.js";import{logger as U}from"../../../tools/notifiers/logger.js";import{getMarkdownCopyPath as g,withPathPrefix as y}from"@redocly/theme/core/utils";import{envConfig as I}from"../../../config/env-config.js";const a="llms.txt",u="Table of contents";async function v(e,i,n={title:a,description:void 0},r){if(!i)return{title:n.title||a,description:n.description,details:void 0,sections:[{title:u,description:void 0,llmstxts:e}]};const s=i.title||n.title||a,l=i.description||n.description,t=await D(i,r),o=i.sections?.map(c=>{const{title:f,description:h,excludeFiles:m,includeFiles:L}=c,P=p(e,{excludeFiles:m,includeFiles:L});return{title:f,description:h,llmstxts:P}});return{title:s,description:l,details:t,sections:o||[{title:u,description:void 0,llmstxts:p(e,{includeFiles:["**/*"],excludeFiles:[]})}]}}async function D(e,i){const n=await i.getConfig();if(e?.details?.path&&n.configPath)try{const r=i.fs.getFileInfo(n.configPath);if(!r)throw new Error(`Config file ${n.configPath} not found`);const s=$(i.fs.cwd,T(r.relativePath),e.details.path);return await w(s,E.R_OK),x(s,"utf-8")}catch{throw new Error(`${e.details.path} is not accessible`)}if(e?.details?.content)return e.details.content}function p(e,i){const{excludeFiles:n,includeFiles:r}=i,s=n?.map(t=>d(t)),l=r?.map(t=>d(t));return e.filter(t=>s?.some(c=>c(t.fsPath))?!1:l?.some(c=>c(t.fsPath)))}async function b(e,i,n={title:a,description:void 0,siteUrl:void 0},r){const s=await v(e,i,n,r),l=n.siteUrl,t=[`# ${s.title}
|
|
2
2
|
|
|
3
3
|
`];return s.description&&t.push(`> ${s.description}
|
|
4
4
|
|
|
5
5
|
`),s.details&&t.push(`${s.details}
|
|
6
6
|
|
|
7
|
-
`),s.sections.forEach(o=>{if(!o.llmstxts.length){
|
|
7
|
+
`),s.sections.forEach(o=>{if(!o.llmstxts.length){U.warn(`llms.txt: No links found for section "${o.title}". Please check the includeFiles/excludeFiles patterns.`);return}t.push(`## ${o.title}
|
|
8
8
|
`),o.description?t.push(`${o.description.replace(/(?<!\n)\n+$/,"")}
|
|
9
9
|
|
|
10
10
|
`):t.push(`
|
|
11
|
-
`),o.llmstxts.forEach(c=>{t.push(` - ${M({title:c.title,description:c.description,slug:
|
|
12
|
-
`)}),t.join("")}function M({title:e,description:i,slug:n,siteUrl:r}){const l=`${
|
|
11
|
+
`),o.llmstxts.forEach(c=>{t.push(` - ${M({title:c.title,description:c.description,slug:g(c.slug),siteUrl:l})}`)}),t.push(`
|
|
12
|
+
`)}),t.join("")}function M({title:e,description:i,slug:n,siteUrl:r}){const l=`${F(r?.trim()||I.REDOCLY_PUBLIC_URL||"")}${encodeURI(y(n))}`,t=i?.replace(/\s+/g," ").trim();return`[${e}](${l})${t?`: ${t}`:""}
|
|
13
13
|
`}function j(e){if(e?.details?.path&&e?.details?.content)throw new Error('"details.path" and "details.content" are mutually exclusive. Please use only one of them.')}export{b as generateLLMsTxt,M as llmsTxtLink,j as validateLLMsTxtConfig};
|
|
@@ -5,6 +5,7 @@ export declare function getDefaultStaticProps({ staticData, variables, }: {
|
|
|
5
5
|
}): {
|
|
6
6
|
metadata?: Record<string, unknown>;
|
|
7
7
|
seo?: import("@redocly/config").SeoConfig;
|
|
8
|
+
markdownUrl?: string;
|
|
8
9
|
sharedDataIds?: Record<string, string>;
|
|
9
10
|
frontmatter?: Omit<import("@redocly/config").PageProps, 'frontmatter'> & {
|
|
10
11
|
settings?: any;
|
package/dist/server/ssr/utils.js
CHANGED
|
@@ -1,21 +1,23 @@
|
|
|
1
|
-
import{pathToFileURL as u}from"url";import{removeTrailingSlash as p}from"../../utils/url/remove-trailing-slash.js";import{slash as f}from"../../utils/path/slash.js";import{getClientPageDataUrl as h}from"../../utils/url/get-client-page-data-url.js";import{getSharedDataFetchUrl as g}from"../../utils/url/get-shared-data-fetch-url.js";import{DEFAULT_COLOR_MODES as l}from"@redocly/theme/core/constants";import{envConfig as m}from"../config/env-config.js";function q(t){const o=t?.colorMode,{modes:e=[l.LIGHT,l.DARK],hide:r,ignoreDetection:
|
|
1
|
+
import{pathToFileURL as u}from"url";import{removeTrailingSlash as p}from"../../utils/url/remove-trailing-slash.js";import{slash as f}from"../../utils/path/slash.js";import{getClientPageDataUrl as h}from"../../utils/url/get-client-page-data-url.js";import{getSharedDataFetchUrl as g}from"../../utils/url/get-shared-data-fetch-url.js";import{DEFAULT_COLOR_MODES as l}from"@redocly/theme/core/constants";import{envConfig as m}from"../config/env-config.js";function q(t){const o=t?.colorMode,{modes:e=[l.LIGHT,l.DARK],hide:r,ignoreDetection:n}=o||{},a=e&&`'${e[0]}'`,s=e?.[0],d=e?.some(i=>i===s)?`'${s}'`:void 0;return r||!a?"":`
|
|
2
2
|
<script>
|
|
3
3
|
if(window&&document.documentElement)
|
|
4
4
|
{
|
|
5
5
|
const q=new URLSearchParams(window.location.search).get("colorSchema");
|
|
6
|
-
|
|
6
|
+
let s;
|
|
7
|
+
try { s=window.localStorage.getItem("colorSchema"); } catch(_) {}
|
|
8
|
+
const e=q || s;
|
|
7
9
|
if(e) {
|
|
8
|
-
const modeToSet = [${e.map(
|
|
9
|
-
${
|
|
10
|
+
const modeToSet = [${e.map(i=>`'${i}'`)}].some((mode) => mode === e) ? e : 'light';
|
|
11
|
+
${c("modeToSet",e)}
|
|
10
12
|
} else {
|
|
11
13
|
if (window.matchMedia) {
|
|
12
|
-
${S(
|
|
14
|
+
${S(n,d,a,e)}
|
|
13
15
|
} else {
|
|
14
|
-
${
|
|
16
|
+
${c(a,e)}
|
|
15
17
|
}
|
|
16
18
|
}
|
|
17
19
|
}
|
|
18
|
-
</script>`}function S(t,o,e,r=["light","dark"]){return t?o?
|
|
20
|
+
</script>`}function S(t,o,e,r=["light","dark"]){return t?o?c(o,r):e?c(e,r):"return":$(o,r)}function c(t=`'${l.LIGHT}'`,o=["light","dark"]){return`(function() {
|
|
19
21
|
var root = document.documentElement;
|
|
20
22
|
var modes = [${o.map(r=>`'${r}'`).join(", ")}];
|
|
21
23
|
var value = ${t};
|
|
@@ -23,7 +25,7 @@ import{pathToFileURL as u}from"url";import{removeTrailingSlash as p}from"../../u
|
|
|
23
25
|
root.classList.remove(className);
|
|
24
26
|
});
|
|
25
27
|
root.classList.add(value);
|
|
26
|
-
})();`}function $(t,o=["light","dark"]){const e=o.map(
|
|
28
|
+
})();`}function $(t,o=["light","dark"]){const e=o.map(n=>`'${n}'`).join(", "),r=t?`root.classList.add(${t});`:"";return`(function() {
|
|
27
29
|
var root = document.documentElement;
|
|
28
30
|
var modes = [${e}];
|
|
29
31
|
modes.forEach(function(className) {
|
|
@@ -36,4 +38,4 @@ import{pathToFileURL as u}from"url";import{removeTrailingSlash as p}from"../../u
|
|
|
36
38
|
}${r?` else {
|
|
37
39
|
${r}
|
|
38
40
|
}`:""}
|
|
39
|
-
})();`}async function T(t){try{return m.isRuntimeMode?await import("@portal/server-props"):await import(u(`${f(t)}/server-props-entry.js`)+"?"+new Date)}catch{return{}}}function
|
|
41
|
+
})();`}async function T(t){try{return m.isRuntimeMode?await import("@portal/server-props"):await import(u(`${f(t)}/server-props-entry.js`)+"?"+new Date)}catch{return{}}}function y(t){const o=t.split("/").map(encodeURIComponent).join("/"),e=o==="/"?o:p(o);return`<link rel="preload" as="fetch" crossorigin="anonymous" href="${h(e)}" />`}function j(t={}){const o=new Set;for(const e of Object.values(t))e&&o.add(g(e,m.isDevelopMode));return[...o].map(e=>`<link rel="preload" as="fetch" crossorigin="anonymous" href="${w(e)}" />`)}function w(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}const x=(t,o)=>{if(!o)return{params:[],queries:{}};const e=t.slug||"",n=o.req.path.split(e.endsWith("/")?e:`${e}/`)[1]||"",a=o.req.query(),s=n.replace("data.json","");return!s||s==="/"?{params:[],queries:a}:{params:s.split("/").filter(Boolean),queries:a}};export{q as detectColorSchemaScript,y as generatePreloadPageData,j as generatePreloadSharedData,x as getPathParams,T as importServerProps};
|
package/dist/server/store.d.ts
CHANGED
|
@@ -147,6 +147,7 @@ export declare class Store {
|
|
|
147
147
|
getRequestHandler: (id: string) => string | undefined;
|
|
148
148
|
createTemplate: (id: string, importPath: string) => string;
|
|
149
149
|
addBrowserPlugin: (importPath: string) => void;
|
|
150
|
+
copyAsset: (src: string, fromFileRelativePath: string) => Promise<string | null>;
|
|
150
151
|
createRequestHandler: (id: string, importPath: string) => string;
|
|
151
152
|
clearRequestHandlersByPrefix: (prefix: string) => void;
|
|
152
153
|
registerServerPropsGetter: (id: string, importPath: string) => string;
|
package/dist/server/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import k from"@redocly/markdoc";import{writeFileSync as S}from"node:fs";import{readFile as D}from"node:fs/promises";import{join as g}from"node:path";import{parseAndResolveMarkdoc as F}from"./plugins/markdown/compiler.js";import{getPathnameForLocale as L}from"@redocly/theme/core/utils";import{DEFAULT_LOCALE_PLACEHOLDER as m}from"../constants/common.js";import{DEFAULT_TITLE as H,MARKDOC_PARTIALS_DATA_KEY as y,MARKDOC_PARTIALS_DEPS_KEY as G}from"./constants/common.js";import{GATED_MARKDOC_TAGS as v}from"./constants/entitlements.js";import{isObject as _}from"../utils/guards/is-object.js";import{mapObject as N}from"../utils/object/map-object.js";import{getValueDeep as w}from"../utils/object/get-value-deep.js";import{removeTrailingSlash as B}from"../utils/url/remove-trailing-slash.js";import{normalizeRouteSlug as d}from"../utils/path/normalize-route-slug.js";import{isLocalLink as E}from"../utils/path/is-local-link.js";import{reporter as P}from"./tools/notifiers/reporter.js";import{logger as u}from"./tools/notifiers/logger.js";import{sha1 as I}from"./utils/crypto/sha1.js";import{envConfig as j,setEnv as V}from"./config/env-config.js";import{KvService as q}from"./persistence/kv/services/kv-service.js";import{SandboxContext as J}from"./utils/sandbox-context.js";import{isAllowedEnv as U}from"./utils/envs/get-api-route-allowed-env-variables.js";import{ensureDir as x,writeSharedData as K}from"./utils/index.js";import{renderComponents as W}from"./ssr/render.js";import{readStaticData as $,writeStaticData as z}from"./utils/static-data.js";import{getMarkdocOptions as Y}from"./plugins/markdown/markdoc/markdoc-options.js";import{EntitlementsProvider as C}from"./entitlements/entitlements-provider.js";import{isRouteReserved as Z}from"./plugins/get-reserved-routes.js";import{isL10nPath as Q}from"./fs/utils/is-l10n-path.js";import{resolveGlobMapValue as X}from"./utils/globs.js";import{createDefaultStoreConfig as ee,resolveConfigEntries as te,resolveStoreConfig as se}from"./store-config.js";import{findRedirect as re}from"./utils/redirects/find-redirect.js";import{followRedirectChain as ae}from"./utils/redirects/follow-redirect-chain.js";import{addWildcardRedirectToTree as oe}from"./utils/redirects/add-wildcard-redirect-to-tree.js";import{telemetryTraceStep as ie}from"../cli/telemetry/helpers/trace-step.js";const A={routesBySlug:"map",staticFilePaths:"object",apiRoutes:"object",middleware:"object",routesByFsPath:"map",routesSharedData:"map",globalData:"object",ssr:"object",searchFacets:"map",routesPartials:"map",mcpToolHandlers:"map",skills:"map",devLogin:"object"},b="store.json",O="store-config.json",T="PLAN_GATES",ne=["OAUTH_CLIENT_ID","OAUTH_CLIENT_SECRET","ORGANIZATION_SLUG","ORGANIZATION_ID","ORG_ID"],Ue="userDefinedApiFunctions";class R{routesBySlug=new Map;routeAliases=new Map;staticFilePaths={};replacedEnvVars={};unsetEnvVars=new Set;lifecycleContext;newRoutes=[];#t={};routesByFsPath=new Map;apiRoutes=[];middleware=[];routesSharedData=new Map;sharedDataDeps=new Map;sharedDataMarkdocComponents=new Map;routesDynamicComponents=new Map;routesPartials=new Map;ssr={preBodyTags:[],postBodyTags:[],headTags:[]};searchFacets=new Map;searchEngine;templates=new Map;browserPlugins=new Set;apiRoutesRequestHandlers=new Map;mcpToolHandlers=new Map;skills=new Map;serverPropsGetters=new Map;pagePropsGetters=new Map;listeners=new Map;globalData={};devLogin=!1;#o=void 0;config=ee();configFile;#i;serverMode;serverOutDir;outdir;buildRevision=0;hasSitemap=!1;compilationErrors=[];#n;userCodeReady;#s=Promise.resolve();#l;#c=Promise.resolve();#d;#h=Promise.resolve();#u;#e=!1;#r=0;#f=0;#a=new Map;constructor({outdir:e,contentDir:t,serverMode:s=!1,serverOutDir:r}){this.#i=t,this.outdir=e,this.serverMode=s,this.serverOutDir=r,J.register({serverOutDir:r,readRoots:[e,process.cwd()]}),this.userCodeReady=new Promise(a=>{this.#n=a})}on(e,t){const s=this.listeners.get(e);s?s.add(t):this.listeners.set(e,new Set([t]))}queueEvent=(e,t,...s)=>{this.#a.set(e+String(t),[e,t,...s])};runListeners=(e,t,...s)=>{for(const r of this.listeners.get(e)||new Set)t?r(t,...s):r(...s)};startPluginsRun(){this.clear(),this.#s=new Promise(e=>{this.#l=e})}waitForPluginsLifecycle(){return Promise.all([this.#s,this.#c,this.#h])}waitForPluginsRun(){return this.#s}finishPluginsRun(){this.#l?.();for(const e of this.#a.values())this.runListeners(...e);this.#a.clear()}startEsbuildRun(){this.#c=new Promise(e=>{this.#d=e})}finishEsbuildRun(){this.#d?.()}markRequestHandlersEntryOutdated(){this.#r++,!this.#e&&(this.#e=!0,this.#h=new Promise(e=>{this.#u=e}))}noteRequestHandlersEntryBuildStart(){this.#f=this.#r}markRequestHandlersEntryUpdated(){this.#e&&(this.#r>this.#f||(this.#e=!1,this.#u?.()))}get contentDir(){if(this.serverMode)throw new Error("contentDir should not be used in server mode");return this.#i}markUserCodeReady(){this.#n?.(!0)}async reloadMarkdocOptions(){await ie("com.redocly.build.reloadMarkdocOptions",async()=>{const e=C.instance(),t=await Y(this.serverOutDir),s=Object.fromEntries(Object.entries(t.tags).filter(([r])=>v[r]!=null?e.canAccessFeature(v[r]):!0));this.#o={...t,tags:s}})}get markdocOptions(){return{...this.#o,partials:this.getGlobalConfig(y),themeConfig:this.config.markdown}}setGlobalData=e=>{const t=this.globalData,s={...this.globalData,...e};this.globalData=s,JSON.stringify(s)!==JSON.stringify(t)&&this.queueEvent("global-data-updated",void 0,s)};getGlobalData=()=>this.globalData;getKv=async()=>q.getInstance({baseDbDir:this.serverOutDir});parseMarkdoc=async({input:e,context:t,deps:s,resource:r})=>{const{data:{info:a,ast:o},compoundHash:l}=await F(e,this.markdocOptions,{actions:this,context:t},r);for(const i of a.sharedDataDeps||[]){for(const n of s?.routeSlugs||[])this.addRouteSharedData(n,i,i);for(const n of s?.sharedDataIds||[]){const c=this.sharedDataDeps.get(n)||new Set;c.add(i),this.sharedDataDeps.set(n,c)}}for(const i of a.dynamicMarkdocComponents||[]){for(const n of s?.routeSlugs||[]){const c=this.routesDynamicComponents.get(n)||new Set;c.add(i),this.routesDynamicComponents.set(n,c)}for(const n of s?.sharedDataIds||[]){const c=this.sharedDataMarkdocComponents.get(n)||new Set;c.add(i),this.sharedDataMarkdocComponents.set(n,c)}}if(s?.routeSlugs&&a.partials?.length)for(const i of s.routeSlugs){const n=this.routesPartials.get(i)||[];for(const c of a.partials)n.includes(c)||n.push(c);this.routesPartials.set(i,n)}return{info:a,ast:o,compoundHash:l}};async loadApiDocuments(e){return(await e.cache.load(".","api-docs")).data}setSearchEngine(e){this.searchEngine=e}setSearchFacets=e=>{this.searchFacets=e};setStaticFilePaths=e=>{this.staticFilePaths=e};setGlobalConfig=e=>{const t=Object.keys(e);for(const o of t)for(const l in this.replacedEnvVars)if(l===o||l.startsWith(`${o}:`)){const i=l.split(":"),{error:n,value:c}=w(e,i);(n||c!==this.replacedEnvVars[l].replaced)&&delete this.replacedEnvVars[l]}const{config:s,unsetEnvVars:r,replacedValues:a}=te(e);for(const o of r)this.unsetEnvVars.add(o);Object.assign(this.replacedEnvVars,a),Object.assign(this.config,s)};getConfig=()=>this.config;getGlobalConfig=e=>this.config[e];getSearchFacets=()=>this.searchFacets;addRedirect=(e,t,s={})=>{if(!C.instance().canAccessFeature("redirects")&&e!=="/")return;this.config.redirects||(this.config.redirects={});const o=d(e).toLowerCase();this.config.redirects[o]=t;const{trackOriginalSource:l=!0}=s,i=this.getGlobalConfig("originalRedirectSources");l&&Array.isArray(i)&&!i.includes(o)&&i.push(o),o.endsWith("*")&&oe(this.config.wildcardRedirectsTree,o)};getRedirect=e=>{const t=d(e).toLowerCase(),s=re(t,this.config.redirects,this.config.wildcardRedirectsTree,this.staticFilePaths);if(!s)return null;if(E(s.to)){const r=d(s.to).toLowerCase();if(!r.endsWith("*")&&ae(r,[t],this.config.redirects,this.config.wildcardRedirectsTree).type==="cycle")return null}return{to:s.to,type:s.type}};createSharedData=async(e,t,s)=>{if(s&&this.#t[e]===s)return e;const r=JSON.stringify(t),a=s??I(r);return this.#t[e]===a||(this.#t[e]=a,await K(e,r,this.outdir),this.queueEvent("shared-data-updated",e)),e};addRouteSharedData=(e,t,s)=>{const r=B(e),a=this.routesSharedData.get(r)||{};a[t]=s,this.routesSharedData.set(r,a),u.verbose(`Adding shared data to ${e}, ${t}, ${s}`)};getRouteSharedDataByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.routesSharedData.get(t)||{}:{}};getPartialsForRoute=e=>{const t=this.getGlobalConfig(y)||{},s=this.routesPartials.get(e);if(!s||s.length===0)return{};const r=this.getGlobalConfig(G)||{},a=new Set(s),o=Array.from(s);for(let i=0;i<o.length;i++){const n=o[i],c=r[n]?.partials??[];for(const h of c)a.has(h)||(a.add(h),o.push(h))}const l={};for(const i of a)t[i]&&(l[i]=t[i]);return l};addRoute=e=>{const s={...X(e.fsPath,this.config.metadataGlobs),...e.metadata||{}};this.newRoutes.push({...e,metadata:s}),u.verbose("Created route %s",e.slug)};addRouteSharedDataToAllLocales=(e,t,s)=>{const r=[m,...this.lifecycleContext?.fs.localeFolders||[]].map(a=>({code:a,name:a}));for(const a of r){const o=L(e,m,a.code,r);this.addRouteSharedData(o,t,s)}};addApiRoute=e=>{this.apiRoutes.push(e),u.verbose("Created API route %s",e.slug)};addMcpTools=(e,t)=>{for(const s of t){const r=this.mcpToolHandlers.get(s.name);r&&r.importPath!==e&&u.warn('MCP tool "%s" from %s overwrites the tool registered from %s',s.name,e,r.importPath);const a=s.hasAvailabilityGate??(r?.importPath===e?r.hasAvailabilityGate:void 0);this.mcpToolHandlers.set(s.name,{...s,importPath:e,hasAvailabilityGate:a}),u.verbose("Created MCP tool %s",s.name)}};getMcpTools=()=>Array.from(this.mcpToolHandlers.values());markGatedMcpTools=e=>{for(const t of e){const s=this.mcpToolHandlers.get(t);s&&this.mcpToolHandlers.set(t,{...s,hasAvailabilityGate:!0})}};addSkills=e=>{for(const t of e)this.skills.set(t.slug,t),u.verbose("Discovered skill %s",t.slug)};getSkills=()=>Array.from(this.skills.values());removeMcpTools=e=>{for(const t of e)this.mcpToolHandlers.delete(t)};addMiddleware=e=>{this.middleware.push(e),u.verbose("Created middleware %s",e.id)};setResourceResponseHeaders=(e,t)=>{this.config.responseHeaders||(this.config.responseHeaders={});const s=new Set(t.map(o=>o.name.toLowerCase())),a=[...(this.config.responseHeaders[e]??[]).filter(o=>!s.has(o.name.toLowerCase())),...t];this.config.responseHeaders[e]=a};getRouteByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.getRouteBySlug(t):void 0};getRouteBySlug=(e,t={})=>{const{followRedirect:s=!0}=t,r=this.getRedirect(e);if(s&&r)return this.routesBySlug.get(d(r.to));const a=s?this.routeAliases.get(d(e).toLowerCase()):void 0;return this.routesBySlug.get(a??e)};addRouteAlias=(e,t)=>{this.routeAliases.set(d(e).toLowerCase(),d(t))};hasRouteOrRedirectBySlug=e=>{if(this.routesBySlug.has(e)||this.routeAliases.has(d(e).toLowerCase())||Z(e,this.getConfig()))return!0;const t=this.getRedirect(e);if(!t)return!1;if(!E(t.to))return!0;const s=d(t.to);return this.routesBySlug.has(s)};getRoutesByTemplateId=e=>this.newRoutes.filter(t=>t.templateId===e);getAllRoutesForLocale=(e=m)=>{const t=Array.from(this.routesBySlug.values()),s=e.toLowerCase();return t.filter(r=>e===m?!Q(r.fsPath):r.slug.startsWith(`/${s}`))};getAllRoutes=()=>Array.from(this.routesBySlug.values());getAllApiRoutes=()=>this.apiRoutes;getAllMiddleware=()=>this.middleware;getTemplate=e=>this.templates.get(e);getRequestHandler=e=>this.apiRoutesRequestHandlers.get(e);createTemplate=(e,t)=>(this.templates.set(e,t),e);addBrowserPlugin=e=>{this.browserPlugins.add(e)};createRequestHandler=(e,t)=>(this.apiRoutesRequestHandlers.set(e,t),e);clearRequestHandlersByPrefix=e=>{for(const t of this.apiRoutesRequestHandlers.keys())t.startsWith(e)&&this.apiRoutesRequestHandlers.delete(t)};registerServerPropsGetter=(e,t)=>(this.serverPropsGetters.set(e,t),e);registerPagePropsGetter=(e,t)=>{this.pagePropsGetters.set(e,t)};async writeRouteStaticData(e,t){const s=await this.resolveRouteStaticData(e,t,!1);s&&z(e.slug,s,this.outdir)}async resolveRouteStaticData(e,t,s){if(this.serverMode)return $(e.slug,this.outdir);const r={...this,contentDir:this.contentDir,parseMarkdoc:({input:c,context:h,resource:f})=>this.parseMarkdoc({input:c,context:h,deps:{routeSlugs:[e.slug]},resource:f})},a=await e.getStaticData?.(e,r)||{},o=new Set(this.routesDynamicComponents.get(e.slug)),l=this.routesSharedData.get(e.slug)||{};for(const c of Object.values(l)){const h=this.sharedDataMarkdocComponents.get(c);h&&h.forEach(p=>o.add(p));const f=this.sharedDataDeps.get(c);f&&f.forEach(p=>this.addRouteSharedData(e.slug,p,p))}const i=this.getGlobalConfig("seo"),n=a?.frontmatter||{};return{...a,frontmatter:{...n,seo:{...n?.seo,title:n?.seo?.title||await e.getNavText?.()}},props:{...a.props,dynamicMarkdocComponents:Array.from(o),metadata:{...a?.props?.metadata,...e.metadata},seo:{title:H,...i,...a.props?.seo,siteUrl:i?.siteUrl},compilationErrors:this.compilationErrors},lastModified:s||!e.fsPath?null:await this.lifecycleContext?.fs.getLastModified(e.fsPath)}}addSsrComponents(e,t){if(!e?.length)return;const s=typeof e[0]=="string"?e.join(""):W(e);s&&(t==="head"?this.ssr.headTags.push(s):t==="preBody"?this.ssr.preBodyTags.push(s):this.ssr.postBodyTags.push(s))}clear=()=>{this.routesByFsPath.clear(),this.templates.clear(),this.newRoutes=[],this.routesBySlug.clear(),this.routeAliases.clear(),this.apiRoutes=[],this.middleware=[],this.routesSharedData.clear(),this.sharedDataDeps.clear(),this.sharedDataMarkdocComponents.clear(),this.routesDynamicComponents.clear(),this.routesPartials.clear(),this.skills.clear(),this.config.redirects={},this.config.wildcardRedirectsTree={},this.config.directoryPermissions={},this.ssr={preBodyTags:[],postBodyTags:[],headTags:[]}};#p(){const e=[];for(const[s,r]of Object.entries(A))switch(r){case"map":{const a=Array.from(this[s].entries());e.push([s,a]);break}case"object":e.push([s,this[s]]);break;default:throw new Error("Invalid format")}const t=Object.fromEntries(e);return t[T]=j.PLAN_GATES,t}static#g(e,t){const s=new R(t);for(const[a,o]of Object.entries(A))switch(o){case"map":s[a]=new Map(e[a]);break;case"object":s[a]=e[a];break;default:throw new Error("Invalid format")}const r=e[T];return r&&V("PLAN_GATES",r),s}async writeServerFiles(){x(this.serverOutDir),S(g(this.serverOutDir,b),JSON.stringify(this.#p())),S(g(this.serverOutDir,O),JSON.stringify(await this.getConfigWithEnvPlaceholders()))}static async fromServerFiles(e){const t=g(e.serverOutDir,O),{config:s,env:r}=se(JSON.parse(await D(t,"utf8")));s[y]=le(s[y]);const a=JSON.parse(await D(g(e.serverOutDir,b),"utf8")),o=R.#g(a,e);o.config=s;const l=Object.fromEntries(Object.entries(r).filter(([i])=>U(i)));return o.configFile={path:t,env:l,config:{...s}},o}async getConfigWithEnvPlaceholders(){const e=JSON.parse(JSON.stringify(this.config));for(const t in this.replacedEnvVars){const{original:s}=this.replacedEnvVars[t],r=t.split(":"),a=r.pop(),{error:o,value:l}=w(e,r);if(o||!_(l)&&!Array.isArray(l)){await P.panicOnBuild(`Failed to replace env var with env name for ${t}`);continue}l[a]=s}return e}async reportUnsetEnvVars(){if(this.unsetEnvVars.size===0)return;const e=Array.from(this.unsetEnvVars).filter(s=>!ne.includes(s));if(e.length===0)return;const t=`Failed to resolve config. The following environment variables are not set: ${e.join(", ")}`;await P.panicOnBuildContentError(t)}}function le(M){return N(M,e=>k.Ast.fromJSON(JSON.stringify(e)))}export{R as Store,Ue as USER_DEFINED_API_FUNCTIONS_COUNTER_KEY};
|
|
1
|
+
import T from"@redocly/markdoc";import{writeFileSync as w}from"node:fs";import{readFile as R}from"node:fs/promises";import{join as g}from"node:path";import{parseAndResolveMarkdoc as M}from"./plugins/markdown/compiler.js";import{getPathnameForLocale as k}from"@redocly/theme/core/utils";import{DEFAULT_LOCALE_PLACEHOLDER as m}from"../constants/common.js";import{DEFAULT_TITLE as F,MARKDOC_PARTIALS_DATA_KEY as y,MARKDOC_PARTIALS_DEPS_KEY as L}from"./constants/common.js";import{isObject as H}from"../utils/guards/is-object.js";import{mapObject as N}from"../utils/object/map-object.js";import{getValueDeep as S}from"../utils/object/get-value-deep.js";import{removeTrailingSlash as G}from"../utils/url/remove-trailing-slash.js";import{normalizeRouteSlug as d}from"../utils/path/normalize-route-slug.js";import{isLocalLink as v}from"../utils/path/is-local-link.js";import{reporter as E}from"./tools/notifiers/reporter.js";import{logger as u}from"./tools/notifiers/logger.js";import{sha1 as _}from"./utils/crypto/sha1.js";import{FileNotFoundError as B}from"./utils/fs.js";import{resolveAssetPath as I}from"./utils/resolve-asset-path.js";import{envConfig as j,setEnv as V}from"./config/env-config.js";import{KvService as q}from"./persistence/kv/services/kv-service.js";import{SandboxContext as J}from"./utils/sandbox-context.js";import{isAllowedEnv as U}from"./utils/envs/get-api-route-allowed-env-variables.js";import{ensureDir as x,writeSharedData as K}from"./utils/index.js";import{renderComponents as $}from"./ssr/render.js";import{readStaticData as W,writeStaticData as z}from"./utils/static-data.js";import{getMarkdocOptions as Y}from"./plugins/markdown/markdoc/markdoc-options.js";import{EntitlementsProvider as Z}from"./entitlements/entitlements-provider.js";import{getPlanDeniedMarkdocTags as Q}from"./entitlements/plan-denied-markdoc-tags.js";import{isRouteReserved as X}from"./plugins/get-reserved-routes.js";import{isL10nPath as ee}from"./fs/utils/is-l10n-path.js";import{resolveGlobMapValue as te}from"./utils/globs.js";import{createDefaultStoreConfig as se,resolveConfigEntries as re,resolveStoreConfig as oe}from"./store-config.js";import{findRedirect as ae}from"./utils/redirects/find-redirect.js";import{followRedirectChain as ie}from"./utils/redirects/follow-redirect-chain.js";import{addWildcardRedirectToTree as ne}from"./utils/redirects/add-wildcard-redirect-to-tree.js";import{telemetryTraceStep as le}from"../cli/telemetry/helpers/trace-step.js";const P={routesBySlug:"map",staticFilePaths:"object",apiRoutes:"object",middleware:"object",routesByFsPath:"map",routesSharedData:"map",globalData:"object",ssr:"object",searchFacets:"map",routesPartials:"map",mcpToolHandlers:"map",skills:"map",devLogin:"object"},C="store.json",A="store-config.json",b="PLAN_GATES",ce=["OAUTH_CLIENT_ID","OAUTH_CLIENT_SECRET","ORGANIZATION_SLUG","ORGANIZATION_ID","ORG_ID"],We="userDefinedApiFunctions";class D{routesBySlug=new Map;routeAliases=new Map;staticFilePaths={};replacedEnvVars={};unsetEnvVars=new Set;lifecycleContext;newRoutes=[];#t={};routesByFsPath=new Map;apiRoutes=[];middleware=[];routesSharedData=new Map;sharedDataDeps=new Map;sharedDataMarkdocComponents=new Map;routesDynamicComponents=new Map;routesPartials=new Map;ssr={preBodyTags:[],postBodyTags:[],headTags:[]};searchFacets=new Map;searchEngine;templates=new Map;browserPlugins=new Set;apiRoutesRequestHandlers=new Map;mcpToolHandlers=new Map;skills=new Map;serverPropsGetters=new Map;pagePropsGetters=new Map;listeners=new Map;globalData={};devLogin=!1;#a=void 0;#i={};config=se();configFile;#n;serverMode;serverOutDir;outdir;buildRevision=0;hasSitemap=!1;compilationErrors=[];#l;userCodeReady;#s=Promise.resolve();#c;#d=Promise.resolve();#h;#u=Promise.resolve();#f;#e=!1;#r=0;#p=0;#o=new Map;constructor({outdir:e,contentDir:t,serverMode:s=!1,serverOutDir:r}){this.#n=t,this.outdir=e,this.serverMode=s,this.serverOutDir=r,J.register({serverOutDir:r,readRoots:[e,process.cwd()]}),this.userCodeReady=new Promise(o=>{this.#l=o})}on(e,t){const s=this.listeners.get(e);s?s.add(t):this.listeners.set(e,new Set([t]))}queueEvent=(e,t,...s)=>{this.#o.set(e+String(t),[e,t,...s])};runListeners=(e,t,...s)=>{for(const r of this.listeners.get(e)||new Set)t?r(t,...s):r(...s)};startPluginsRun(){this.clear(),this.#s=new Promise(e=>{this.#c=e})}waitForPluginsLifecycle(){return Promise.all([this.#s,this.#d,this.#u])}waitForPluginsRun(){return this.#s}finishPluginsRun(){this.#c?.();for(const e of this.#o.values())this.runListeners(...e);this.#o.clear()}startEsbuildRun(){this.#d=new Promise(e=>{this.#h=e})}finishEsbuildRun(){this.#h?.()}markRequestHandlersEntryOutdated(){this.#r++,!this.#e&&(this.#e=!0,this.#u=new Promise(e=>{this.#f=e}))}noteRequestHandlersEntryBuildStart(){this.#p=this.#r}markRequestHandlersEntryUpdated(){this.#e&&(this.#r>this.#p||(this.#e=!1,this.#f?.()))}get contentDir(){if(this.serverMode)throw new Error("contentDir should not be used in server mode");return this.#n}markUserCodeReady(){this.#l?.(!0)}async reloadMarkdocOptions(){await le("com.redocly.build.reloadMarkdocOptions",async()=>{const{userTagNames:e,...t}=await Y(this.serverOutDir),s=Q(e),r=Object.fromEntries(Object.entries(t.tags).filter(([o])=>!(o in s)));this.#a={...t,tags:r},this.#i=s})}get markdocOptions(){return{...this.#a,partials:this.getGlobalConfig(y),themeConfig:this.config.markdown,planDeniedTags:this.#i}}setGlobalData=e=>{const t=this.globalData,s={...this.globalData,...e};this.globalData=s,JSON.stringify(s)!==JSON.stringify(t)&&this.queueEvent("global-data-updated",void 0,s)};getGlobalData=()=>this.globalData;getKv=async()=>q.getInstance({baseDbDir:this.serverOutDir});parseMarkdoc=async({input:e,context:t,deps:s,resource:r})=>{const{data:{info:o,ast:a},compoundHash:l}=await M(e,this.markdocOptions,{actions:this,context:t},r);for(const i of o.sharedDataDeps||[]){for(const n of s?.routeSlugs||[])this.addRouteSharedData(n,i,i);for(const n of s?.sharedDataIds||[]){const c=this.sharedDataDeps.get(n)||new Set;c.add(i),this.sharedDataDeps.set(n,c)}}for(const i of o.dynamicMarkdocComponents||[]){for(const n of s?.routeSlugs||[]){const c=this.routesDynamicComponents.get(n)||new Set;c.add(i),this.routesDynamicComponents.set(n,c)}for(const n of s?.sharedDataIds||[]){const c=this.sharedDataMarkdocComponents.get(n)||new Set;c.add(i),this.sharedDataMarkdocComponents.set(n,c)}}if(s?.routeSlugs&&o.partials?.length)for(const i of s.routeSlugs){const n=this.routesPartials.get(i)||[];for(const c of o.partials)n.includes(c)||n.push(c);this.routesPartials.set(i,n)}return{info:o,ast:a,compoundHash:l}};async loadApiDocuments(e){return(await e.cache.load(".","api-docs")).data}setSearchEngine(e){this.searchEngine=e}setSearchFacets=e=>{this.searchFacets=e};setStaticFilePaths=e=>{this.staticFilePaths=e};setGlobalConfig=e=>{const t=Object.keys(e);for(const a of t)for(const l in this.replacedEnvVars)if(l===a||l.startsWith(`${a}:`)){const i=l.split(":"),{error:n,value:c}=S(e,i);(n||c!==this.replacedEnvVars[l].replaced)&&delete this.replacedEnvVars[l]}const{config:s,unsetEnvVars:r,replacedValues:o}=re(e);for(const a of r)this.unsetEnvVars.add(a);Object.assign(this.replacedEnvVars,o),Object.assign(this.config,s)};getConfig=()=>this.config;getGlobalConfig=e=>this.config[e];getSearchFacets=()=>this.searchFacets;addRedirect=(e,t,s={})=>{if(!Z.instance().canAccessFeature("redirects")&&e!=="/")return;this.config.redirects||(this.config.redirects={});const a=d(e).toLowerCase();this.config.redirects[a]=t;const{trackOriginalSource:l=!0}=s,i=this.getGlobalConfig("originalRedirectSources");l&&Array.isArray(i)&&!i.includes(a)&&i.push(a),a.endsWith("*")&&ne(this.config.wildcardRedirectsTree,a)};getRedirect=e=>{const t=d(e).toLowerCase(),s=ae(t,this.config.redirects,this.config.wildcardRedirectsTree,this.staticFilePaths);if(!s)return null;if(v(s.to)){const r=d(s.to).toLowerCase();if(!r.endsWith("*")&&ie(r,[t],this.config.redirects,this.config.wildcardRedirectsTree).type==="cycle")return null}return{to:s.to,type:s.type}};createSharedData=async(e,t,s)=>{if(s&&this.#t[e]===s)return e;const r=JSON.stringify(t),o=s??_(r);return this.#t[e]===o||(this.#t[e]=o,await K(e,r,this.outdir),this.queueEvent("shared-data-updated",e)),e};addRouteSharedData=(e,t,s)=>{const r=G(e),o=this.routesSharedData.get(r)||{};o[t]=s,this.routesSharedData.set(r,o),u.verbose(`Adding shared data to ${e}, ${t}, ${s}`)};getRouteSharedDataByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.routesSharedData.get(t)||{}:{}};getPartialsForRoute=e=>{const t=this.getGlobalConfig(y)||{},s=this.routesPartials.get(e);if(!s||s.length===0)return{};const r=this.getGlobalConfig(L)||{},o=new Set(s),a=Array.from(s);for(let i=0;i<a.length;i++){const n=a[i],c=r[n]?.partials??[];for(const h of c)o.has(h)||(o.add(h),a.push(h))}const l={};for(const i of o)t[i]&&(l[i]=t[i]);return l};addRoute=e=>{const s={...te(e.fsPath,this.config.metadataGlobs),...e.metadata||{}};this.newRoutes.push({...e,metadata:s}),u.verbose("Created route %s",e.slug)};addRouteSharedDataToAllLocales=(e,t,s)=>{const r=[m,...this.lifecycleContext?.fs.localeFolders||[]].map(o=>({code:o,name:o}));for(const o of r){const a=k(e,m,o.code,r);this.addRouteSharedData(a,t,s)}};addApiRoute=e=>{this.apiRoutes.push(e),u.verbose("Created API route %s",e.slug)};addMcpTools=(e,t)=>{for(const s of t){const r=this.mcpToolHandlers.get(s.name);r&&r.importPath!==e&&u.warn('MCP tool "%s" from %s overwrites the tool registered from %s',s.name,e,r.importPath);const o=s.hasAvailabilityGate??(r?.importPath===e?r.hasAvailabilityGate:void 0);this.mcpToolHandlers.set(s.name,{...s,importPath:e,hasAvailabilityGate:o}),u.verbose("Created MCP tool %s",s.name)}};getMcpTools=()=>Array.from(this.mcpToolHandlers.values());markGatedMcpTools=e=>{for(const t of e){const s=this.mcpToolHandlers.get(t);s&&this.mcpToolHandlers.set(t,{...s,hasAvailabilityGate:!0})}};addSkills=e=>{for(const t of e)this.skills.set(t.slug,t),u.verbose("Discovered skill %s",t.slug)};getSkills=()=>Array.from(this.skills.values());removeMcpTools=e=>{for(const t of e)this.mcpToolHandlers.delete(t)};addMiddleware=e=>{this.middleware.push(e),u.verbose("Created middleware %s",e.id)};setResourceResponseHeaders=(e,t)=>{this.config.responseHeaders||(this.config.responseHeaders={});const s=new Set(t.map(a=>a.name.toLowerCase())),o=[...(this.config.responseHeaders[e]??[]).filter(a=>!s.has(a.name.toLowerCase())),...t];this.config.responseHeaders[e]=o};getRouteByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.getRouteBySlug(t):void 0};getRouteBySlug=(e,t={})=>{const{followRedirect:s=!0}=t,r=this.getRedirect(e);if(s&&r)return this.routesBySlug.get(d(r.to));const o=s?this.routeAliases.get(d(e).toLowerCase()):void 0;return this.routesBySlug.get(o??e)};addRouteAlias=(e,t)=>{this.routeAliases.set(d(e).toLowerCase(),d(t))};hasRouteOrRedirectBySlug=e=>{if(this.routesBySlug.has(e)||this.routeAliases.has(d(e).toLowerCase())||X(e,this.getConfig()))return!0;const t=this.getRedirect(e);if(!t)return!1;if(!v(t.to))return!0;const s=d(t.to);return this.routesBySlug.has(s)};getRoutesByTemplateId=e=>this.newRoutes.filter(t=>t.templateId===e);getAllRoutesForLocale=(e=m)=>{const t=Array.from(this.routesBySlug.values()),s=e.toLowerCase();return t.filter(r=>e===m?!ee(r.fsPath):r.slug.startsWith(`/${s}`))};getAllRoutes=()=>Array.from(this.routesBySlug.values());getAllApiRoutes=()=>this.apiRoutes;getAllMiddleware=()=>this.middleware;getTemplate=e=>this.templates.get(e);getRequestHandler=e=>this.apiRoutesRequestHandlers.get(e);createTemplate=(e,t)=>(this.templates.set(e,t),e);addBrowserPlugin=e=>{this.browserPlugins.add(e)};copyAsset=async(e,t)=>{const s=this.lifecycleContext?.fs;if(!s)throw new Error(`Cannot copy asset ${e}: the content file system is not ready`);try{const r=await I(e,s,{fromFileRelativePath:t,contentDir:this.contentDir,outdir:this.outdir});if(!r)throw new Error(`Cannot copy asset ${e}`);return r}catch(r){if(r instanceof B)return null;throw r}};createRequestHandler=(e,t)=>(this.apiRoutesRequestHandlers.set(e,t),e);clearRequestHandlersByPrefix=e=>{for(const t of this.apiRoutesRequestHandlers.keys())t.startsWith(e)&&this.apiRoutesRequestHandlers.delete(t)};registerServerPropsGetter=(e,t)=>(this.serverPropsGetters.set(e,t),e);registerPagePropsGetter=(e,t)=>{this.pagePropsGetters.set(e,t)};async writeRouteStaticData(e,t){const s=await this.resolveRouteStaticData(e,t,!1);s&&z(e.slug,s,this.outdir)}async resolveRouteStaticData(e,t,s){if(this.serverMode)return W(e.slug,this.outdir);const r={...this,contentDir:this.contentDir,parseMarkdoc:({input:c,context:h,resource:f})=>this.parseMarkdoc({input:c,context:h,deps:{routeSlugs:[e.slug]},resource:f})},o=await e.getStaticData?.(e,r)||{},a=new Set(this.routesDynamicComponents.get(e.slug)),l=this.routesSharedData.get(e.slug)||{};for(const c of Object.values(l)){const h=this.sharedDataMarkdocComponents.get(c);h&&h.forEach(p=>a.add(p));const f=this.sharedDataDeps.get(c);f&&f.forEach(p=>this.addRouteSharedData(e.slug,p,p))}const i=this.getGlobalConfig("seo"),n=o?.frontmatter||{};return{...o,frontmatter:{...n,seo:{...n?.seo,title:n?.seo?.title||await e.getNavText?.()}},props:{...o.props,dynamicMarkdocComponents:Array.from(a),metadata:{...o?.props?.metadata,...e.metadata},seo:{title:F,...i,...o.props?.seo,siteUrl:i?.siteUrl},compilationErrors:this.compilationErrors},lastModified:s||!e.fsPath?null:await this.lifecycleContext?.fs.getLastModified(e.fsPath)}}addSsrComponents(e,t){if(!e?.length)return;const s=typeof e[0]=="string"?e.join(""):$(e);s&&(t==="head"?this.ssr.headTags.push(s):t==="preBody"?this.ssr.preBodyTags.push(s):this.ssr.postBodyTags.push(s))}clear=()=>{this.routesByFsPath.clear(),this.templates.clear(),this.newRoutes=[],this.routesBySlug.clear(),this.routeAliases.clear(),this.apiRoutes=[],this.middleware=[],this.routesSharedData.clear(),this.sharedDataDeps.clear(),this.sharedDataMarkdocComponents.clear(),this.routesDynamicComponents.clear(),this.routesPartials.clear(),this.skills.clear(),this.config.redirects={},this.config.wildcardRedirectsTree={},this.config.directoryPermissions={},this.ssr={preBodyTags:[],postBodyTags:[],headTags:[]}};#g(){const e=[];for(const[s,r]of Object.entries(P))switch(r){case"map":{const o=Array.from(this[s].entries());e.push([s,o]);break}case"object":e.push([s,this[s]]);break;default:throw new Error("Invalid format")}const t=Object.fromEntries(e);return t[b]=j.PLAN_GATES,t}static#m(e,t){const s=new D(t);for(const[o,a]of Object.entries(P))switch(a){case"map":s[o]=new Map(e[o]);break;case"object":s[o]=e[o];break;default:throw new Error("Invalid format")}const r=e[b];return r&&V("PLAN_GATES",r),s}async writeServerFiles(){x(this.serverOutDir),w(g(this.serverOutDir,C),JSON.stringify(this.#g())),w(g(this.serverOutDir,A),JSON.stringify(await this.getConfigWithEnvPlaceholders()))}static async fromServerFiles(e){const t=g(e.serverOutDir,A),{config:s,env:r}=oe(JSON.parse(await R(t,"utf8")));s[y]=de(s[y]);const o=JSON.parse(await R(g(e.serverOutDir,C),"utf8")),a=D.#m(o,e);a.config=s;const l=Object.fromEntries(Object.entries(r).filter(([i])=>U(i)));return a.configFile={path:t,env:l,config:{...s}},a}async getConfigWithEnvPlaceholders(){const e=JSON.parse(JSON.stringify(this.config));for(const t in this.replacedEnvVars){const{original:s}=this.replacedEnvVars[t],r=t.split(":"),o=r.pop(),{error:a,value:l}=S(e,r);if(a||!H(l)&&!Array.isArray(l)){await E.panicOnBuild(`Failed to replace env var with env name for ${t}`);continue}l[o]=s}return e}async reportUnsetEnvVars(){if(this.unsetEnvVars.size===0)return;const e=Array.from(this.unsetEnvVars).filter(s=>!ce.includes(s));if(e.length===0)return;const t=`Failed to resolve config. The following environment variables are not set: ${e.join(", ")}`;await E.panicOnBuildContentError(t)}}function de(O){return N(O,e=>T.Ast.fromJSON(JSON.stringify(e)))}export{D as Store,We as USER_DEFINED_API_FUNCTIONS_COUNTER_KEY};
|
|
@@ -31,6 +31,8 @@ export type ResolveItemsOptions = {
|
|
|
31
31
|
};
|
|
32
32
|
export type MarkdocOptions = Partial<Omit<MarkdocConfigProps, 'relativePath'>> & {
|
|
33
33
|
themeConfig?: RedoclyConfig['markdown'];
|
|
34
|
+
/** The tags the project's plan lacks, each with the message a page shows in place of the tag. */
|
|
35
|
+
planDeniedTags?: Record<string, string>;
|
|
34
36
|
};
|
|
35
37
|
export type GetStaticDataContext = {
|
|
36
38
|
getRouteByFsPath: (relativePath: string) => PageRouteDetails<PageStaticData, PageProps> | undefined;
|
|
@@ -111,7 +113,7 @@ export type PageRouteInit = Omit<PageRouteDetails<PageStaticData, PageProps>, 'v
|
|
|
111
113
|
key: string;
|
|
112
114
|
}>;
|
|
113
115
|
redirectFrom?: Array<{
|
|
114
|
-
type
|
|
116
|
+
type?: number;
|
|
115
117
|
from: string;
|
|
116
118
|
}>;
|
|
117
119
|
};
|
|
@@ -119,6 +121,8 @@ export type ApiRouteMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all'
|
|
|
119
121
|
export type ApiRoute = RouteDetails & {
|
|
120
122
|
httpMethod: ApiRouteMethod;
|
|
121
123
|
requestHandlerId: string;
|
|
124
|
+
timeoutMs?: number;
|
|
125
|
+
maxResponseSizeMB?: number;
|
|
122
126
|
};
|
|
123
127
|
export type McpToolSchema = {
|
|
124
128
|
name: string;
|
|
@@ -169,6 +173,14 @@ export type ProcessContentActions = {
|
|
|
169
173
|
addRedirect: (from: string, to: RedirectConfig, options?: RedirectOptions) => void;
|
|
170
174
|
createTemplate: (id: string, importPath: string) => string;
|
|
171
175
|
addBrowserPlugin: (importPath: string) => void;
|
|
176
|
+
/**
|
|
177
|
+
* Resolves an asset `src` written in the page at `fromFileRelativePath` the way Markdown
|
|
178
|
+
* images resolve: a `static/` file keeps its path, a content file is published under a
|
|
179
|
+
* host-owned asset name, an l10n page falls back to the default-locale file, and an
|
|
180
|
+
* external URL is returned as is. The URL includes the path prefix. Resolves to `null`
|
|
181
|
+
* when the file does not exist; rejects on any other failure.
|
|
182
|
+
*/
|
|
183
|
+
copyAsset: (src: string, fromFileRelativePath: string) => Promise<string | null>;
|
|
172
184
|
registerServerPropsGetter: (id: string, importPath: string) => string;
|
|
173
185
|
registerPagePropsGetter: (id: string, importPath: string) => void;
|
|
174
186
|
addSsrComponents: (components: JSX.Element[] | string[], position: 'head' | 'preBody' | 'postBody') => void;
|
|
@@ -60,6 +60,11 @@ declare module 'hono' {
|
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
62
|
export type LlmsTxtGenerator = {
|
|
63
|
+
/**
|
|
64
|
+
* Whether `getPageMarkdown` would answer for this path, without rendering anything. A sub-path
|
|
65
|
+
* of a route with client routes answers for the owner route.
|
|
66
|
+
*/
|
|
67
|
+
hasPageMarkdown(mdPathname: string): boolean;
|
|
63
68
|
getPageMarkdown(mdPathname: string): Promise<{
|
|
64
69
|
route: PageRouteDetails;
|
|
65
70
|
content: string;
|
|
@@ -3,6 +3,7 @@ export declare class HttpError extends Error {
|
|
|
3
3
|
constructor(status: number, message: string);
|
|
4
4
|
}
|
|
5
5
|
export declare class OidcDiscoveryError extends Error {
|
|
6
|
-
|
|
6
|
+
/** `reason` completes the sentence "<host> ...", e.g. "answered HTTP 503 (text/html)". */
|
|
7
|
+
constructor(url: string, reason: string);
|
|
7
8
|
}
|
|
8
9
|
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
class
|
|
1
|
+
class s extends Error{status;constructor(t,r){super(r),this.status=t,Object.setPrototypeOf(this,s.prototype)}}class e extends Error{constructor(t,r){super(`OIDC discovery failed: ${new URL(t).host} ${r}`),this.name="OidcDiscoveryError",Object.setPrototypeOf(this,e.prototype)}}export{s as HttpError,e as OidcDiscoveryError};
|
|
@@ -6,5 +6,10 @@ type ResolvedLlmsTxtMd = {
|
|
|
6
6
|
route: PageRouteDetails | undefined;
|
|
7
7
|
};
|
|
8
8
|
export declare function resolveLlmsTxtMd(mdPathname: string, store: Store, generator?: LlmsTxtGenerator): Promise<ResolvedLlmsTxtMd>;
|
|
9
|
+
/**
|
|
10
|
+
* The prefixed URL of the Markdown copy of the page at `slug`, or `undefined` when the site
|
|
11
|
+
* has no copy of it: the build wrote none, or develop mode generates none.
|
|
12
|
+
*/
|
|
13
|
+
export declare function resolvePageMarkdownUrl(slug: string, store: Store, generator?: LlmsTxtGenerator): Promise<string | undefined>;
|
|
9
14
|
export {};
|
|
10
15
|
//# sourceMappingURL=resolve-llms-txt-md.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import s from"path";import{getMarkdownCopyPath as a,getSlugFromMarkdownCopyPath as d,withPathPrefix as u}from"@redocly/theme/core/utils";import{isPathInFolder as f}from"../../../utils/path/is-path-in-folder.js";import{removeLeadingSlash as l}from"../../../utils/url/remove-leading-slash.js";import{fileExistsAsync as c}from"../index.js";async function y(t,o,e){if(e){const r=await e.getPageMarkdown(t);return{exists:r!==void 0,content:r?.content,route:r?.route}}const n=d(t);return{exists:await i(t,o),content:void 0,route:n===null?void 0:o.getRouteBySlug(n,{followRedirect:!1})}}async function M(t,o,e){const n=a(t);return(e?e.hasPageMarkdown(n):await i(n,o))?encodeURI(u(n)):void 0}async function i(t,o){if(/[\\\0]/.test(t))return!1;const e=s.resolve(o.outdir,l(t));return f(e,o.outdir)&&c(e)}export{y as resolveLlmsTxtMd,M as resolvePageMarkdownUrl};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import"../node-crypto-polyfill.js";import{DOMParser as
|
|
1
|
+
import"../node-crypto-polyfill.js";import{DOMParser as U}from"@xmldom/xmldom";import{SignedXml as ne}from"xml-crypto";import re from"xpath";import{deflateSync as oe,inflateSync as se}from"fflate";import{createHash as ie}from"crypto";import{ulid as ae}from"ulid";import{AuthProviderType as p,DEFAULT_TEAM_CLAIM_NAME as $}from"@redocly/config";import{ALTERNATIVE_AUD_CLAIM_NAME as ce,AUTH_URL as V,JWT_SECRET_KEY as y,MAX_AUTH_TOKEN_COOKIE_BYTES as de}from"../constants/common.js";import{ensureArray as O}from"../../utils/array/ensure-array.js";import{envConfig as ue}from"../config/env-config.js";import{decryptClaimValue as le}from"../utils/crypto/decrypt-claim-value.js";import{decryptAesGcm as fe}from"../utils/crypto/decrypt-aes-gcm.js";import{encryptAesGcm as me}from"../utils/crypto/encrypt-aes-gcm.js";import{getPathPrefix as pe,withPathPrefix as he,withoutPathPrefix as ye}from"@redocly/theme/core/utils";import{ServerRoutes as K}from"../../constants/api.js";import{AuthCookieNames as I,DEFAULT_AUTHENTICATED_TEAM as we,REQUIRED_OIDC_SCOPES as B}from"../../constants/common.js";import{appendQueryParams as Ae}from"../../utils/url/append-query-params.js";import{parsePreviewUrl as F}from"../../utils/url/parse-preview-url.js";import{logger as E}from"../tools/notifiers/logger.js";import{OidcDiscoveryError as M}from"../utils/errors.js";import{randomString as _e}from"../utils/crypto/random-string.js";import{randomUUID as D}from"../utils/crypto/random-uuid.js";import{AlgorithmTypes as l,JwtTokenExpired as Se}from"./jwt/types.js";import*as m from"./jwt/jwt.js";import{InternalTokenTypes as g}from"./jwt/token-types.js";import{parseTeamClaimToArray as Te}from"../utils/index.js";import{parseTeamNameTemplate as ge}from"../utils/rbac-expand.js";import{arrayBufferToBase64 as xe,decodeBase64 as H,encodeBase64URL as Ie,urlSafeBase64 as z}from"./jwt/encode.js";import{formatSamlCertificate as Ee}from"./utils/format-saml-certificate.js";const ke=new Set(Object.values(g));function x(e){return e?.type===p.OIDC}function Re(e){return e?.type===p.SAML2}async function Ct(e,t){if(x(t))return Oe(e,t);if(Re(t))return Me(e,t)}async function Oe(e,t){const n=await X(e,t),r=new Set((t.scopes||[]).concat(B)),o=t.authorizationRequestCustomParams||{};return{type:p.OIDC,idpId:e,name:"OAuth provider",authorizationEndpoint:n.authorization_endpoint,clientId:t.clientId,responseType:"code",scope:Array.from(r).join(" "),extraParams:o,pkce:t.pkce}}function Me(e,t){return{type:p.SAML2,idpId:e,name:"SAML2 provider",ssoUrl:t.ssoUrl,issuerId:t.issuerId,entityId:t.entityId||t.issuerId}}function W(e){return Array.from(new Set((e.scopes||[]).concat(B))).join(" ")}async function J(e,t,n){return await fetch(e,{method:"POST",body:new URLSearchParams({client_id:t.clientId,...t.clientSecret?{client_secret:t.clientSecret}:{},...n}).toString(),headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}).then(r=>r.json())}async function bt(e,t,n,r,o={}){return await J(e,r,{scope:W(r),code:t,redirect_uri:q(n),grant_type:"authorization_code",...o})}async function Pt(e,t,n){return await J(e,n,{scope:W(n),grant_type:"refresh_token",refresh_token:t})}function De(e,{authorizationEndpoint:t,clientId:n,responseType:r,scope:o,extraParams:s,idpId:i,pkce:c},u,h,d){if(!t||!n||!r||!o)return{loginUrl:void 0};const a=new URL(t),A=d?.redirectUriOverride??`${e}${he(K.OIDC_CALLBACK)}`,S={state:D(),idpId:i,redirectUri:A,redirectTo:u,branch:d?.branchOverride??be(e),inviteCode:h,source:d?.sourceOverride??"portal",uiLocales:d?.uiLocales},T={};if(c){const w=z(_e(50)),k=z(ie("sha256").update(w).digest("base64")),R="S256";a.searchParams.append("code_challenge",k),a.searchParams.append("code_challenge_method",R),T.code_verifier={value:w,options:{secure:!0,httpOnly:!0,expires:new Date(Date.now()+1e3*60*10),path:pe()||"/"}}}a.searchParams.append("client_id",n),a.searchParams.append("scope",o),a.searchParams.append("response_type",r),a.searchParams.append("redirect_uri",q(A)),a.searchParams.append("state",Ie(JSON.stringify(S))),d?.uiLocales&&a.searchParams.append("ui_locales",d.uiLocales);for(const w in s)s[w]!==void 0&&a.searchParams.append(w,s[w]);return{loginUrl:a.toString(),cookies:T}}function vt(e,t,n,r){const o=new URL(e);return n&&(o.searchParams.append("post_logout_redirect_uri",t),r&&o.searchParams.append("state",r),o.searchParams.append("id_token_hint",n)),o.toString()}function Le(e,t){const n=O(t?.audience??[]);return!n.length||Y(e,n)}function Y(e,t){const n=[e.aud,e[ce]].flat();return t.some(r=>r!==""&&n.includes(r))}function Ne(e,t){return!t||!x(t)?!0:Le(e,t)&&Ce(e,t)}function Ce(e,t){return!x(t)||!Qe(t)||!t.clientId?!0:O(e.aud||[]).includes(t.clientId)}function jt(e){if(!e)return!1;try{return m.decode(e).header.alg===l.RS256}catch{return!1}}async function Ut(e){const t=Math.floor(Date.now()/1e3),n=t+(e.ttlSec??600);return m.sign({type:g.MCP_AUTHORIZATION_CODE,client_id:e.clientId,redirect_uri:e.redirectUri,id_token_enc:me(e.idToken,y),...e.idpId?{idp_id:e.idpId}:{},...e.idpAccessTokenEnc?{idp_access_token_enc:e.idpAccessTokenEnc}:{},...e.idpRefreshTokenEnc?{idp_refresh_token_enc:e.idpRefreshTokenEnc}:{},...e.codeChallenge?{code_challenge:e.codeChallenge}:{},...e.codeChallengeMethod?{code_challenge_method:e.codeChallengeMethod}:{},iat:t,exp:n},y,l.HS256)}async function $t(e){await m.verify(e,y,l.HS256);const{payload:t}=m.decode(e);if(t.type!==g.MCP_AUTHORIZATION_CODE)throw new Error("Invalid authorization code type");if(!t.client_id||!t.redirect_uri)throw new Error("Authorization code missing required claims");if(typeof t.exp=="number"&&Date.now()>=t.exp*1e3)throw new Error("Authorization code expired");if(typeof t.id_token_enc!="string")throw new Error("Authorization code missing session");return{...t,id_token:fe(t.id_token_enc,y)}}async function Vt(e){const t=Math.floor(Date.now()/1e3);return m.sign({type:g.MCP_REFRESH_TOKEN,client_id:e.clientId,...e.idpId?{idp_id:e.idpId}:{},claims:e.claims,...e.idpAccessTokenEnc?{idp_access_token_enc:e.idpAccessTokenEnc}:{},...e.idpRefreshTokenEnc?{idp_refresh_token_enc:e.idpRefreshTokenEnc}:{},session_exp:e.sessionExp,iat:t,exp:e.sessionExp,jti:D()},y,l.HS256)}async function Kt(e){await m.verify(e,y,l.HS256);const{payload:t}=m.decode(e);if(t.type!==g.MCP_REFRESH_TOKEN)throw new Error("Invalid refresh token type");if(!t.client_id||typeof t.claims!="object"||t.claims===null)throw new Error("Refresh token missing required claims");if(typeof t.session_exp!="number")throw new Error("Refresh token missing session expiry");return t}function Bt(e){const t=e||ae(),n=t.startsWith("mcp_")?t:`mcp_${t}`;return{id:n,object:"mcpSession",uri:`urn:redocly:realm:mcp:session:${n}`}}function q(e){const t=F(e);if(!t)return e;const n=Pe(t.hostname);if(n)return t.hostname=`previewauth--${n.previewBranch}${n.after}`,G(e,t);const r=Q(t.hostname);return r?(t.hostname=`${r.projectSlug}.previewauth.${r.after}`,G(e,t)):e}function be(e){const t=F(e);if(t)return Q(t.hostname)?.previewBranch}function G(e,t){const n=e.replace(/^https?:\/\/[^/?#]+/i,"");return`${t.protocol}//${t.host}${ye(n)}`}function Q(e){const t=e.split(".preview.",2);if(t.length<2)return null;const[n,r]=t,o=n.indexOf("--");if(o===-1)return null;const s=n.slice(0,o),i=n.slice(o+2);return!s||!i||i.includes(".")?null:{projectSlug:s,previewBranch:i,after:r}}function Pe(e){const t=e.indexOf("."),n=t===-1?e:e.slice(0,t);if(!n.startsWith("preview-"))return null;const r=n.indexOf("--");if(r===-1)return null;const o=n.slice(r+2);if(!o)return null;const s=t===-1?"":e.slice(t);return{previewBranch:o,after:s}}function ve(e){return e.type===p.OIDC}function je(e){return e.type===p.SAML2}function Ft(e,t,n,r,o){return ve(e)?De(t,e,n,r,{uiLocales:o}):je(e)?Ue(t,e,n,r,o):{}}function Ue(e,t,n,r,o){const i=`<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
|
|
2
2
|
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
|
|
3
3
|
Version="2.0"
|
|
4
|
-
ID="_${
|
|
4
|
+
ID="_${D()}"
|
|
5
5
|
IssueInstant="${new Date().toISOString()}"
|
|
6
6
|
AssertionConsumerServiceURL="${e}${K.SAML_CALLBACK}"
|
|
7
7
|
AttributeConsumingServiceIndex="0">
|
|
@@ -9,4 +9,4 @@ import"../node-crypto-polyfill.js";import{DOMParser as j}from"@xmldom/xmldom";im
|
|
|
9
9
|
<samlp:NameIDPolicy
|
|
10
10
|
AllowCreate="true"
|
|
11
11
|
Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"/>
|
|
12
|
-
</samlp:AuthnRequest>`,c
|
|
12
|
+
</samlp:AuthnRequest>`,c=$e(i);return{loginUrl:Ae(t.ssoUrl,{SAMLRequest:c,RelayState:JSON.stringify({idpId:t.idpId,redirectTo:n,inviteCode:r,source:"portal",uiLocales:o})})}}function $e(e){return xe(oe(new TextEncoder().encode(e)).buffer)}function Ht(e){const t=H(e);if(t.startsWith("<samlp:Response")||t.indexOf("<saml2p:Response")>-1)return t;const n=se(new Uint8Array(atob(e).split("").map(r=>r.charCodeAt(0))));return new TextDecoder().decode(n)}function zt(e){try{return JSON.parse(H(e||""))}catch{throw new Error("Invalid OAuth2 state")}}function Wt(e){const t=new U().parseFromString(e,"application/xml"),r=f(t,"//*[local-name(.)='StatusCode']/@Value")[0]?.nodeValue?.endsWith("Success")||!1,s=f(t,"//*[local-name(.)='Response']/@Destination")[0]?.nodeValue||"",i=f(t,"//*[local-name(.)='Assertion']//*[local-name(.)='Issuer']/text()")[0],c=i&&i.nodeValue||void 0,u=f(t,"//*[local-name(.)='Audience']/text()")[0],h=u&&u.nodeValue||void 0,a=f(t,"//*[local-name(.)='Assertion']//*[local-name(.)='X509Certificate']/text()")[0]?.nodeValue||"",A=f(t,"//*[local-name(.)='Subject']//*[local-name(.)='NameID']/text()")[0],S=A&&A.nodeValue||"",T=f(t,"//*[local-name(.)='Subject']//*[local-name(.)='NameID']/@Format")[0],w=T&&T.nodeValue||"",k=f(t,"//*[local-name(.)='Conditions']/@NotOnOrAfter")[0],R=Ve(k),C={},b=f(t,"//*[local-name(.)='AttributeStatement']//*[local-name(.)='Attribute']");if(b.length)for(const P of b){const v=f(P,"./@Name")[0];if(v.nodeValue){const j=f(P,"./*[local-name(.)='AttributeValue']/text()")[0];j?.nodeValue&&(C[v.nodeValue]=j.nodeValue)}}return{uid:S,success:r,expiresAt:R,issuerId:c,entityId:h,attrs:C,cert:a,nameFormat:w,destination:s}}function Ve(e){const t=typeof e?.nodeValue=="string"&&L(Date.parse(e.nodeValue)),n=L(Date.now()),r=L(Date.now()+720*60*1e3);return t?t>n&&t<r?r:t:n}function L(e){return Math.floor(e/1e3)}const N={},_={jwks:{},missedAt:{}},Ke=6e4;function Be(e){const t=_.jwks[e];return t===void 0?!0:t===null&&Date.now()-(_.missedAt[e]??0)>=Ke}async function X(e,t){if(!N[e]){const n=t.configurationUrl?await ee(t.configurationUrl):t.configuration;N[e]=Fe()?ze(n):n}return N[e]}function Fe(){const e=ue.REDOCLY_ENFORCE_RESIDENCY;return!!e&&e.includes("host.docker.internal")}const He=["authorization_endpoint","end_session_endpoint"];function ze(e){if(typeof e!="object"||e===null)return e;const t={...e};for(const n of Object.keys(t)){if(He.includes(String(n)))continue;const r=t[n];typeof r=="string"&&r.includes("://localhost")&&(t[n]=r.replace("://localhost","://host.docker.internal"))}return t}const We=["kty","n","e","crv","x","y"];function Je(e,t){return We.every(n=>e[n]===t[n])}async function Ye(e){const t={};for(const n of Object.keys(e)){const r=e[n];if(!x(r))continue;const o=await X(n,r);if(o.jwks_uri){const s=await ee(o.jwks_uri);for(const i of s.keys){const c=t[i.kid],u=c&&Je(c,i)?[...c.idpIds,n]:[n];t[i.kid]={...i,idpIds:u},_.jwks[i.kid]=t[i.kid]}}}}function qe(e,t,n){const r=_.jwks[e]?.idpIds??[];return r.find(o=>{const s=n[o];if(!x(s))return!1;const i=O(s.audience??[]);return Y(t,i.length?i:[s.clientId])})??r.at(-1)}const Ge=6e4,Z={};async function ee(e){const t=Z[e];if(t&&Date.now()-t.failedAt<Ge)throw t.error;const n=await fetch(e,{headers:{Accept:"application/json"}}).catch(o=>{throw new M(e,`could not be reached (${o?.cause?.code??o?.message})`)}),r=n.ok?await n.json().catch(()=>{}):void 0;if(r===void 0){const o=new M(e,`answered HTTP ${n.status} (${n.headers.get("content-type")??"no content type"})`);throw Z[e]={error:o,failedAt:Date.now()},o}return r}async function Jt(e){return fetch(`${V}/oidc/userinfo`,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}}).then(t=>t.status===200?t.json():void 0).catch(()=>{})}async function Yt(e){return fetch(`${V}/api/auth/organization-session/login-code/exchange`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({code:e})}).then(t=>t.status===200?t.json():void 0).then(t=>typeof t?.token=="string"?t.token:void 0).catch(()=>{})}function Qe(e){if(!e.configurationUrl)return!1;const t=new URL(e.configurationUrl);return["localhost","127.0.0.1","blueharvest.cloud","bhstage.cloud","cloud.redocly.com","beta.redocly.com","cloud.eu.redocly.com","beta.eu.redocly.com"].some(r=>Xe(t.hostname,r))}function Xe(e,t){return e===t||e.endsWith(`.${t}`)}async function qt(e,t){const n=new U().parseFromString(e,"application/xml"),r=f(n,"//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']")[0];if(!r)throw new Error("Cannot find Signature in the SAML response");const o=Ee(t),s=new ne({publicCert:o});s.loadSignature(r);try{return s.checkSignature(e)}catch{return!1}}function Ze(e){const t=new Set,n=r=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[o,s]of Object.entries(r))typeof s=="string"?t.add(o):n(s)};return n(e),t}function et(e,t,n){if(!t)return e;const r=Ze(t),o=s=>{const i=n?.[s]||s;return r.has(i)||!!ge(t,i)};return[...e.filter(o),...e.filter(s=>!o(s))]}async function Gt(e,t,n,r){const o=n?e[n]:void 0,s=Array.isArray(o)?et(o.map(String),r?.rbacConfig,r?.teamsMapping):[];let i=s.length;const c=s.length+1;for(let u=0;u<c;u++){const h={...e,idpId:t};n&&s.length&&(h[n]=s.slice(0,i));const d=await m.sign(h,y,l.HS256),a=Buffer.byteLength(d)-de;if(a<=0)return{token:d,teamsTotal:s.length,teamsKept:i,droppedTeams:s.slice(i)};if(i===0)return null;const A=Buffer.byteLength(JSON.stringify(s.slice(0,i))),S=Math.max(1,A/i*4/3);i=Math.max(0,i-Math.max(1,Math.ceil(a/S)))}return null}function Qt(e,t,n,r){t==="urn:oasis:names:tc:SAML:2.0:nameid-format:transient"&&(e=n["http://schemas.microsoft.com/identity/claims/objectidentifier"]);let o;(t==="urn:oasis:names:tc:SAML:2.0:nameid-format:email"||t==="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress")&&(o=e),t==="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"&&e?.match(/^.+@.+/m)&&(o=e);const s=n["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"],i=s?.match(/^.+@.+/m);return o=o||n["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"]||(i?s:void 0),o=o?.toLowerCase(),{sub:e,given_name:n["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"],family_name:n["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"],name:n["http://schemas.microsoft.com/identity/claims/displayname"]||s,email:o,email_verified:!0,teams:r?Te(n[r]):[]}}function te(e,t={}){return e.map(n=>t[n]||n)}async function Xt(e,t){if(!t)return{};const n=t[I.AUTHORIZATION];if(!n)return{};try{const r=m.decode(n);if(typeof r.payload.type=="string"&&ke.has(r.payload.type))return{};if(r.header.alg===l.RS256){const h=Be(r.header.kid);h&&await Ye(e);const d=_.jwks[r.header.kid];if(!d)return h&&(_.missedAt[r.header.kid]=Date.now()),_.jwks[r.header.kid]=null,{};await m.verify(n,d,l.RS256)}else await m.verify(n,y,l.HS256);const s=r.header.alg===l.RS256?qe(r.header.kid,r.payload,e):r.payload.idpId,i=e[s]||{};if(r.header.alg===l.RS256&&typeof r.payload.exp!="number")return E.warn("Rejected id_token: it has no exp claim"),{};if(r.header.alg===l.RS256&&!Ne(r.payload,i))return E.warn("Rejected id_token: it was issued for another project"),{};const c=rt(i),u=nt(i);return{...r.payload,email:r.payload.email?.toLowerCase(),idpId:s,teams:Array.from(new Set([...te(r.payload.teams||[],u),..."defaultTeams"in i&&i.defaultTeams||[],...te("teamsClaimName"in i&&r.payload[c||""]||[],u),we])),name:tt(r.payload),isAuthenticated:!0,idpAccessToken:le(r.payload.idp_access_token,y)||t[I.IDP_ACCESS_TOKEN],federatedAccessToken:t[I.FEDERATED_ACCESS_TOKEN],federatedIdToken:t[I.FEDERATED_ID_TOKEN],authCookie:n}}catch(r){r instanceof Se||(r instanceof M?E.error(r.message):E.error("Malformed JWT token: %s",r.message))}return{}}function tt(e){return(e.firstName&&e.lastName?`${e.firstName} ${e.lastName}`:e.name||e.given_name||e.firstName||e.lastName)||e.email}function nt(e){switch(e.type){case p.SAML2:return e.teamsAttributeMap;case p.OIDC:return e.teamsClaimMap;default:return}}function rt(e){switch(e.type){case p.SAML2:return e.teamsAttributeName??$;case p.OIDC:return e.teamsClaimName;default:return $}}function f(e,t){return re.select(t,e)||[]}export{Ge as OIDC_DISCOVERY_RETRY_MS,Ke as UNKNOWN_KID_RETRY_MS,Ft as buildLoginUrl,De as buildOidcLoginUrl,vt as buildOidcLogoutUrl,Ue as buildSAML2LoginUrl,Ut as createMcpAuthorizationCode,Vt as createMcpRefreshToken,Bt as createMcpSessionResource,Ht as decodeSamlResponse,Ye as discoverJwks,$e as encodeSAML2,Yt as exchangeTokenLoginCode,Qt as extractUserClaims,Ct as getAuthProviderLoginParams,Oe as getOidcLoginParams,X as getOidcMetadata,Jt as getRedoclyTokenPayload,Me as getSaml2LoginParams,Xt as getUserParamsFromCookies,tt as getUsernameFromPayload,Le as idTokenAudienceIsAllowed,Ne as idTokenIsForThisProject,jt as isIdpIssuedToken,x as isOidcProviderConfig,Qe as isRedoclySso,Re as isSaml2ProviderConfig,bt as oidcExchangeCodeForToken,_ as oidcJwksCache,N as oidcMetadataCache,Pt as oidcRefreshTokenGrant,et as orderTeamsRbacFirst,zt as parseOidcState,be as parsePreviewBranch,Wt as parseSamlResponse,q as rewritePreviewAuthRedirectUri,Gt as signTokenWithinCookieSizeLimit,$t as verifyMcpAuthorizationCode,Kt as verifyMcpRefreshToken,qt as verifySAMLResponse};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import u from"path";import{realpath as z}from"fs/promises";import{REDOCLY_ROUTE_RBAC as G,REDOCLY_TEAMS_RBAC as j}from"@redocly/config";import{combineUrls as V,getMarkdownCopyPath as se,withoutPathPrefix as ce,withPathPrefix as A}from"@redocly/theme/core/utils";import{CACHE_CONTROL_NO_STORE_HEADER_VALUE as K,CACHE_CONTROL_PUBLIC_HTML as le,DEFAULT_IMMUTABLE_CACHE_MAX_AGE as me,DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as de,PAGE_DATA_FOLDER as ue,PUBLIC_API_DEFINITIONS_FOLDER as fe,PUBLIC_ASSETS_FOLDER as ge,STATIC_DATA_FOLDER as pe,X_REDOCLY_CACHE_CONTROL_HEADER as he,X_REDOCLY_CACHE_CONTROL_PUBLIC_HTML as Ee}from"../../constants/common.js";import{AuthCookieNames as W}from"../../../constants/common.js";import{removeTrailingSlash as Z}from"../../../utils/url/remove-trailing-slash.js";import{findInIterable as Re}from"../../../utils/collection/find-in-iterable.js";import{sanitizeRedirectPathname as Ae}from"../../../utils/url/sanitize-redirect-pathname.js";import{envConfig as Ce}from"../../config/env-config.js";import{addLeadingSlash as _e}from"../../../utils/url/add-leading-slash.js";import{isPathInFolder as I}from"../../../utils/path/is-path-in-folder.js";import{resolveLlmsTxtMd as J,resolvePageMarkdownUrl as Le}from"../../utils/llmstxt/resolve-llms-txt-md.js";import{removeLeadingSlash as S}from"../../../utils/url/remove-leading-slash.js";import{decodeRequestPath as Te}from"../../utils/decode-request-path.js";import{AI_INDEX_EXPORT_FOLDER as we,SEARCH_DATA_EXPORT_FOLDER as Oe}from"../../constants/plugins/search.js";import{processRedirects as Pe}from"./helpers/process-redirects.js";import{renderPage as De,getServerProps as Ie}from"../../ssr/index.js";import{canAccessAsset as Se,canAccessResource as Q}from"../../utils/rbac.js";import{handleErrorPageRender as C,handleUnauthorized as x,handleUnauthorizedAsset as ee}from"../utils.js";import{DEFAULT_MAX_AGE_FOR_MIME_TYPE as Ue,MIME_TYPES as ye}from"../mime-types.js";import{fileExistsAsync as Fe}from"../../utils/index.js";import{isAiAgentRequest as Me}from"../../utils/ai-agent-detection.js";import{getRedirectRoute as be}from"../utils/legacy-openapi-redirects.js";import{getContentTypeHeaderValue as te}from"../utils/content-type.js";import{telemetry as qe}from"../../../cli/telemetry/index.js";import{telemetry as Ne}from"../../telemetry/index.js";const He=[Oe,we,pe,S(fe),S(de),ue];async function ve(e,f){try{const[d,a]=await Promise.all([z(e),z(f)]);return He.some(t=>I(d,u.join(a,t)))}catch{return!1}}function ke(e=""){return e.split(";").some(f=>{const d=f.split("=")[0].trim();let a=d;try{a=decodeURIComponent(d)}catch{}return a===W.FEDERATED_ACCESS_TOKEN||a===W.FEDERATED_ID_TOKEN})}function gt(e,f,d,a){return async t=>{const U=t.get("logger"),s=t.req,l=new URL(s.url),_=l.pathname.replace(/\/{2,}/g,"/"),y=Te(_);if(y===void 0)return t.text("Bad Request",400);const g=Ce.isProductionEnv?301:302;if(_!==l.pathname)return t.newResponse(null,g,{Location:_+l.search});const r=ce(y),F=u.parse(r).ext.toLowerCase()===".md",M=Me({accept:s.header("accept"),signatureAgent:s.header("signature-agent"),signature:s.header("signature"),signatureInput:s.header("signature-input"),userAgent:s.header("user-agent")}),i=_e(Z(r)),o=(s.method==="GET"||s.method==="HEAD")&&!F?e.getRouteBySlug(i,{followRedirect:!1})||Re(e.routesBySlug?.values(),n=>n.hasClientRoutes&&(r===n.slug||r.startsWith(n.slug+"/"))):void 0,b=e.getRedirect(i);if(b){const n=Pe({redirect:b,reqUrlSearch:l.search});return Ne.sendRedirectMessage([{id:i,object:"redirect",uri:`urn:redocly:realm:api:redirect:${i}`,from:i,templateId:n.type.toString()}]),t.newResponse(null,n.type,{Location:n.location})}if(o?.metadata?.type==="openapi"){const n=be(l.pathname);if(n)return U.info("Legacy OpenAPI docs redirect from "+l.pathname),t.newResponse(null,g,{Location:encodeURI(n)});if(r.match(/[A-Z]/))return U.warn("Redirect to lowercase route to avoid 404 error"),t.newResponse(null,g,{Location:encodeURI(A(r.toLowerCase()))})}if(r.endsWith("/")&&r!=="/"){const n=Ae(new URL(i||"/",t.req.url).pathname);return t.newResponse(null,g,{Location:A((n==="/"?"/":Z(n))+l.search)})}const{isAuthenticated:p,teams:L,claims:{email:T}}=t.get("auth");if(o&&!Q(o,{isAuthenticated:p,email:T,teams:L},e.config.access?.rbac,e.config.access?.requiresLogin))return p?C(t,e,{slug:o.slug,[j]:o[j],[G]:o[G]},403):x(t,e,o.slug);const h=o&&M?se(i):void 0,q=h?await J(h,e,a):void 0,w=q?.exists??!1;if(o&&(!M||!w)){const n=await f(o),D=await Le(i,e,a),oe={...await Ie(o,t,n,e),...D?{markdownUrl:D}:{}},{html:re,statusCode:B,error:ie}=await De(o,oe,t,e,qe),X=e.config.access?.rbac,Y=!ke(t.req.header("cookie"))&&!e.config.access?.requiresLogin&&(!X||!Object.keys(X).length),$=B>=400||!!ie||!!e.compilationErrors?.length,ae=Y&&!$;let R;return $?R=K:Y?R=le:R="private",t.html(re,B,{"Cache-Control":R,...ae&&{[he]:Ee}})}const E=h&&w?h:r,ne=S(E),c=u.resolve(e.outdir,ne);if(!I(c,e.outdir))return ee(t);const N=F?await J(r,e,a):void 0,m=N?.route;if(m&&!Q(m,{isAuthenticated:p,email:T,teams:L},e.config.access?.rbac,e.config.access?.requiresLogin))return x(t,e,r);if(!w&&!m){if(await ve(c,e.outdir))return C(t,e,{slug:i},404);const n=e.getGlobalConfig("access");if(!Se(E,n?.rbac||{},n?.requiresLogin||!1,e.getGlobalConfig("directoryPaths"),{isAuthenticated:p,email:T,teams:L}))return I(E,ge)?ee(t):C(t,e,{slug:i},404)}const O=ye[u.extname(c)]||"text/plain",P=c.match(/assets\/.*\.[a-f0-9]{8,}\..+/)||c.match(/runtime\/chunks\/.*/)?me:Ue[O],H=P?{"Cache-Control":`public, max-age=${P}, immutable`,Expires:new Date(Date.now()+P*1e3).toUTCString()}:{"Cache-Control":K},v=s.query("download")!=null,k=q?.content??N?.content;if(k!==void 0)return t.newResponse(k,200,{"Content-Type":te(O),"Access-Control-Allow-Origin":"*",...H,...m&&{"X-Robots-Tag":"noindex, follow",...e.config.seo?.siteUrl&&{Link:`<${V(e.config.seo.siteUrl,A(m.slug))}>; rel="canonical"`}},...v&&{"Content-Disposition":`attachment; filename="${u.basename(E)}"`}});if(await Fe(c)){const n=await d(c);return t.newResponse(n,200,{"Content-Type":te(O),"Access-Control-Allow-Origin":"*",...H,...m&&{"X-Robots-Tag":"noindex, follow",...e.config.seo?.siteUrl&&{Link:`<${V(e.config.seo.siteUrl,A(m.slug))}>; rel="canonical"`}},...v&&{"Content-Disposition":`attachment; filename="${u.basename(c)}"`}})}else return C(t,e,{slug:i},404)}}export{gt as dynamicRouteHandler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{context as s,SpanStatusCode as n,trace as
|
|
1
|
+
import{context as s,SpanStatusCode as n,trace as a}from"@opentelemetry/api";import{HTTPException as o}from"hono/http-exception";import{envConfig as i}from"../../config/env-config.js";import{logger as r}from"../../tools/notifiers/logger.js";import{OidcDiscoveryError as f}from"../../utils/errors.js";const g=e=>{const t=a?.getSpan(s.active());return e instanceof Error&&"name"in e&&e.name==="URIError"?(t&&(t.setStatus({code:n.OK}),t.end()),new Response("Malformed URL",{status:400})):e instanceof SyntaxError?(t&&(t.setStatus({code:n.OK}),t.end()),new Response("Invalid JSON",{status:400})):e instanceof o&&e.status<500?(t&&(t.setStatus({code:n.OK}),t.end()),e.getResponse()):(t&&(t.setStatus({code:n.ERROR,message:e.message}),t.recordException(e),t.end()),e instanceof f?(r.error(e.message),new Response("Bad gateway: the identity provider is unreachable or returned an invalid response",{status:502})):i.isDevelopMode&&e?.name==="PageMissingDefaultExportError"?new Response(e.message,{status:200}):new Response("Internal Server Error",{status:500}))};export{g as errorHandler};
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { RedirectConfig } from '@redocly/config';
|
|
2
|
-
import type {
|
|
2
|
+
import type { ContentfulStatusCode } from 'hono/utils/http-status';
|
|
3
3
|
/**
|
|
4
4
|
*
|
|
5
5
|
* Processes a redirect by normalizing the location and adding search parameters.
|
|
6
6
|
* Does not handle wildcard redirects. Only direct redirects are supported.
|
|
7
|
+
* Without an explicit `type`, the redirect is permanent (301) only in production;
|
|
8
|
+
* elsewhere it is temporary (302) so browsers do not cache an edited redirect.
|
|
7
9
|
*
|
|
8
10
|
* @param options - The options for the redirect.
|
|
9
11
|
* @param options.redirect - The redirect configuration.
|
|
@@ -12,11 +14,11 @@ import type { StatusCode } from 'hono/utils/http-status';
|
|
|
12
14
|
*
|
|
13
15
|
* @example
|
|
14
16
|
* processRedirects({ redirect: { to: '/new-page' } });
|
|
15
|
-
* // Returns: { location: '/new-page', type: 301 }
|
|
17
|
+
* // Returns: { location: '/new-page', type: 301 } in production, 302 otherwise
|
|
16
18
|
*
|
|
17
19
|
* @example
|
|
18
20
|
* processRedirects({ redirect: { to: '/new-page' }, reqUrlSearch: '?param=value' });
|
|
19
|
-
* // Returns: { location: '/new-page?param=value', type: 301 }
|
|
21
|
+
* // Returns: { location: '/new-page?param=value', type: 301 } in production, 302 otherwise
|
|
20
22
|
*
|
|
21
23
|
* @example
|
|
22
24
|
* processRedirects({ redirect: { to: 'https://example.com', type: 302 } });
|
|
@@ -27,6 +29,6 @@ export declare function processRedirects({ redirect, reqUrlSearch, }: {
|
|
|
27
29
|
reqUrlSearch?: string;
|
|
28
30
|
}): {
|
|
29
31
|
location: string;
|
|
30
|
-
type:
|
|
32
|
+
type: ContentfulStatusCode;
|
|
31
33
|
};
|
|
32
34
|
//# sourceMappingURL=process-redirects.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{removeTrailingSlash as i}from"../../../../utils/url/remove-trailing-slash.js";import{isLocalLink as
|
|
1
|
+
import{removeTrailingSlash as i}from"../../../../utils/url/remove-trailing-slash.js";import{isLocalLink as r}from"../../../../utils/path/is-local-link.js";import{withPathPrefix as e}from"@redocly/theme/core/utils";import{envConfig as c}from"../../../config/env-config.js";function l({redirect:o,reqUrlSearch:t=""}){const n=r(o.to)?e(o.to):o.to;return{location:a(i(n))+t,type:o?.type||(c.isProductionEnv?301:302)}}function a(o){return encodeURI(o).replace(/%25([0-9A-Fa-f]{2})/g,"%$1")}export{l as processRedirects};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{serveStatic as c}from"hono/serve-static";import{withPathPrefix as i,withoutPathPrefix as H}from"@redocly/theme/core/utils";import{ServerRoutes as l}from"../../../constants/api.js";import{LLMS_TXT_FILE_NAME as L,PUBLIC_STATIC_FOLDER as C}from"../../constants/common.js";import{envConfig as I}from"../../config/env-config.js";import{authMiddleware as g}from"../middleware/authMiddleware.js";import{ensureSearchData as h}from"../middleware/ensureSearchData.js";import{dynamicMiddleware as D}from"../middleware/dynamic-middleware/dynamic-middleware.js";import{installRoutes as P}from"../../plugins/dev-onboarding/api/routes/index.js";import{installSkillsRoutes as N}from"./skills/skills-routes.js";import{llmsTxtHandler as M}from"./llms-txt.js";import{authorizeHandler as w,oidcCallbackHandler as B,logoutHandler as E,postLogoutHandler as v,idpLoginHandler as F,redoclyLoginCallbackHandler as G,samlCallbackHandler as U,redoclyTokenLoginHandler as Y,inviteHandler as y}from"./auth.js";import{appDataHandler as K}from"./app-data.js";import{searchFacetsHandler as k,searchHandler as x}from"./search.js";import{dynamicRouteHandler as b}from"./dynamic-route.js";import{pageDataHandler as V,sharedPageDataHandler as q}from"./page-data.js";import{pathPrefixRedirectHandler as X}from"./path-prefix-redirect.js";import{getRoutesByLineHandler as _,resolvePathHandler as S,resolvePathsHandler as $,resolveSlugHandler as f}from"./resolve-route.js";import{feedbackHandler as j}from"./feedback.js";import{loggerMiddleware as z}from"../middleware/loggerMiddleware.js";import{responseHeadersMiddleware as W}from"../middleware/responseHeadersMiddleware.js";import{idleTimeoutMiddleware as Z}from"../middleware/idleTimeoutMiddleware.js";import{otelTracesHandler as u}from"./otel/otel.js";import{healthCheckHandler as J}from"./health.js";import{askAiHandler as Q,aiAssistantEscalationsHandler as aa,aiAssistantFeedbackHandler as ea,AI_ASSISTANT_IDENTITY_STATUS_HEADER as ia}from"./ask-ai.js";import{semanticSearchHandler as la}from"./semantic-search.js";import{replayOauth2RedirectCallbackHandler as ta}from"./replay-oauth2-redirect.js";import{corsProxyHandler as r}from"./cors-proxy.js";import{corsMiddleware as m}from"../middleware/corsMiddleware.js";import{installApiRoutes as ma}from"./api-routes/api-routes.js";import{cookieMiddleware as oa}from"../middleware/cookieMiddleware.js";import{staticContentHandler as da}from"../routes/static-content.js";import{infoHandler as O}from"./info.js";import{catalogHandler as Aa}from"./catalog/catalog.js";import{catalogRelationsHandler as na}from"./catalog/catalog-relations.js";import{bffCatalogHandler as sa}from"./catalog/bff-catalog.js";import{bffCatalogRevisionsHandler as pa}from"./catalog/bff-catalog-revisions.js";import{bffCatalogRelatedEntitiesHandler as Ta}from"./catalog/bff-catalog-related-entities.js";import{catalogAuthMiddleware as o}from"../middleware/catalogAuthMiddleware.js";import{telemetryMiddleware as Ea}from"../middleware/telemetry-middleware.js";import{errorHandler as _a}from"./error.js";import{installMcpRoutes as Sa}from"./mcp-routes/mcp-routes.js";import{jsonValidatorMiddleware as n}from"../middleware/jsonValidatorMiddleware.js";import{otelTracesRequestSchema as fa}from"../../../api-schemas/otel-traces.js";import{searchFacetsRequestSchema as ra}from"../../../api-schemas/search-facets.js";import{searchRequestSchema as Oa}from"../../../api-schemas/search.js";function Te(a,e,
|
|
1
|
+
import{serveStatic as c}from"hono/serve-static";import{withPathPrefix as i,withoutPathPrefix as H}from"@redocly/theme/core/utils";import{ServerRoutes as l}from"../../../constants/api.js";import{LLMS_TXT_FILE_NAME as L,PUBLIC_STATIC_FOLDER as C}from"../../constants/common.js";import{envConfig as I}from"../../config/env-config.js";import{authMiddleware as g}from"../middleware/authMiddleware.js";import{ensureSearchData as h}from"../middleware/ensureSearchData.js";import{dynamicMiddleware as D}from"../middleware/dynamic-middleware/dynamic-middleware.js";import{installRoutes as P}from"../../plugins/dev-onboarding/api/routes/index.js";import{installSkillsRoutes as N}from"./skills/skills-routes.js";import{llmsTxtHandler as M}from"./llms-txt.js";import{authorizeHandler as w,oidcCallbackHandler as B,logoutHandler as E,postLogoutHandler as v,idpLoginHandler as F,redoclyLoginCallbackHandler as G,samlCallbackHandler as U,redoclyTokenLoginHandler as Y,inviteHandler as y}from"./auth.js";import{appDataHandler as K}from"./app-data.js";import{searchFacetsHandler as k,searchHandler as x}from"./search.js";import{dynamicRouteHandler as b}from"./dynamic-route.js";import{pageDataHandler as V,sharedPageDataHandler as q}from"./page-data.js";import{pathPrefixRedirectHandler as X}from"./path-prefix-redirect.js";import{getRoutesByLineHandler as _,resolvePathHandler as S,resolvePathsHandler as $,resolveSlugHandler as f}from"./resolve-route.js";import{feedbackHandler as j}from"./feedback.js";import{loggerMiddleware as z}from"../middleware/loggerMiddleware.js";import{responseHeadersMiddleware as W}from"../middleware/responseHeadersMiddleware.js";import{idleTimeoutMiddleware as Z}from"../middleware/idleTimeoutMiddleware.js";import{otelTracesHandler as u}from"./otel/otel.js";import{healthCheckHandler as J}from"./health.js";import{askAiHandler as Q,aiAssistantEscalationsHandler as aa,aiAssistantFeedbackHandler as ea,AI_ASSISTANT_IDENTITY_STATUS_HEADER as ia}from"./ask-ai.js";import{semanticSearchHandler as la}from"./semantic-search.js";import{replayOauth2RedirectCallbackHandler as ta}from"./replay-oauth2-redirect.js";import{corsProxyHandler as r}from"./cors-proxy.js";import{corsMiddleware as m}from"../middleware/corsMiddleware.js";import{installApiRoutes as ma}from"./api-routes/api-routes.js";import{cookieMiddleware as oa}from"../middleware/cookieMiddleware.js";import{staticContentHandler as da}from"../routes/static-content.js";import{infoHandler as O}from"./info.js";import{catalogHandler as Aa}from"./catalog/catalog.js";import{catalogRelationsHandler as na}from"./catalog/catalog-relations.js";import{bffCatalogHandler as sa}from"./catalog/bff-catalog.js";import{bffCatalogRevisionsHandler as pa}from"./catalog/bff-catalog-revisions.js";import{bffCatalogRelatedEntitiesHandler as Ta}from"./catalog/bff-catalog-related-entities.js";import{catalogAuthMiddleware as o}from"../middleware/catalogAuthMiddleware.js";import{telemetryMiddleware as Ea}from"../middleware/telemetry-middleware.js";import{errorHandler as _a}from"./error.js";import{installMcpRoutes as Sa}from"./mcp-routes/mcp-routes.js";import{jsonValidatorMiddleware as n}from"../middleware/jsonValidatorMiddleware.js";import{otelTracesRequestSchema as fa}from"../../../api-schemas/otel-traces.js";import{searchFacetsRequestSchema as ra}from"../../../api-schemas/search-facets.js";import{searchRequestSchema as Oa}from"../../../api-schemas/search.js";function Te(a,e,A){const{resolveRouteData:s,readStaticAsset:p,llmsTxtGenerator:d}=A;a.use("*",Z()),a.use("*",oa()),a.use("*",D(e)),a.use("*",g(e)),a.use("*",z()),a.use("*",W(e)),a.use("*",Ea()),a.use(i("*"),c({root:`./${C}`,getContent:(t,R)=>da(t,R,e,p),rewriteRequestPath:t=>H(t)})),a.use(i(l.FEEDBACK),m({allowMethods:["POST"]})),a.use(i(l.ASK_AI),m({allowMethods:["POST"],exposeHeaders:[ia]})),a.use(i(l.AI_ASSISTANT_ESCALATIONS),m({allowMethods:["POST"]})),a.use(i(l.AI_ASSISTANT_FEEDBACK),m({allowMethods:["POST"]})),a.use(i(l.SEMANTIC_SEARCH),m({allowMethods:["POST"]})),a.use("*",Ra(e));const T=h(e);a.use(i(l.INFO),O()),I.NEW_CATALOG_ENABLED&&(a.use(i(l.CATALOG_ENTITIES),o({serverOutDir:e.serverOutDir}),Aa(e)),a.use(i(l.CATALOG_ENTITIES_RELATIONS),o({serverOutDir:e.serverOutDir}),na(e)),a.get(i(l.BFF_CATALOG_ENTITIES),o({serverOutDir:e.serverOutDir,protectReadMethods:!1}),sa(e)),a.get(i(l.BFF_CATALOG_RELATED_ENTITIES),o({serverOutDir:e.serverOutDir,protectReadMethods:!1}),Ta(e)),a.get(i(l.BFF_CATALOG_REVISIONS),o({serverOutDir:e.serverOutDir,protectReadMethods:!1}),pa(e))),a.get(i(l.SHARED_PAGE_DATA),q(e)),a.get(i(l.PAGE_DATA),V(e,s,d)),a.get(i(l.APP_DATA),K(e)),a.post(i(l.SEARCH),T,n(Oa),x(e)),a.post(i(l.SEARCH_FACETS),T,n(ra),k(e)),a.post(i(l.AUTHORIZATION),t=>w(t,e)),a.post(i(l.LOGOUT),E(e)),a.get(i(l.LOGOUT),E(e)),a.get(i(l.POST_LOGOUT),v(e)),a.get(i(l.OIDC_CALLBACK),B(e)),a.get(i(l.REDOCLY_TOKEN_LOGIN),Y(e)),a.get(i(l.REDOCLY_LOGIN_CALLBACK),G()),a.get(i(l.IDP_LOGIN),F(e)),a.post(i(l.SAML_CALLBACK),U(e)),a.get(i(l.INVITE),y(e)),a.get(i(l.HEALTH),J),Sa(a,e),P(a,e),N(a,e),a.all(i(l.CORS_PROXY),r(e)),a.all(i(`${l.CORS_PROXY}/*`),r(e)),ma(a,e),a.post(i(l.FEEDBACK),j(e)),a.post(i(l.RESOLVE_ROUTE_BY_PATH),S(e)),a.post(i(l.RESOLVE_ROUTES_BY_PATHS),$(e)),a.post(i(l.RESOLVE_ROUTE_BY_SLUG),f(e)),a.post(i(l.ASK_AI),Q(e)),a.post(i(l.AI_ASSISTANT_ESCALATIONS),aa(e)),a.post(i(l.AI_ASSISTANT_FEEDBACK),ea(e)),a.post(i(l.SEMANTIC_SEARCH),la(e)),a.get(i(l.GET_ROUTES_BY_LINE),_(e)),a.post(i(l.OTEL_TRACES),n(fa),u),a.get(i(l.REPLAY_OAUTH2_CALLBACK),ta),d&&a.get(i(`/${L}`),M(d)),a.all(i("/*"),b(e,s,p,d)),a.get("*",X),a.onError(_a)}function Ra(a){return async(e,A)=>{await a.waitForPluginsLifecycle(),await A()}}function Ee(a,e){a.get(i(l.INFO),O()),a.post(i(l.RESOLVE_ROUTE_BY_PATH),S(e)),a.post(i(l.RESOLVE_ROUTE_BY_SLUG),f(e)),a.get(i(l.GET_ROUTES_BY_LINE),_(e))}export{Ee as installDevRoutes,Te as installProdRoutes,Ra as waitForPluginsLifecycle};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Handler } from 'hono';
|
|
2
2
|
import type { Store } from '../../store';
|
|
3
3
|
import type { RouteDataResolver } from './index';
|
|
4
|
-
|
|
4
|
+
import type { LlmsTxtGenerator } from '../../types';
|
|
5
|
+
export declare function pageDataHandler(store: Store, resolveRouteData: RouteDataResolver, llmsTxtGenerator?: LlmsTxtGenerator): Handler;
|
|
5
6
|
export declare function sharedPageDataHandler(store: Store): Handler;
|
|
6
7
|
//# sourceMappingURL=page-data.d.ts.map
|