@redocly/realm 0.136.0-next.0 → 0.136.0-next.2
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 +30 -0
- package/dist/client/app/hooks/catalog/useCatalogViewMode.js +1 -1
- package/dist/client/app/hooks/catalog/useFetchCatalogEntities.js +1 -1
- package/dist/client/app/hooks/catalog/useFetchCatalogEntitiesRelations.js +1 -1
- package/dist/client/app/hooks/catalog/useSearchTracker.d.ts +2 -5
- package/dist/client/app/hooks/catalog/useSearchTracker.js +1 -1
- package/dist/server/api-routes/execute-api-route.js +1 -1
- package/dist/server/api-routes/helpers/enhance-context.d.ts +3 -1
- package/dist/server/api-routes/helpers/enhance-context.js +1 -1
- package/dist/server/api-routes/helpers/is-mock-server.d.ts +2 -0
- package/dist/server/api-routes/helpers/is-mock-server.js +1 -0
- package/dist/server/api-routes/mock-server/kv-state-store.d.ts +3 -0
- package/dist/server/api-routes/mock-server/kv-state-store.js +1 -0
- package/dist/server/api-routes/mock-server/mock-js-executor.d.ts +3 -0
- package/dist/server/api-routes/mock-server/mock-js-executor.js +13 -0
- package/dist/server/api-routes/run-api-routes-worker.js +1 -1
- package/dist/server/config/env-config.d.ts +4 -0
- package/dist/server/config/env-schema.d.ts +10 -0
- package/dist/server/config/env-schemas/catalog.d.ts +3 -0
- package/dist/server/config/env-schemas/catalog.js +1 -1
- package/dist/server/config/env-schemas/feature-flags.d.ts +4 -0
- package/dist/server/config/env-schemas/feature-flags.js +1 -1
- package/dist/server/plugins/catalog-entities/database/catalog-entities-diff-publisher.d.ts +27 -0
- package/dist/server/plugins/catalog-entities/database/catalog-entities-diff-publisher.js +12 -0
- package/dist/server/plugins/catalog-entities/database/catalog-entities-publisher.js +1 -12
- package/dist/server/plugins/catalog-entities/database/catalog-entities-revisions-pruner.d.ts +22 -0
- package/dist/server/plugins/catalog-entities/database/catalog-entities-revisions-pruner.js +62 -0
- package/dist/server/plugins/catalog-entities/database/consts.d.ts +5 -0
- package/dist/server/plugins/catalog-entities/database/consts.js +1 -1
- package/dist/server/plugins/catalog-entities/database/repositories/entities/entities-write-repository.js +1 -1
- package/dist/server/plugins/catalog-entities/extensions/extractors/api-description/base.d.ts +4 -1
- package/dist/server/plugins/catalog-entities/extensions/extractors/api-description/base.js +1 -1
- package/dist/server/plugins/catalog-entities/plugin.js +1 -1
- package/dist/server/plugins/markdown/markdoc/plugins/utils.d.ts +5 -0
- package/dist/server/plugins/markdown/markdoc/plugins/utils.js +1 -1
- package/dist/server/plugins/markdown/runtime-transform.js +1 -1
- package/dist/server/plugins/mcp/auth/auth-handlers.d.ts +2 -0
- package/dist/server/plugins/mcp/auth/auth-handlers.js +1 -1
- package/dist/server/plugins/mcp/codemode/constants.d.ts +3 -0
- package/dist/server/plugins/mcp/codemode/constants.js +1 -1
- package/dist/server/plugins/mcp/codemode/sandbox/create-sandbox-setup.d.ts +10 -0
- package/dist/server/plugins/mcp/codemode/sandbox/create-sandbox-setup.js +11 -0
- package/dist/server/plugins/mcp/codemode/sandbox/polyfills.d.ts +2 -0
- package/dist/server/plugins/mcp/codemode/sandbox/{sandbox-polyfills.js → polyfills.js} +7 -8
- package/dist/server/plugins/mcp/codemode/tools/execute.js +1 -1
- package/dist/server/plugins/mcp/codemode/types.d.ts +0 -8
- package/dist/server/sandbox/constants/host-functions.d.ts +3 -0
- package/dist/server/sandbox/constants/host-functions.js +1 -0
- package/dist/server/sandbox/constants/sandbox.d.ts +6 -0
- package/dist/server/sandbox/constants/sandbox.js +1 -0
- package/dist/server/sandbox/sandbox.d.ts +8 -0
- package/dist/server/sandbox/sandbox.js +3 -0
- package/dist/server/sandbox/types.d.ts +24 -0
- package/dist/server/sandbox/types.js +0 -0
- package/dist/server/sandbox/utils/eval-guest-code.d.ts +15 -0
- package/dist/server/sandbox/utils/eval-guest-code.js +1 -0
- package/dist/server/sandbox/utils/execution-budget.d.ts +11 -0
- package/dist/server/sandbox/utils/execution-budget.js +1 -0
- package/dist/server/sandbox/utils/setup-host-functions.d.ts +18 -0
- package/dist/server/sandbox/utils/setup-host-functions.js +5 -0
- package/dist/server/store.js +1 -1
- package/dist/server/utils/fetch-with-client.d.ts +10 -0
- package/dist/server/utils/fetch-with-client.js +1 -0
- package/dist/server/utils/sandbox-context.d.ts +18 -0
- package/dist/server/utils/sandbox-context.js +1 -0
- package/dist/server/web-server/middleware/apiKeyMiddleware.js +1 -1
- package/dist/server/web-server/middleware/catalogAuthMiddleware.js +1 -1
- package/dist/server/web-server/routes/ask-ai.js +1 -1
- package/dist/server/web-server/routes/auth.js +1 -1
- package/dist/server/web-server/routes/catalog/helpers/upsert-pages-stats.js +1 -1
- package/dist/server/web-server/routes/feedback.js +1 -1
- package/dist/server/web-server/routes/mcp-routes/mcp-oauth.d.ts +5 -4
- package/dist/server/web-server/routes/mcp-routes/mcp-oauth.js +1 -1
- package/dist/server/web-server/routes/mcp-routes/mcp-routes.js +1 -1
- package/dist/server/web-server/routes/semantic-search.js +1 -1
- package/dist/server/workers/api-routes-worker-pool.js +1 -1
- package/dist/server/workers/mcp-tool-worker-pool.js +1 -1
- package/dist/server/workers/worker-pool.d.ts +1 -0
- package/dist/server/workers/worker-pool.js +1 -1
- package/package.json +7 -7
- package/dist/server/plugins/mcp/codemode/sandbox/sandbox-polyfills.d.ts +0 -3
- package/dist/server/plugins/mcp/codemode/sandbox/sandbox.d.ts +0 -3
- package/dist/server/plugins/mcp/codemode/sandbox/sandbox.js +0 -15
|
@@ -1 +1 @@
|
|
|
1
|
-
import{and as v,eq as c,isNull as E,or as
|
|
1
|
+
import{and as v,eq as c,isNull as E,or as x,sql as I}from"drizzle-orm";import{VERSION_NOT_SPECIFIED as V}from"@redocly/theme/core/constants";import{sha1 as F}from"../../../../../utils/crypto/sha1.js";import{envConfig as K}from"../../../../../config/env-config.js";import{entitiesTable as i}from"../../../../../providers/database/databases/sqlite-db/schemas/entities-table.js";import{convertFilterToWhereCondition as O}from"../../../../../providers/database/pagination/filter.js";import{entitiesRelationsTable as a}from"../../../../../providers/database/databases/sqlite-db/schemas/entities-relations-table.js";import{promiseMapLimit as p}from"../../../../../utils/async/promise-map-limit.js";import{RevisionRepository as z}from"../common/revision-repository.js";import{VersionRepository as H}from"../common/version-repository.js";import{EntityAttributesWriteRepository as P}from"../entityAttributes/entity-attributes-write-repository.js";import{createEntityDbRecord as W}from"../../mappers/create-entity-db-record.js";import{createEntityReadModel as k}from"../../mappers/create-entity-read-model.js";import{createEntityRelationDbRecordFromFileSchema as j}from"../../mappers/create-entity-relation-db-record-from-file-schema.js";import{createEntityRelationDbRecordFromDto as G}from"../../mappers/create-entity-relation-db-record-from-dto.js";import{EntitiesReadRepository as M}from"./entities-read-repository.js";import{RelationsReadRepository as U}from"../relations/relations-read-repository.js";import{RelationsWriteRepository as $}from"../relations/relations-write-repository.js";const m=15;class de{#e;#t;#n;#o;#i;#s;#a;#l;#r;constructor(e,s,r){this.#e=e,this.#i=s,this.#s=r,this.#t=new z(e),this.#n=new H(e),this.#o=new P(e),this.#a=new M(e),this.#l=new U(e),this.#r=new $(e,s,r)}async createEntity({entity:e,source:s,fileHash:r,sourceFile:o,isRootEntity:t,isDeleted:n,rbacTeams:u,errorOnSkip:d=!1,revision:h}){const{relations:l=[],...f}=e,y=F(JSON.stringify(f)),g=e.version??V,C=h??new Date().toISOString(),L=await this.#t.shouldSkipRevisionCreation(e.key,g,y,t,n);Array.isArray(u)&&await this.#o.upsertEntityAttributes({entityKey:e.key,rbacTeams:u,organizationId:this.#i,projectId:this.#s});const D=K.isDevelopMode&&!K.REDOCLY_INTERNAL_DEV;if(l?.length&&!D&&await this.#r.createEntityRelations(l.map(N=>({...N,sourceKey:e.key,targetKey:N.key,sourceFile:o??null,fileHash:r??null}))),L){if(d)throw new Error("Entity validation failed: entity already exists");return null}const{shouldSetNewCurrentRevision:R,hasCurrentRevision:_}=await this.#t.getCurrentRevisionInfo({key:e.key,version:g,revision:C}),w=W({entity:{...e,revision:C,hash:y,isCurrent:R,isDefaultVersion:R,isDeleted:n,version:g},organizationId:this.#i,projectId:this.#s,source:s,sourceFile:o??null,fileHash:r??null}),{key:A,...T}=w;if(R&&_&&(await this.#t.markAllRevisionsAsNotCurrent(A),await this.#n.markAllVersionsAsNotDefault(A)),D)return await this.#u(w,l);const S=await this.#e.client.insert(i).values(w).onConflictDoUpdate({target:[i.key,i.source,i.revision,i.version],set:T}).returning();return S.length?k(S[0]):null}async updateEntity(e,s){const{shouldSetNewCurrentRevision:r,hasCurrentRevision:o}=await this.#t.getCurrentRevisionInfo({key:s.key,version:e.version??s.version??V,revision:s.revision});r&&o&&(await this.#t.markAllRevisionsAsNotCurrent(s.key),await this.#n.markAllVersionsAsNotDefault(s.key));const t=W({entity:{...s,...e,hash:F(JSON.stringify({...s,...e})),isCurrent:r,isDefaultVersion:r,createdAt:s.createdAt??void 0},organizationId:this.#i,projectId:this.#s,source:"remote",sourceFile:null,fileHash:null}),{key:n,source:u,scorecardsStatus:d,...h}=t,l=await this.#e.client.insert(i).values(t).onConflictDoUpdate({target:[i.key,i.source,i.revision,i.version],set:{...h,scorecardsStatus:I`CASE WHEN ${i.scorecardsStatus} = 'CALCULATING' THEN 'CANCELLED' ELSE 'OUTDATED' END`}}).returning();return l.length?k(l[0]):null}async setEntitiesAsOutdated(e){const s=O(e);await this.#e.client.update(i).set({scorecardsStatus:"OUTDATED"}).where(s)}async#u(e,s){const{key:r,source:o,version:t,...n}=e,h=await this.#e.client.select({id:i.id}).from(i).where(v(c(i.key,r),t?c(i.version,t):E(i.version))).limit(1).get()!=null?await this.#e.client.update(i).set(n).where(v(c(i.key,r),t?c(i.version,t):E(i.version))).returning():await this.#e.client.insert(i).values(e).onConflictDoUpdate({target:[i.key,i.source,i.revision,i.version],set:n}).returning(),l=s?.map(f=>{const y=j({relation:f,sourceFile:e.sourceFile??"",fileHash:e.fileHash??"",sourceKey:e.key,sourceVersion:e.version??null,sourceRevision:e.revision??null,organizationId:this.#i,projectId:this.#s});return this.#e.client.insert(a).values(y).onConflictDoUpdate({target:[a.sourceKey,a.targetKey,a.sourceVersion,a.targetVersion,a.sourceRevision,a.targetRevision,a.sourceToTargetRelation],set:y}).run()})??[];return await p(l,m,async f=>f),k(h[0])}async softDeleteEntitiesWithRelations({filter:e,revision:s,fileHash:r}){const t={op:"AND",conditions:[e,{field:"is_deleted",operator:"equal",value:!1}]};for(;;){const n=await this.#a.getEntities({paginationParams:{filter:t,limit:500}});if(n.items.length===0)break;const u=await this.#c({entities:n.items,revision:s,fileHash:r});await this.#d(u,s)}}async deleteEntity(e){return await this.#r.deleteEntityRelationsOnEntityRemoval(e),await this.#e.client.delete(i).where(c(i.id,e.id)),await this.#t.ensureDefaultAndCurrentRevisionForKey(e.key),e.id}async deleteEntities(e){const s=O(e);if(!s)return!1;const r=await this.#e.client.delete(i).where(s).returning({key:i.key,source:i.source,isCurrent:i.isCurrent,isDefaultVersion:i.isDefaultVersion,version:i.version});if(r.length===0)return!0;const o=r.reduce((t,n)=>((n.isCurrent||n.isDefaultVersion)&&t.add(n.key),t),new Set);if(o.size===0)return!0;await p(Array.from(o),m,async t=>this.#t.ensureDefaultAndCurrentRevisionForKey(t));for(const t of r)await this.#e.client.delete(a).where(x(v(c(a.sourceKey,t.key),...t.version?[c(a.sourceVersion,t.version)]:[E(a.sourceVersion)]),v(c(a.targetKey,t.key),...t.version?[c(a.targetVersion,t.version)]:[E(a.targetVersion)])));return!0}async updateEntityScorecardsStatus(e,s){return(await this.#e.client.update(i).set({scorecardsStatus:s}).where(c(i.id,e)).returning()).length>0}async updateEntityScorecardsStatusIfCalculating(e,s){return(await this.#e.client.update(i).set({scorecardsStatus:s}).where(I`${i.id} = ${e} AND ${i.scorecardsStatus} = 'CALCULATING'`).returning()).length>0}async#c({entities:e,revision:s,fileHash:r}){return(await p(e,m,async t=>{const n={type:t.type,key:t.key,title:t.title,summary:t.summary??void 0,tags:t.tags??void 0,metadata:t.metadata??void 0,git:t.git??void 0,contact:t.contact??void 0,links:t.links??void 0,version:t.version??void 0};return this.createEntity({entity:n,sourceFile:t.sourceFile??"",fileHash:r,isDeleted:!0,errorOnSkip:!1,source:t.source,revision:s})})).filter(t=>t!==null)}async#d(e,s){if(e.length===0)return!0;const r=await p(e,m,async o=>(await this.#l.getRelationsForEntity(o.key,o.version,s)).map(n=>{if(!n)return null;const u=n.direction,d=n.sourceToTargetRelation,h=n.targetKey,l=u==="outgoing"?o.key:h,f=u==="outgoing"?h:o.key,y=u==="outgoing"?d:d.startsWith("reverse:")?d.slice(8):d;return!y||!l||!f?null:G({type:y,sourceKey:l,targetKey:f,sourceVersion:o.version,targetVersion:o.version,sourceRevision:s,targetRevision:s,isDeleted:!0},this.#i,this.#s)}).filter(n=>n!==null));return await p(r.flat(),m,async o=>this.#r.upsertEntityRelation(o)),!0}}export{de as EntitiesWriteRepository};
|
package/dist/server/plugins/catalog-entities/extensions/extractors/api-description/base.d.ts
CHANGED
|
@@ -5,7 +5,9 @@ import type { FileType } from '../../../../../persistence/file-hashes/types.js';
|
|
|
5
5
|
import type { HashManager } from '../../../utils/hash-manager.js';
|
|
6
6
|
import type { BaseApiEntitiesExtractorParams, SpecType } from '../../../types/extractors.js';
|
|
7
7
|
import type { EntityDtoSchema } from '../../../schemas/dto-schemas.js';
|
|
8
|
-
export declare abstract class BaseApiEntitiesExtractor<BundledApiDefinition extends Pick<FileInfo, 'realRelativePath' | 'relativePath' | 'isVirtual' | 'hash'
|
|
8
|
+
export declare abstract class BaseApiEntitiesExtractor<BundledApiDefinition extends Pick<FileInfo, 'realRelativePath' | 'relativePath' | 'isVirtual' | 'hash'> & {
|
|
9
|
+
definition?: unknown;
|
|
10
|
+
}> implements BaseEntitiesExtractor {
|
|
9
11
|
#private;
|
|
10
12
|
protected type: 'api-description';
|
|
11
13
|
protected specType: SpecType;
|
|
@@ -16,6 +18,7 @@ export declare abstract class BaseApiEntitiesExtractor<BundledApiDefinition exte
|
|
|
16
18
|
protected fileHashManager: HashManager;
|
|
17
19
|
protected entitySources: Record<string, string>;
|
|
18
20
|
constructor(specType: SpecType, params: BaseApiEntitiesExtractorParams);
|
|
21
|
+
protected getDescriptionHash(description: BundledApiDefinition): string | undefined;
|
|
19
22
|
extract(): Promise<void>;
|
|
20
23
|
protected validateEntityRelationFileSchema(relation: unknown): void;
|
|
21
24
|
protected getRbacTeamsForDefinition(relativePath: string): string[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{entityRelationFileSchema as P}from"@redocly/config";import{removeLeadingSlash as _}from"@redocly/theme/core/utils";import{toKebabCase as R}from"../../../../../../utils/string/to-kebab-case.js";import{FileHashStatus as g}from"../../../../../persistence/file-hashes/types.js";import{promiseMapLimit as w}from"../../../../../utils/async/promise-map-limit.js";import{OPERATORS as A}from"../../../../../providers/database/pagination/constants.js";import{VERSION_NOT_SPECIFIED as T}from"@redocly/theme/core/constants";import{getRbacTeamsListForResource as
|
|
1
|
+
import{entityRelationFileSchema as P}from"@redocly/config";import{removeLeadingSlash as _}from"@redocly/theme/core/utils";import{sha1 as S}from"../../../../../utils/crypto/sha1.js";import{toKebabCase as R}from"../../../../../../utils/string/to-kebab-case.js";import{FileHashStatus as g}from"../../../../../persistence/file-hashes/types.js";import{promiseMapLimit as w}from"../../../../../utils/async/promise-map-limit.js";import{OPERATORS as A}from"../../../../../providers/database/pagination/constants.js";import{VERSION_NOT_SPECIFIED as T}from"@redocly/theme/core/constants";import{getRbacTeamsListForResource as D}from"../../../../../utils/rbac.js";import{envConfig as u}from"../../../../../config/env-config.js";import{resolveEntityVersion as F}from"../../../utils/resolve-entity-version.js";import{catalogDataCollector as p}from"../../../utils/catalog-data-collector.js";import{createValidator as H}from"../../../utils/ajv-validator.js";const O=15,C=200,k=500;class Y{type="api-description";specType;fileType;actions;context;catalogEntitiesService;fileHashManager;entitySources={};#e;constructor(t,e){this.specType=t,this.fileType=e.fileType,this.actions=e.actions,this.context=e.context,this.catalogEntitiesService=e.catalogEntitiesService,this.fileHashManager=e.fileHashManager,this.#e=e.shouldCalculateEntities??!1}getDescriptionHash(t){return t.definition===void 0?t.hash:S(JSON.stringify(t.definition))}async extract(){const t=await this.loadApiDescriptions(),e=await this.fileHashManager.getStatusSnapshot(this.fileType);await this.fileHashManager.markAllAsOutdated(this.fileType),t.length&&p.addExtractor(this.specType);const a=this.#s(t),i={skipped:0,fileHashMissing:0,fileHashMismatch:0,shouldCalculateFlag:0,forceRevalidateFlag:0,previouslyUnconfirmed:0},o=[],r=new Set;await w(Array.from(a.values()),O,async c=>{for(const{description:s,version:l}of c)try{const n=this.getDescriptionHash(s);if(!n)continue;r.add(s.realRelativePath);const h=await this.fileHashManager.getByPath(s.realRelativePath),m=h?.hash!==n,v=e.get(s.realRelativePath),y=v!==void 0&&v!==g.UP_TO_DATE,f=this.#i({fileHashChanged:m,hasExistingHashRecord:!!h,previouslyUnconfirmed:y});if(!(f!==null)){i.skipped++,p.increaseSkippedFilesCount(),await this.fileHashManager.upsert(this.fileType,s.realRelativePath,n,g.UP_TO_DATE);continue}f&&i[f]++,f==="fileHashMismatch"&&h&&o.length<3&&o.push({path:s.realRelativePath,stored:h.hash,incoming:n});const d=await this.catalogEntitiesService.getEntityKeysAndVersionsBySourceFile(s.realRelativePath);await this.#a(d);const E=new Date().toISOString();await this.processApiDescription(s,E,l,d),(m||y||u.FORCE_CATALOG_CACHE_REVALIDATE)&&p.markSourceFileAsChanged(s.realRelativePath),await this.#r(d,s.realRelativePath,E,n),p.increaseProcessedFilesCount(),await this.fileHashManager.upsert(this.fileType,s.realRelativePath,n,g.OUTDATED),p.markFileHashPendingConfirmation({fileType:this.fileType,filePath:s.realRelativePath,hash:n})}catch(n){this.context.logger.warn(`Error extracting entities from ${this.specType} description: ${s.realRelativePath}`),this.context.logger.warn(n)}}),await this.#o(r)}#i({fileHashChanged:t,hasExistingHashRecord:e,previouslyUnconfirmed:a}){return t?e?"fileHashMismatch":"fileHashMissing":a?"previouslyUnconfirmed":this.#e?"shouldCalculateFlag":u.FORCE_CATALOG_CACHE_REVALIDATE?"forceRevalidateFlag":null}#a=async t=>{u.FORCE_CATALOG_CACHE_REVALIDATE&&(await this.catalogEntitiesService.deleteEntities({field:"key",operator:"in",value:Array.from(t).map(e=>e.split(":")[0])}),t.clear())};#t=async t=>{let e=0,a=0;for(;;){const i=await this.catalogEntitiesService.getEntities({paginationParams:{limit:k,filter:t}});if(!i||i.items.length===0)break;await this.catalogEntitiesService.deleteEntities({field:"id",operator:"in",value:i.items.map(({id:o})=>o)}),e+=i.items.length,a+=1}return{total:e,pages:a}};#s(t){const e=new Map;for(const a of t)if(!(a.isVirtual||!a.hash))try{const i=this.#n(a),o=this.mapApiDescriptionToEntity(a,i),r=e.get(o.key)??[];r.push({description:a,version:i}),e.set(o.key,r)}catch(i){this.context.logger.warn(`Error resolving entity key for ${this.specType} description (skipping): ${a.realRelativePath}`),this.context.logger.warn(i)}return e}#o=async t=>{const e=await this.fileHashManager.getAllOutdated(this.fileType);if(!e||e.length===0)return;const a=e.filter(({filePath:l})=>!t.has(l));if(a.length===0)return;a.forEach(({filePath:l})=>{p.markSourceFileAsRemoved(l)});const i=a.map(({filePath:l})=>l),{total:o,pages:r}=await this.#t({op:"AND",conditions:[{field:"source_file",operator:"in",value:i},{field:"is_current",operator:"equal",value:!0}]}),{total:c,pages:s}=await this.#t({field:"source_file",operator:"in",value:i});this.context.logger.info(`[${this.specType}] removed-files cleanup: files=${i.length} currentRevisionsDeleted=${o} currentPages=${r} orphanRevisionsDeleted=${c} orphanPages=${s} removedFiles=${i.slice(0,3).join(", ")}${i.length>3?`, +${i.length-3} more`:""}`)};#r=async(t,e,a,i)=>{if(t.size===0||u.FORCE_CATALOG_CACHE_REVALIDATE)return;const o=Array.from(t).map(r=>{const[c,s]=r.split(":");return{key:c,version:s}});for(let r=0;r<o.length;r+=C){const c=o.slice(r,r+C),s=Array.from(new Set(c.map(({key:n})=>n))),l=c.map(({key:n,version:h})=>({op:A.AND,conditions:[{field:"key",operator:"equal",value:n},{field:"version",operator:"equal",value:h}]}));await this.catalogEntitiesService.softDeleteEntitiesWithRelations({revision:a,fileHash:i,filter:{op:"AND",conditions:[{field:"key",operator:"in",value:s},{op:A.OR,conditions:l},{field:"source",operator:"equal",value:"file"},{field:"source_file",operator:"equal",value:e},{field:"is_current",operator:"equal",value:!0}]}})}};#n(t){const e=t.document?.info?.version??t.definition?.info?.version??null,a=F(e,t.realRelativePath);return a.success?a.version??T:T}validateEntityRelationFileSchema(t){H(P,{errorPrefix:"Entity relation validation failed:",dataVar:"relation"})(t)}getRbacTeamsForDefinition(t){const e=this.actions.getConfig().access?.rbac,a=this.actions.getRouteByFsPath(t);return D(a||{fsPath:t},e||{})}resolveEntityKey({realRelativePath:t,customKey:e,extensionPattern:a}){const i=this.#l(t,a);return typeof e=="string"&&e.trim()?R(e.trim()):i}#l(t,e){let i=_(t);for(;/^@[^/]+\//.test(i);)i=i.replace(/^@[^/]+\//,"");i=i.replace(/\/@[^/]+/g,"");const o=e?i.replace(e,""):i.replace(/\.[^.]+$/,"");return R(o.replace(/[\\/]/g,"-"))}}export{Y as BaseApiEntitiesExtractor};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FileHashStatus as
|
|
1
|
+
import{FileHashStatus as v,FileType as h}from"../../persistence/file-hashes/types.js";import{envConfig as C}from"../../config/env-config.js";import{CATALOG_BASE_SLUG as S}from"../../../constants/catalog-entities.js";import{telemetryTraceStep as $}from"../../../cli/telemetry/helpers/trace-step.js";import{catalogDataCollector as f}from"./utils/catalog-data-collector.js";import{CATALOG_FILTERS_CACHE_NAMESPACE as k,ENTITIES_MAP_GLOBAL_DATA_KEY as B}from"../../constants/plugins/catalog-entities.js";import{CacheService as z}from"../../persistence/cache/services/cache-service.js";import{getTemplatePath as R}from"./utils/get-template-path.js";import{getCompleteCatalogConfig as O}from"./get-complete-catalog-config.js";import{AsyncApiEntitiesExtractor as Y}from"./extensions/extractors/api-description/asyncapi-entities-extractor.js";import{GraphqlEntitiesExtractor as U}from"./extensions/extractors/api-description/graphql-entities-extractor.js";import{FileHashesService as j}from"../../persistence/file-hashes/services/file-hashes-service.js";import{CatalogEntitiesService as q}from"./database/catalog-entities-service.js";import{CatalogEntitiesPublisher as V}from"./database/catalog-entities-publisher.js";import{CatalogEntitiesRevisionsPruner as _}from"./database/catalog-entities-revisions-pruner.js";import{DEFAULT_MAX_ENTITY_REVISIONS as W}from"./database/consts.js";import{DatabaseConnectionFactory as J}from"../../providers/database/database-connection-factory.js";import{ArazzoEntitiesExtractor as X}from"./extensions/extractors/api-description/arazzo-entities-extractor.js";import{FsEntitiesExtractor as Z}from"./extensions/extractors/fs-entities-extractor.js";import{HashManager as K}from"./utils/hash-manager.js";import{RbacConfigHashCache as Q}from"./utils/rbac-config-hash-cache.js";import{OpenApiEntitiesExtractor as ee}from"./extensions/extractors/api-description/openapi-entities-extractor.js";const te="catalog-entity-template",ie="catalog-entity";let I=!0;async function ae(){return{id:"CatalogEntities",requiredEntitlements:["catalog"],async processContent(e,i){const s=await i.getConfig(),r=O(s.entitiesCatalog);if(!r.show)return;const{logger:n}=i,a=e.registerServerPropsGetter(ie,R("../get-server-props.js")),g=e.createTemplate(te,R("../template/index.js"));e.addRoute({duplicateInAllLocales:!0,slug:S,fsPath:"",templateId:g,excludeFromSidebar:!0,hasClientRoutes:!0,serverPropsGetterIds:[a],getNavText:()=>Promise.resolve("Catalog"),getStaticData:async()=>({props:{catalogConfig:r}})});const[l]=Object.entries(r.catalogs??{}).find(([P,m])=>!m?.hide)||[];l&&e.addRedirect(S,{type:302,to:`${S}/${l}`},{trackOriginalSource:!1}),n.info("Catalog Entities plugin finished")},async afterRoutesCreated(e,i){await $("build.plugin.catalog_entities",async s=>{const r=await i.getConfig(),n=O(r.entitiesCatalog);if(s?.setAttribute("config",JSON.stringify(n)),!n.show)return;const{logger:a}=i;f.resetForRun();const g=I&&C.isDevelopMode,l=await z.getInstance({baseDbDir:e.serverOutDir,databaseType:"local"}),P=new Q(l),{rbacConfigChanged:m}=await P.syncAndDetectChange(r.access?.rbac??null),c=g||m,o=await q.getInstance({baseDbDir:e.serverOutDir,removeExisting:g,databaseType:"local",runWithPragmaWalWriteOptimization:!0}),T=await j.getInstance({baseDbDir:e.serverOutDir,databaseType:"local"}),u=new K(T),w=[new Z({fileHashManager:u,context:i,catalogEntitiesService:o,catalogConfig:n,shouldCalculateEntities:c}),new ee({actions:e,context:i,catalogEntitiesService:o,fileHashManager:u,fileType:h.OPENAPI_DESCRIPTION,shouldCalculateEntities:c}),new Y({actions:e,context:i,catalogEntitiesService:o,fileHashManager:u,fileType:h.ASYNCAPI_DESCRIPTION,shouldCalculateEntities:c}),new U({actions:e,context:i,catalogEntitiesService:o,fileHashManager:u,fileType:h.GRAPHQL_DESCRIPTION,shouldCalculateEntities:c}),new X({actions:e,context:i,catalogEntitiesService:o,fileHashManager:u,fileType:h.ARAZZO_DESCRIPTION,shouldCalculateEntities:c})];a.info("Starting entities extractors...");const F=a.startTiming();await o.transaction(async()=>{await Promise.all(w.map(async t=>t.extract()))});const H=o.getEntitySources();e.setGlobalData({[B]:H}),await l.deleteByNamespace(k),a.infoTime(F,"Entities extractors finished");const y=C.CATALOG_MAX_REVISIONS??W,d=await J.create({baseDbDir:e.serverOutDir,databaseType:"local"}),N=!C.isDevelopMode&&C.isProductionEnv;let E=[];if(N&&d&&y>0){const t=await _.pruneLocalRevisions({localConnection:d,maxRevisions:y});if(t.prunedEntities>0||t.prunedRelations>0||t.legacyRelationsHealed>0||t.legacyRelationsDeleted>0){a.info(`Pruned entity revision history: entities=${t.prunedEntities} relations=${t.prunedRelations} legacyHealed=${t.legacyRelationsHealed} legacyDeleted=${t.legacyRelationsDeleted} files=${t.affectedSourceFiles.length} (keeping ${y} revisions per entity)`),E=t.affectedSourceFiles;for(const D of E)f.markSourceFileAsChanged(D)}}const{changedSourceFiles:L,removedSourceFiles:b}=f.getPublishDelta(),x=a.startTiming(),A=await V.publishFromLocalToRemote(m?{baseDbDir:e.serverOutDir}:{baseDbDir:e.serverOutDir,changedSourceFiles:L,removedSourceFiles:b});if(A.published&&a.infoTime(x,"Entities published to the database"),A.shouldFinalizeFileHashes){b.length&&await T.deleteFileHashes({op:"AND",conditions:[{field:"status",operator:"equal",value:v.OUTDATED},{field:"file_path",operator:"in",value:b}]});const t=f.getFileHashConfirmations();for(const{fileType:D,filePath:G,hash:M}of t)await T.upsertFileHash({fileType:D,filePath:G,hash:M,status:v.UP_TO_DATE});A.published&&E.length&&d&&await _.confirmPrunedFiles({localConnection:d,sourceFiles:E})}else a.warn("Skipped file_hashes finalization because remote catalog publish connection is unavailable; next build will retry.");const p=await f.getCatalogEntitiesData(o);s?.setAttribute("totalEntities",p.totalEntitiesCount),s?.setAttribute("entitiesCountByType",JSON.stringify(p.countOfEntitiesByType)),s?.setAttribute("totalFilesSkippedByHash",p.totalFilesSkippedByHash),s?.setAttribute("totalProcessedFiles",p.totalProcessedFiles),s?.setAttribute("extractors",p.extractors),I=!1})}}}var ve=ae;export{ae as catalogEntitiesPlugin,ve as default};
|
|
@@ -4,6 +4,11 @@ export declare function getHeadingData(node: Tag | Node): {
|
|
|
4
4
|
id: any;
|
|
5
5
|
depth: any;
|
|
6
6
|
} | undefined;
|
|
7
|
+
export declare function getNumberedItemHeadingData(node: Tag | Node): {
|
|
8
|
+
value: string;
|
|
9
|
+
id: any;
|
|
10
|
+
depth: any;
|
|
11
|
+
} | undefined;
|
|
7
12
|
export declare function extractFirstHeading(ast: Node): undefined | string;
|
|
8
13
|
export declare const EXIT: unique symbol;
|
|
9
14
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isNode as l}from"../../../../../markdoc/helpers/guards/is-node.js";import{isStringNode as
|
|
1
|
+
import{isNode as l}from"../../../../../markdoc/helpers/guards/is-node.js";import{isStringNode as f}from"../../../../../markdoc/helpers/guards/is-string-node.js";import{getNodeAttribute as o}from"../../../../../markdoc/helpers/get-node-attribute.js";import{getInnerText as a}from"../../../../../markdoc/helpers/get-inner-text.js";function d(t){const e=o(t,"level");if(e)return{value:a(t.children),id:o(t,"id"),depth:e}}function x(t){const e=o(t,"headlineLevel"),r=o(t,"anchorId"),s=o(t,"headline");if(!(!e||!r||!Array.isArray(s)))return{value:a(s),id:r,depth:e}}function v(t){let e;return u(t,r=>{if(l(r)&&r.type==="heading")return e=d(r)?.value,c}),e}const c=Symbol("Exit visitor");function u(t,e){if(!t)return;const r=e(t);if(r===c)return r;for(const i of t.children){if(!i||f(i))continue;const n=u(i,e);if(n===c)return n}const s=t.slots||{};for(const i of Object.values(s)){if(!i||f(i))continue;const n=u(i,e);if(n===c)return n}}export{c as EXIT,v as extractFirstHeading,d as getHeadingData,x as getNumberedItemHeadingData,u as visit};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import b from"@markdoc/markdoc";import{isTag as f}from"../../../markdoc/helpers/guards/is-tag.js";import{slugger as l}from"../../utils/index.js";import{getMarkdocOptions as h}from"./markdoc/markdoc-options.js";import{visit as k,getHeadingData as D,getNumberedItemHeadingData as H}from"./markdoc/plugins/utils.js";import{renderDiagramsWithVariants as v}from"./markdoc/plugins/render-diagrams.js";import{deepStringify as y}from"./markdoc/utils/deep-stringify.js";import{stringifyTagChildrenObjects as T}from"./utils/stringify-tag-children-objects.js";async function _(p,t,g){const u=await h(g),e=[],a=[],s=y(t.variables?.pageProps),{headers:w,...c}=t.variables||{};l.reset();const o=b.transform(p,{...u,...t,variables:{...c,pageProps:s}});let m=0;k(o,r=>{if(f(r)){switch(r.name){case"Heading":r.attributes.__idx=m,m++;const n=D(r);n&&e.push(n);break;case"NumberedItem":const d=H(r);d&&e.push(d);break;case"Diagram":a.push({tag:r,input:{type:r.attributes.diagramType,source:r.attributes.diagramSource}});break}T(r)}});const i=await v(a.map(r=>r.input));for(let r=0;r<a.length;r++)a[r].tag.attributes.diagramError=i[r].error,a[r].tag.attributes.diagramHtml=i[r].light,a[r].tag.attributes.diagramHtmlDark=i[r].dark;return{headings:e,renderableAst:o,pageProps:s}}export{_ as transformMdAst};
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { ApiFunctionsContext, ApiFunctionsUser } from '@redocly/config';
|
|
2
|
+
import type { Store } from '../../../store.js';
|
|
2
3
|
export declare function shouldHandleMcpAuth(requiresLogin: boolean, rbacConfig?: Record<string, unknown>): boolean;
|
|
4
|
+
export declare function isMcpContentProtected(store: Store): boolean;
|
|
3
5
|
export declare function handleMcpAuth(request: Request, context: ApiFunctionsContext): Promise<{
|
|
4
6
|
isAuthenticated: boolean;
|
|
5
7
|
isTokenValid?: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{extractTokenFromAuthHeader as u}from"../../../plugins/mcp/utils/jwt.js";import{getUserParamsFromCookies as d}from"../../../web-server/auth.js";import{ServerRoutes as l}from"../../../../constants/api.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as i,RBAC_ALL_OTHER_TEAMS as a}from"../../../../constants/common.js";import{withPathPrefix as h}from"@redocly/theme/core/utils";function c(e){return!e||typeof e!="object"||Object.keys(e).length===0?!1:!(e[i]&&e[i]!=="none"||e[a]&&e[a]!=="none")}function
|
|
1
|
+
import{extractTokenFromAuthHeader as u}from"../../../plugins/mcp/utils/jwt.js";import{getUserParamsFromCookies as d}from"../../../web-server/auth.js";import{ServerRoutes as l}from"../../../../constants/api.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as i,RBAC_ALL_OTHER_TEAMS as a}from"../../../../constants/common.js";import{withPathPrefix as h}from"@redocly/theme/core/utils";function c(e){return!e||typeof e!="object"||Object.keys(e).length===0?!1:!(e[i]&&e[i]!=="none"||e[a]&&e[a]!=="none")}function f(e,t){if(!t||Object.keys(t).length===0)return e;const r=t.content;if(r&&Object.keys(r).length>0&&Object.values(r).some(c))return!0;const o=t.teamFoldersBaseRoles;return c(o)?!0:e}function O(e){const t=e.getConfig().access;return f(!!t?.requiresLogin,t?.rbac||{})}async function _(e,t){const r=e.headers.get("Authorization");if(!r)return{isAuthenticated:!1};const o=u(r),s=t?.config?.ssoDirect||{},n=o?await d(s,{authorization:o}):{};return o&&n&&n.isAuthenticated?{isAuthenticated:!0,isTokenValid:!0,currentUser:{teams:n.teams||[],email:n.email||"",claims:n,isAuthenticated:!0,idpAccessToken:n.idpAccessToken||void 0,idpId:n.idpId||void 0},accessToken:o}:{isAuthenticated:!1,isTokenValid:!1}}function g(e){return e=e.replace(/^http:\/\//,"https://"),new Response(JSON.stringify({error:"unauthorized",message:"Authentication required"}),{status:401,headers:{"Content-Type":"application/json","WWW-Authenticate":`Bearer resource_metadata="${e}${l.MCP_OAUTH_PROTECTED_RESOURCE}${h("/mcp")}"`,"Access-Control-Allow-Origin":"*"}})}function x(){return new Response(JSON.stringify({error:"invalid_token",message:"Invalid or expired token"}),{status:401,headers:{"Content-Type":"application/json","WWW-Authenticate":'Bearer error="invalid_token", error_description="Invalid or expired token"',"Access-Control-Allow-Origin":"*"}})}export{x as constructInvalidTokenResponse,g as constructUnauthorizedResponse,_ as handleMcpAuth,O as isMcpContentProtected,f as shouldHandleMcpAuth};
|
|
@@ -2,4 +2,7 @@ export declare const EXECUTE_TOOL_NAME = "execute";
|
|
|
2
2
|
export declare const DESCRIBE_TOOLS_TOOL_NAME = "describe-tools";
|
|
3
3
|
export declare const FETCH_TOOL_NAME = "fetch";
|
|
4
4
|
export declare const CODE_MODE_TOOL_NAMES: ReadonlySet<string>;
|
|
5
|
+
export declare const TOOLS_BRIDGE_GLOBAL_NAME = "tools";
|
|
6
|
+
export declare const FETCH_BRIDGE_GLOBAL_NAME = "__fetchBridge";
|
|
7
|
+
export declare const FETCH_BRIDGE_FUNCTION_NAME = "fetch";
|
|
5
8
|
//# sourceMappingURL=constants.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const t="execute",_="describe-tools",E="fetch",e=new Set([t,_]),o="tools",O="__fetchBridge",c="fetch";export{e as CODE_MODE_TOOL_NAMES,_ as DESCRIBE_TOOLS_TOOL_NAME,t as EXECUTE_TOOL_NAME,c as FETCH_BRIDGE_FUNCTION_NAME,O as FETCH_BRIDGE_GLOBAL_NAME,E as FETCH_TOOL_NAME,o as TOOLS_BRIDGE_GLOBAL_NAME};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { SetupSandboxContext } from '../../../../sandbox/types.js';
|
|
2
|
+
import type { SandboxFetch, SandboxTool } from '../types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Builds the `setupContext` that shapes the shared sandbox (`~/server/sandbox`) for code
|
|
5
|
+
* mode: the given tools — and, when provided, host fetch — become host-function rails, each
|
|
6
|
+
* capped and bound by the run's budget, and the prelude installs the code-mode guest surface
|
|
7
|
+
* over them.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createSandboxSetup(tools: Record<string, SandboxTool>, hostFetch?: SandboxFetch): SetupSandboxContext;
|
|
10
|
+
//# sourceMappingURL=create-sandbox-setup.d.ts.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{setupHostFunctions as a}from"../../../../sandbox/utils/setup-host-functions.js";import{evalGuestCode as p}from"../../../../sandbox/utils/eval-guest-code.js";import{SANDBOX_FETCH_SETUP as i}from"./polyfills.js";import{FETCH_BRIDGE_FUNCTION_NAME as u,FETCH_BRIDGE_GLOBAL_NAME as c,TOOLS_BRIDGE_GLOBAL_NAME as n}from"../constants.js";const m=100,f=50;function T(r,t){return(e,l)=>{const s=[a(e,r,{globalName:n,budget:l,maxCalls:m,messages:{outputTooLarge:o=>`Tool output is too large (${o} bytes); request narrower data instead`,callLimitExceeded:o=>`Exceeded the limit of ${o} tool calls`}})];return t&&s.push(a(e,{[u]:o=>t(o)},{globalName:c,budget:l,maxCalls:f,messages:{outputTooLarge:o=>`Response is too large (${o} bytes); request less data`,callLimitExceeded:o=>`Exceeded the limit of ${o} fetch calls`}})),p(e,E(!!t)),()=>{for(const o of s)o()}}}function E(r){const t=r?i:"",e=`globalThis[${JSON.stringify(n)}]`;return`(() => {${t}
|
|
2
|
+
const tools = ${e};
|
|
3
|
+
${e} = new Proxy(tools, {
|
|
4
|
+
get(target, prop) {
|
|
5
|
+
if (typeof prop !== 'string' || prop in target || prop === 'then' || prop === 'toJSON') {
|
|
6
|
+
return target[prop];
|
|
7
|
+
}
|
|
8
|
+
throw new TypeError('Unknown tool "' + prop + '". Available tools: ' + Object.keys(target).join(', '));
|
|
9
|
+
},
|
|
10
|
+
});
|
|
11
|
+
})();`}export{T as createSandboxSetup};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export declare const SANDBOX_FETCH_SETUP = "\n const URLSearchParams = class URLSearchParams {\n constructor(init) {\n this._params = [];\n if (typeof init === 'string') {\n const str = init.startsWith('?') ? init.slice(1) : init;\n for (const pair of (str ? str.split('&') : [])) {\n const eq = pair.indexOf('=');\n const k = eq >= 0 ? pair.slice(0, eq) : pair;\n const v = eq >= 0 ? pair.slice(eq + 1) : '';\n if (k) this._params.push([decodeURIComponent(k), decodeURIComponent(v)]);\n }\n } else if (init != null && typeof init === 'object') {\n for (const [k, v] of Object.entries(init)) this._params.push([k, String(v)]);\n }\n }\n append(key, value) { this._params.push([String(key), String(value)]); }\n set(key, value) {\n const k = String(key), v = String(value);\n this._params = this._params.filter(([pk]) => pk !== k);\n this._params.push([k, v]);\n }\n get(key) { return (this._params.find(([k]) => k === String(key)) ?? [undefined, null])[1]; }\n getAll(key) { return this._params.filter(([k]) => k === String(key)).map(([, v]) => v); }\n has(key) { return this._params.some(([k]) => k === String(key)); }\n delete(key) { this._params = this._params.filter(([k]) => k !== String(key)); }\n entries() { return this._params.values(); }\n [Symbol.iterator]() { return this._params.values(); }\n toString() {\n return this._params\n .map(([k, v]) => encodeURIComponent(k) + '=' + encodeURIComponent(v))\n .join('&');\n }\n };\n globalThis.URLSearchParams = URLSearchParams;\n\n const FormData = class FormData {\n constructor() { this._fields = []; }\n append(key, value) { this._fields.push([String(key), String(value)]); }\n set(key, value) {\n const k = String(key), v = String(value);\n this._fields = this._fields.filter(([fk]) => fk !== k);\n this._fields.push([k, v]);\n }\n get(key) { return (this._fields.find(([k]) => k === String(key)) ?? [undefined, null])[1]; }\n has(key) { return this._fields.some(([k]) => k === String(key)); }\n delete(key) { this._fields = this._fields.filter(([k]) => k !== String(key)); }\n entries() { return this._fields.values(); }\n [Symbol.iterator]() { return this._fields.values(); }\n };\n globalThis.FormData = FormData;\n\n const hostFetch = globalThis.__fetchBridge.fetch;\n delete globalThis.__fetchBridge;\n globalThis.fetch = (url, init = {}) => {\n let body;\n let autoContentType;\n if (init.body instanceof URLSearchParams) {\n body = init.body.toString();\n autoContentType = 'application/x-www-form-urlencoded';\n } else if (init.body instanceof FormData) {\n const boundary = '----FormBoundary' + Math.random().toString(36).slice(2);\n body = init.body._fields\n .map(([k, v]) =>\n '--' + boundary + '\\r\\nContent-Disposition: form-data; name=\"' + k + '\"\\r\\n\\r\\n' + v,\n )\n .join('\\r\\n') + '\\r\\n--' + boundary + '--';\n autoContentType = 'multipart/form-data; boundary=' + boundary;\n } else if (init.body != null && typeof init.body !== 'string') {\n throw new TypeError('fetch body must be a string, URLSearchParams, or FormData');\n } else {\n body = init.body ?? undefined;\n }\n const callerHeaders = init.headers;\n const hasContentType = callerHeaders != null && Object.keys(callerHeaders).some(\n (k) => k.toLowerCase() === 'content-type',\n );\n const headers = autoContentType && !hasContentType\n ? Object.assign({ 'content-type': autoContentType }, callerHeaders)\n : callerHeaders;\n return hostFetch({ url: String(url), method: init.method, headers, body })\n .then((res) => {\n const resHeaders = res.headers || {};\n return {\n status: res.status,\n statusText: res.statusText,\n ok: res.ok,\n headers: {\n get: (name) => {\n const value = resHeaders[String(name).toLowerCase()];\n return value === undefined ? null : value;\n },\n },\n json: () => Promise.resolve(JSON.parse(res.bodyText)),\n text: () => Promise.resolve(res.bodyText),\n };\n });\n };\n";
|
|
2
|
+
//# sourceMappingURL=polyfills.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const
|
|
1
|
+
import{FETCH_BRIDGE_FUNCTION_NAME as t,FETCH_BRIDGE_GLOBAL_NAME as e}from"../constants.js";const s=`
|
|
2
2
|
const URLSearchParams = class URLSearchParams {
|
|
3
3
|
constructor(init) {
|
|
4
4
|
this._params = [];
|
|
@@ -49,9 +49,9 @@ const e=`
|
|
|
49
49
|
[Symbol.iterator]() { return this._fields.values(); }
|
|
50
50
|
};
|
|
51
51
|
globalThis.FormData = FormData;
|
|
52
|
-
`,
|
|
53
|
-
const hostFetch = globalThis
|
|
54
|
-
delete globalThis
|
|
52
|
+
`,r=`
|
|
53
|
+
const hostFetch = globalThis.${e}.${t};
|
|
54
|
+
delete globalThis.${e};
|
|
55
55
|
globalThis.fetch = (url, init = {}) => {
|
|
56
56
|
let body;
|
|
57
57
|
let autoContentType;
|
|
@@ -78,9 +78,8 @@ const e=`
|
|
|
78
78
|
const headers = autoContentType && !hasContentType
|
|
79
79
|
? Object.assign({ 'content-type': autoContentType }, callerHeaders)
|
|
80
80
|
: callerHeaders;
|
|
81
|
-
return hostFetch(
|
|
82
|
-
.then((
|
|
83
|
-
const res = JSON.parse(json);
|
|
81
|
+
return hostFetch({ url: String(url), method: init.method, headers, body })
|
|
82
|
+
.then((res) => {
|
|
84
83
|
const resHeaders = res.headers || {};
|
|
85
84
|
return {
|
|
86
85
|
status: res.status,
|
|
@@ -97,4 +96,4 @@ const e=`
|
|
|
97
96
|
};
|
|
98
97
|
});
|
|
99
98
|
};
|
|
100
|
-
`;export{
|
|
99
|
+
`,i=`${s}${r}`;export{i as SANDBOX_FETCH_SETUP};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mcpToolHandlers as
|
|
1
|
+
import{mcpToolHandlers as s}from"../../../../../client/mcp-tool-handlers-entry.js";import{runInSandbox as c}from"../../../../sandbox/sandbox.js";import{isMcpToolAvailable as l}from"../../workers/execute-mcp-tool.js";import{buildExecuteHostFetch as m,isFetchCapable as f}from"../../gateway-mcp/fetch-capability.js";import{CODE_MODE_TOOL_NAMES as u,EXECUTE_TOOL_NAME as p}from"../constants.js";import{sanitizeToolName as d}from"../build-tool-type-declarations.js";import{invokeTool as b}from"../invoke-tool.js";import{createSandboxSetup as T}from"../sandbox/create-sandbox-setup.js";const E=async(e,t,i)=>{const o=await O(t,i),n=f(t)?m(t):void 0,{result:r,error:a}=await c(e.code,{setupContext:T(o,n)});return{content:[{type:"text",text:JSON.stringify({result:r,error:a})}],isError:a!==void 0}};async function O(e,t){const i={};for(const o of Object.keys(s))u.has(o)||!await l({toolName:o,context:e}).catch(()=>!1)||(i[d(o)]=r=>b(o,r,e,t));return i}var C={[p]:E};export{C as default};
|
|
@@ -13,12 +13,4 @@ export type SandboxFetchResponse = {
|
|
|
13
13
|
bodyText: string;
|
|
14
14
|
};
|
|
15
15
|
export type SandboxFetch = (request: SandboxFetchRequest) => Promise<SandboxFetchResponse>;
|
|
16
|
-
export type SandboxResult = {
|
|
17
|
-
result?: unknown;
|
|
18
|
-
error?: string;
|
|
19
|
-
};
|
|
20
|
-
export type RunInSandboxOptions = {
|
|
21
|
-
timeoutMs?: number;
|
|
22
|
-
hostFetch?: SandboxFetch;
|
|
23
|
-
};
|
|
24
16
|
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=1048576,t="hostFunctions";export{t as DEFAULT_GLOBAL_NAME,o as MAX_HOST_OUTPUT_BYTES};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare const DEFAULT_TIMEOUT_MS = 10000;
|
|
2
|
+
export declare const MEMORY_LIMIT_BYTES: number;
|
|
3
|
+
export declare const DEFAULT_MAX_LIFETIME_MS: number;
|
|
4
|
+
export declare const MAX_STACK_SIZE_BYTES: number;
|
|
5
|
+
export declare const MAX_RESULT_BYTES: number;
|
|
6
|
+
//# sourceMappingURL=sandbox.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const _=1e4,E=67108864,T=6e5,o=262144,t=1048576;export{T as DEFAULT_MAX_LIFETIME_MS,_ as DEFAULT_TIMEOUT_MS,t as MAX_RESULT_BYTES,o as MAX_STACK_SIZE_BYTES,E as MEMORY_LIMIT_BYTES};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { RunInSandboxOptions, SandboxResult } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Evaluates `code` in a fresh, isolated QuickJS VM bounded by memory, stack, and time. The VM
|
|
4
|
+
* starts pristine — no host access of any kind. Consumers shape the guest realm through
|
|
5
|
+
* `setupContext` (see e.g. `setupHostFunctions`); the time bounds live in `createExecutionBudget`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function runInSandbox(code: string, options?: RunInSandboxOptions): Promise<SandboxResult>;
|
|
8
|
+
//# sourceMappingURL=sandbox.d.ts.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import f from"@jitl/quickjs-singlefile-mjs-release-sync";import{newQuickJSWASMModuleFromVariant as p}from"quickjs-emscripten-core";import{createExecutionBudget as E}from"./utils/execution-budget.js";import{DEFAULT_MAX_LIFETIME_MS as _,DEFAULT_TIMEOUT_MS as T,MAX_RESULT_BYTES as g,MAX_STACK_SIZE_BYTES as x,MEMORY_LIMIT_BYTES as y}from"./constants/sandbox.js";let c;function A(){return c??=p(f)}async function v(t,l={}){const{timeoutMs:m=T,maxLifetimeMs:d=_,setupContext:M}=l,e=(await A()).newContext();let n,s,r;try{e.runtime.setMemoryLimit(y),e.runtime.setMaxStackSize(x),n=E(e,m,d),s=M?.(e,n)??void 0,r=e.unwrapResult(e.evalCode(`(async () => {
|
|
2
|
+
${t}
|
|
3
|
+
})()`));const o=e.resolvePromise(r);e.runtime.executePendingJobs();const S=await Promise.race([o,n.aborted]),i=e.unwrapResult(S),u=e.dump(i);i.dispose();const a=JSON.stringify(u??null).length;return a>g?{error:`Result is too large (${a} bytes); return less data`}:{result:u}}catch(o){return{error:I(o)}}finally{n?.dispose(),r?.dispose();try{s?.()}catch{}try{e.dispose()}catch{c=void 0}}}function I(t){return t instanceof Error?t.message:String(t)}export{v as runInSandbox};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { QuickJSContext } from 'quickjs-emscripten-core';
|
|
2
|
+
export type SandboxResult = {
|
|
3
|
+
result?: unknown;
|
|
4
|
+
error?: string;
|
|
5
|
+
};
|
|
6
|
+
export type ExecutionBudget = {
|
|
7
|
+
/**
|
|
8
|
+
* Run `work()` as a host call: its latency is exempt from the compute budget (`timeoutMs`).
|
|
9
|
+
* While the call is in flight the idle timer is paused, and the guest gets a fresh CPU
|
|
10
|
+
* deadline when it settles — so time spent off in the host isn't charged as guest compute.
|
|
11
|
+
*/
|
|
12
|
+
hostCall<T>(work: () => Promise<T>): Promise<T>;
|
|
13
|
+
/** Rejects when a wall-clock deadline fires */
|
|
14
|
+
aborted: Promise<never>;
|
|
15
|
+
dispose(): void;
|
|
16
|
+
};
|
|
17
|
+
export type SetupSandboxContext = (context: QuickJSContext, budget: ExecutionBudget) => void | (() => void);
|
|
18
|
+
export type RunInSandboxOptions = {
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
maxLifetimeMs?: number;
|
|
21
|
+
setupContext?: SetupSandboxContext;
|
|
22
|
+
};
|
|
23
|
+
export type SandboxHostFunction = (input: unknown) => Promise<unknown> | unknown;
|
|
24
|
+
//# sourceMappingURL=types.d.ts.map
|
|
File without changes
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { QuickJSContext } from 'quickjs-emscripten-core';
|
|
2
|
+
/**
|
|
3
|
+
* Evaluates guest source inside a QuickJS context for its side effects
|
|
4
|
+
*
|
|
5
|
+
* @param context - The QuickJS context to evaluate in
|
|
6
|
+
* @param source - Guest JavaScript source evaluated for side effects
|
|
7
|
+
* @throws When the source throws or fails to parse (unwrapped from the VM)
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* evalGuestCode(context, 'globalThis.ctx = Object.freeze({ n: 41 });');
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export declare function evalGuestCode(context: QuickJSContext, source: string): void;
|
|
15
|
+
//# sourceMappingURL=eval-guest-code.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function s(e,o){e.unwrapResult(e.evalCode(o)).dispose()}export{s as evalGuestCode};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ExecutionBudget } from '../types.js';
|
|
2
|
+
import type { QuickJSContext } from 'quickjs-emscripten-core';
|
|
3
|
+
/**
|
|
4
|
+
* Time-bounds a single sandbox run. Two deadlines — a refreshable per-stretch compute budget
|
|
5
|
+
* (`timeoutMs`) and a fixed whole-run ceiling (`maxLifetimeMs`) — are each enforced two ways,
|
|
6
|
+
* because the guest is only ever in one of two states and each enforcer reaches only one:
|
|
7
|
+
* - while the guest RUNS bytecode → the interrupt handler
|
|
8
|
+
* - while the guest is PARKED on an `await` → a wall-clock `setTimeout`
|
|
9
|
+
*/
|
|
10
|
+
export declare function createExecutionBudget(context: QuickJSContext, timeoutMs: number, maxLifetimeMs: number): ExecutionBudget;
|
|
11
|
+
//# sourceMappingURL=execution-budget.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function f(a,t,i){const s=Date.now()+i;let c=Date.now()+t,l=()=>{};const d=new Promise((e,o)=>{l=r=>o(new Error(r))});let n;const u=()=>{clearTimeout(n),n=setTimeout(()=>l(`Execution timed out after ${t}ms`),t)};a.runtime.setInterruptHandler(()=>{const e=Date.now();return e>c||e>s}),u();const T=setTimeout(()=>l(`Exceeded the maximum lifetime of ${i}ms`),i);let m=0;return{hostCall:e=>{m++,clearTimeout(n);const o=()=>{a.alive&&(c=Date.now()+t,--m===0&&u())},r=e();return r.then(o,o),r},aborted:d,dispose(){clearTimeout(n),clearTimeout(T)}}}export{f as createExecutionBudget};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ExecutionBudget, SandboxHostFunction } from '../types.js';
|
|
2
|
+
import type { QuickJSContext } from 'quickjs-emscripten-core';
|
|
3
|
+
/**
|
|
4
|
+
* Optional adapter for `runInSandbox`'s `setupContext`: exposes named host functions to the
|
|
5
|
+
* guest as one frozen global — `hostFunctions` by default, or the `globalName` the consumer
|
|
6
|
+
* chooses. Values cross the boundary as JSON strings — the guest only ever receives copies.
|
|
7
|
+
* Returns the cleanup callback.
|
|
8
|
+
*/
|
|
9
|
+
export declare function setupHostFunctions(context: QuickJSContext, hostFunctions: Record<string, SandboxHostFunction>, options?: {
|
|
10
|
+
globalName?: string;
|
|
11
|
+
budget?: ExecutionBudget;
|
|
12
|
+
maxCalls?: number;
|
|
13
|
+
messages?: {
|
|
14
|
+
outputTooLarge?: (bytes: number) => string;
|
|
15
|
+
callLimitExceeded?: (max: number) => string;
|
|
16
|
+
};
|
|
17
|
+
}): () => void;
|
|
18
|
+
//# sourceMappingURL=setup-host-functions.d.ts.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{DEFAULT_GLOBAL_NAME as v,MAX_HOST_OUTPUT_BYTES as _}from"../constants/host-functions.js";import{evalGuestCode as E}from"./eval-guest-code.js";function w(e,o,s){const l=s?.globalName??v,u=s?.maxCalls,f=s?.messages?.outputTooLarge??(n=>`Host function output is too large (${n} bytes); request narrower data instead`),m=s?.messages?.callLimitExceeded??(n=>`Exceeded the limit of ${n} host calls`),d=s?.budget?.hostCall??(n=>n()),c=new Set;let S=0;return e.newFunction("__invoke",(n,a)=>{const h=e.getString(n),p=JSON.parse(e.getString(a)),r=e.newPromise();return c.add(r),u!==void 0&&++S>u?e.newError(m(u)).consume(r.reject):d(()=>Promise.resolve().then(()=>o[h](p))).then(t=>{if(!e.alive)return;let i;try{i=JSON.stringify(t??null)}catch(g){const b=g instanceof Error?g.message:String(g);e.newError(`Host function output is not serializable: ${b}`).consume(r.reject);return}i.length>_?e.newError(f(i.length)).consume(r.reject):e.newString(i).consume(r.resolve)},t=>{if(!e.alive)return;const i=t instanceof Error?t.message:String(t);e.newError(i).consume(r.reject)}),r.settled.then(()=>{e.alive&&e.runtime.executePendingJobs()}),r.handle}).consume(n=>e.setProp(e.global,"__invoke",n)),E(e,O(Object.keys(o),l)),function(){for(const a of c)a.alive&&a.dispose()}}function O(e,o){const s=e.map(l=>`${JSON.stringify(l)}: (input) => invoke(${JSON.stringify(l)}, JSON.stringify(input ?? {})).then(JSON.parse)`).join(", ");return`(() => {
|
|
2
|
+
const invoke = globalThis.__invoke;
|
|
3
|
+
delete globalThis.__invoke;
|
|
4
|
+
globalThis[${JSON.stringify(o)}] = Object.freeze({ ${s} });
|
|
5
|
+
})();`}export{w as setupHostFunctions};
|
package/dist/server/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import C from"@markdoc/markdoc";import{getPathnameForLocale as A}from"@redocly/theme/core/utils";import{DEFAULT_LOCALE_PLACEHOLDER as g}from"../constants/common.js";import{DEFAULT_TITLE as O}from"./constants/common.js";import{GATED_MARKDOC_TAGS as D}from"./constants/entitlements.js";import{MARKDOC_PARTIALS_DATA_KEY as m,MARKDOC_PARTIALS_DEPS_KEY as T}from"./constants/common.js";import{isObject as M}from"../utils/guards/is-object.js";import{mapObject as k}from"../utils/object/map-object.js";import{getValueDeep as y}from"../utils/object/get-value-deep.js";import{removeTrailingSlash as L}from"../utils/url/remove-trailing-slash.js";import{normalizeRouteSlug as h}from"../utils/path/normalize-route-slug.js";import{isLocalLink as R}from"../utils/path/is-local-link.js";import{reporter as S}from"./tools/notifiers/reporter.js";import{logger as u}from"./tools/notifiers/logger.js";import{sha1 as H}from"./utils/crypto/sha1.js";import{envConfig as _,setEnv as G}from"./config/env-config.js";import{KvService as B}from"./persistence/kv/services/kv-service.js";import{writeSharedData as F}from"./utils/index.js";import{renderComponents as I}from"./ssr/render.js";import{readStaticData as N,writeStaticData as q}from"./utils/static-data.js";import{parseAndResolveMarkdoc as V}from"./plugins/markdown/compiler.js";import{getMarkdocOptions as j}from"./plugins/markdown/markdoc/markdoc-options.js";import{EntitlementsProvider as w}from"./entitlements/entitlements-provider.js";import{isL10nPath as U}from"./fs/utils/is-l10n-path.js";import{resolveGlobMapValue as K}from"./utils/globs.js";import{replaceEnvVariablesDeep as J}from"./utils/envs/replace-env-variables-deep.js";import{findRedirect as x}from"./utils/redirects/find-redirect.js";import{followRedirectChain as W}from"./utils/redirects/follow-redirect-chain.js";import{addWildcardRedirectToTree as $}from"./utils/redirects/add-wildcard-redirect-to-tree.js";import{telemetryTraceStep as z}from"../cli/telemetry/helpers/trace-step.js";const v={routesBySlug:"map",apiRoutes:"object",middleware:"object",routesByFsPath:"map",routesSharedData:"map",globalData:"object",config:"object",ssr:"object",searchFacets:"map",routesPartials:"map",mcpToolHandlers:"map",skills:"map"},E="PLAN_GATES",Y=["OAUTH_CLIENT_ID","OAUTH_CLIENT_SECRET","ORGANIZATION_SLUG","ORGANIZATION_ID","ORG_ID"],Oe="userDefinedApiFunctions";class P{routesBySlug=new Map;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={};#o=void 0;config={configFilePath:"",redirects:{},wildcardRedirectsTree:{},access:{rbac:{},requiresLogin:!1},directoryPermissions:{},devLogin:!1,ssoDirect:{}};#i;serverMode;serverOutDir;outdir;buildRevision=0;hasSitemap=!1;compilationErrors=[];#n;userCodeReady;#s=Promise.resolve();#c;#l=Promise.resolve();#d;#u=Promise.resolve();#h;#e=!1;#r=0;#f=0;#a=new Map;constructor({outdir:e,contentDir:t,serverMode:s=!1,serverOutDir:a}){this.#i=t,this.outdir=e,this.serverMode=s,this.serverOutDir=a,this.userCodeReady=new Promise(r=>{this.#n=r})}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 a of this.listeners.get(e)||new Set)t?a(t,...s):a(...s)};startPluginsRun(){this.clear(),this.#s=new Promise(e=>{this.#c=e})}waitForPluginsLifecycle(){return Promise.all([this.#s,this.#l,this.#u])}waitForPluginsRun(){return this.#s}finishPluginsRun(){this.#c?.();for(const e of this.#a.values())this.runListeners(...e);this.#a.clear()}startEsbuildRun(){this.#l=new Promise(e=>{this.#d=e})}finishEsbuildRun(){this.#d?.()}markRequestHandlersEntryOutdated(){this.#r++,!this.#e&&(this.#e=!0,this.#u=new Promise(e=>{this.#h=e}))}noteRequestHandlersEntryBuildStart(){this.#f=this.#r}markRequestHandlersEntryUpdated(){this.#e&&(this.#r>this.#f||(this.#e=!1,this.#h?.()))}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 z("build.reload_markdoc_options",async()=>{const e=w.instance(),t=await j(this.serverOutDir),s=Object.fromEntries(Object.entries(t.tags).filter(([a])=>D[a]!=null?e.canAccessFeature(D[a]):!0));this.#o={...t,tags:s}})}get markdocOptions(){return{...this.#o,partials:this.getGlobalConfig(m),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()=>B.getInstance({baseDbDir:this.serverOutDir});parseMarkdoc=async({input:e,context:t,deps:s,resource:a})=>{const{data:{info:r,ast:o},compoundHash:l}=await V(e,this.markdocOptions,{actions:this,context:t},a);for(const i of r.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 r.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&&r.partials?.length)for(const i of s.routeSlugs){const n=this.routesPartials.get(i)||[];for(const c of r.partials)n.includes(c)||n.push(c);this.routesPartials.set(i,n)}return{info:r,ast:o,compoundHash:l}};async loadOpenApiDefinitions(e){return(await e.cache.load(".","load-oas-docs")).data}async loadAsyncApiDefinitions(e){return(await e.cache.load(".","asyncapi-docs")).data}async loadGraphqlDefinitions(e){return(await e.cache.load(".","load-graphql-docs")).data}setSearchEngine(e){this.searchEngine=e}setSearchFacets=e=>{this.searchFacets=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}=y(e,i);(n||c!==this.replacedEnvVars[l].replaced)&&delete this.replacedEnvVars[l]}const{resolvedObj:s,unsetEnvVars:a,replacedValues:r}=J(e);for(const o of a)this.unsetEnvVars.add(o);Object.assign(this.replacedEnvVars,r),Object.assign(this.config,s)};getConfig=()=>this.config;getGlobalConfig=e=>this.config[e];getSearchFacets=()=>this.searchFacets;addRedirect=(e,t,s={})=>{if(!w.instance().canAccessFeature("redirects")&&e!=="/")return;this.config.redirects||(this.config.redirects={});const o=h(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("*")&&$(this.config.wildcardRedirectsTree,o)};getRedirect=e=>{const t=h(e).toLowerCase(),s=x(t,this.config.redirects,this.config.wildcardRedirectsTree);if(!s)return null;if(R(s.to)){const a=h(s.to).toLowerCase();if(!a.endsWith("*")&&W(a,[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 a=JSON.stringify(t),r=s??H(a);return this.#t[e]===r||(this.#t[e]=r,await F(e,a,this.outdir),this.queueEvent("shared-data-updated",e)),e};addRouteSharedData=(e,t,s)=>{const a=L(e),r=this.routesSharedData.get(a)||{};r[t]=s,this.routesSharedData.set(a,r),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(m)||{},s=this.routesPartials.get(e);if(!s||s.length===0)return{};const a=this.getGlobalConfig(T)||{},r=new Set(s),o=Array.from(s);for(let i=0;i<o.length;i++){const n=o[i],c=a[n]?.partials??[];for(const d of c)r.has(d)||(r.add(d),o.push(d))}const l={};for(const i of r)t[i]&&(l[i]=t[i]);return l};addRoute=e=>{const s={...K(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 a=[g,...this.lifecycleContext?.fs.localeFolders||[]].map(r=>({code:r,name:r}));for(const r of a){const o=A(e,g,r.code,a);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)this.mcpToolHandlers.set(s.name,{...s,importPath:e}),u.verbose("Created MCP tool %s",s.name)};getMcpTools=()=>Array.from(this.mcpToolHandlers.values());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());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())),r=[...(this.config.responseHeaders[e]??[]).filter(o=>!s.has(o.name.toLowerCase())),...t];this.config.responseHeaders[e]=r};getRouteByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.getRouteBySlug(t):void 0};getRouteBySlug=(e,t={})=>{const{followRedirect:s=!0}=t,a=this.getRedirect(e);return s&&a?this.routesBySlug.get(h(a.to)):this.routesBySlug.get(e)};hasRouteOrRedirectBySlug=e=>{if(this.routesBySlug.has(e))return!0;const t=this.getRedirect(e);if(!t)return!1;if(!R(t.to))return!0;const s=h(t.to);return this.routesBySlug.has(s)};getRoutesByTemplateId=e=>this.newRoutes.filter(t=>t.templateId===e);getAllRoutesForLocale=(e=g)=>{const t=Array.from(this.routesBySlug.values()),s=e.toLowerCase();return t.filter(a=>e===g?!U(a.fsPath):a.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&&q(e.slug,s,this.outdir)}async resolveRouteStaticData(e,t,s){if(this.serverMode)return N(e.slug,this.outdir);const a={...this,contentDir:this.contentDir,parseMarkdoc:({input:c,context:d,resource:f})=>this.parseMarkdoc({input:c,context:d,deps:{routeSlugs:[e.slug]},resource:f})},r=await e.getStaticData?.(e,a)||{},o=new Set(this.routesDynamicComponents.get(e.slug)),l=this.routesSharedData.get(e.slug)||{};for(const c of Object.values(l)){const d=this.sharedDataMarkdocComponents.get(c);d&&d.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=r?.frontmatter||{};return{...r,frontmatter:{...n,seo:{...n?.seo,title:n?.seo?.title||await e.getNavText?.()}},props:{...r.props,dynamicMarkdocComponents:Array.from(o),metadata:{...r?.props?.metadata,...e.metadata},seo:{title:O,...i,...r.props?.seo},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(""):I(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.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:[]}};async toJson(){const e=[];for(const[s,a]of Object.entries(v))switch(a){case"map":const r=Array.from(this[s].entries());e.push([s,r]);break;case"object":s==="config"&&e.push([s,await this.getConfigWithEnvPlaceholders()]),e.push([s,this[s]]);break;default:throw new Error("Invalid format")}const t=Object.fromEntries(e);return t[E]=_.PLAN_GATES,t}static fromJson(e,t){const s=new P(t);for(const[r,o]of Object.entries(v))switch(o){case"map":s[r]=new Map(e[r]);break;case"object":if(r==="config"){s.setGlobalConfig(e[r]);break}s[r]=e[r];break;default:throw new Error("Invalid format")}s.config[m]=Z(s.config[m]||{});const a=e[E];return a&&G("PLAN_GATES",a),s}async getConfigWithEnvPlaceholders(){const e=JSON.parse(JSON.stringify(this.config));for(const t in this.replacedEnvVars){const{original:s}=this.replacedEnvVars[t],a=t.split(":"),r=a.pop(),{error:o,value:l}=y(e,a);if(o||!M(l)&&!Array.isArray(l)){await S.panicOnBuild(`Failed to replace env var with env name for ${t}`);continue}l[r]=s}return e}async reportUnsetEnvVars(){if(this.unsetEnvVars.size===0)return;const e=Array.from(this.unsetEnvVars).filter(s=>!Y.includes(s));if(e.length===0)return;const t=`Failed to resolve config. The following environment variables are not set: ${e.join(", ")}`;await S.panicOnBuildContentError(t)}}function Z(b){return k(b,e=>C.Ast.fromJSON(JSON.stringify(e)))}export{P as Store,Oe as USER_DEFINED_API_FUNCTIONS_COUNTER_KEY};
|
|
1
|
+
import C from"@markdoc/markdoc";import{getPathnameForLocale as A}from"@redocly/theme/core/utils";import{DEFAULT_LOCALE_PLACEHOLDER as g}from"../constants/common.js";import{DEFAULT_TITLE as T}from"./constants/common.js";import{GATED_MARKDOC_TAGS as y}from"./constants/entitlements.js";import{MARKDOC_PARTIALS_DATA_KEY as m,MARKDOC_PARTIALS_DEPS_KEY as O}from"./constants/common.js";import{isObject as M}from"../utils/guards/is-object.js";import{mapObject as k}from"../utils/object/map-object.js";import{getValueDeep as D}from"../utils/object/get-value-deep.js";import{removeTrailingSlash as L}from"../utils/url/remove-trailing-slash.js";import{normalizeRouteSlug as h}from"../utils/path/normalize-route-slug.js";import{isLocalLink as R}from"../utils/path/is-local-link.js";import{reporter as S}from"./tools/notifiers/reporter.js";import{logger as u}from"./tools/notifiers/logger.js";import{sha1 as H}from"./utils/crypto/sha1.js";import{envConfig as _,setEnv as G}from"./config/env-config.js";import{KvService as B}from"./persistence/kv/services/kv-service.js";import{SandboxContext as F}from"./utils/sandbox-context.js";import{writeSharedData as I}from"./utils/index.js";import{renderComponents as N}from"./ssr/render.js";import{readStaticData as q,writeStaticData as V}from"./utils/static-data.js";import{parseAndResolveMarkdoc as j}from"./plugins/markdown/compiler.js";import{getMarkdocOptions as U}from"./plugins/markdown/markdoc/markdoc-options.js";import{EntitlementsProvider as w}from"./entitlements/entitlements-provider.js";import{isL10nPath as K}from"./fs/utils/is-l10n-path.js";import{resolveGlobMapValue as x}from"./utils/globs.js";import{replaceEnvVariablesDeep as J}from"./utils/envs/replace-env-variables-deep.js";import{findRedirect as W}from"./utils/redirects/find-redirect.js";import{followRedirectChain as $}from"./utils/redirects/follow-redirect-chain.js";import{addWildcardRedirectToTree as z}from"./utils/redirects/add-wildcard-redirect-to-tree.js";import{telemetryTraceStep as Y}from"../cli/telemetry/helpers/trace-step.js";const v={routesBySlug:"map",apiRoutes:"object",middleware:"object",routesByFsPath:"map",routesSharedData:"map",globalData:"object",config:"object",ssr:"object",searchFacets:"map",routesPartials:"map",mcpToolHandlers:"map",skills:"map"},E="PLAN_GATES",Z=["OAUTH_CLIENT_ID","OAUTH_CLIENT_SECRET","ORGANIZATION_SLUG","ORGANIZATION_ID","ORG_ID"],Me="userDefinedApiFunctions";class P{routesBySlug=new Map;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={};#o=void 0;config={configFilePath:"",redirects:{},wildcardRedirectsTree:{},access:{rbac:{},requiresLogin:!1},directoryPermissions:{},devLogin:!1,ssoDirect:{}};#i;serverMode;serverOutDir;outdir;buildRevision=0;hasSitemap=!1;compilationErrors=[];#n;userCodeReady;#s=Promise.resolve();#c;#l=Promise.resolve();#d;#u=Promise.resolve();#h;#e=!1;#r=0;#f=0;#a=new Map;constructor({outdir:e,contentDir:t,serverMode:s=!1,serverOutDir:a}){this.#i=t,this.outdir=e,this.serverMode=s,this.serverOutDir=a,F.register({serverOutDir:a,readRoots:[e,process.cwd()]}),this.userCodeReady=new Promise(r=>{this.#n=r})}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 a of this.listeners.get(e)||new Set)t?a(t,...s):a(...s)};startPluginsRun(){this.clear(),this.#s=new Promise(e=>{this.#c=e})}waitForPluginsLifecycle(){return Promise.all([this.#s,this.#l,this.#u])}waitForPluginsRun(){return this.#s}finishPluginsRun(){this.#c?.();for(const e of this.#a.values())this.runListeners(...e);this.#a.clear()}startEsbuildRun(){this.#l=new Promise(e=>{this.#d=e})}finishEsbuildRun(){this.#d?.()}markRequestHandlersEntryOutdated(){this.#r++,!this.#e&&(this.#e=!0,this.#u=new Promise(e=>{this.#h=e}))}noteRequestHandlersEntryBuildStart(){this.#f=this.#r}markRequestHandlersEntryUpdated(){this.#e&&(this.#r>this.#f||(this.#e=!1,this.#h?.()))}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 Y("build.reload_markdoc_options",async()=>{const e=w.instance(),t=await U(this.serverOutDir),s=Object.fromEntries(Object.entries(t.tags).filter(([a])=>y[a]!=null?e.canAccessFeature(y[a]):!0));this.#o={...t,tags:s}})}get markdocOptions(){return{...this.#o,partials:this.getGlobalConfig(m),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()=>B.getInstance({baseDbDir:this.serverOutDir});parseMarkdoc=async({input:e,context:t,deps:s,resource:a})=>{const{data:{info:r,ast:o},compoundHash:l}=await j(e,this.markdocOptions,{actions:this,context:t},a);for(const i of r.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 r.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&&r.partials?.length)for(const i of s.routeSlugs){const n=this.routesPartials.get(i)||[];for(const c of r.partials)n.includes(c)||n.push(c);this.routesPartials.set(i,n)}return{info:r,ast:o,compoundHash:l}};async loadOpenApiDefinitions(e){return(await e.cache.load(".","load-oas-docs")).data}async loadAsyncApiDefinitions(e){return(await e.cache.load(".","asyncapi-docs")).data}async loadGraphqlDefinitions(e){return(await e.cache.load(".","load-graphql-docs")).data}setSearchEngine(e){this.searchEngine=e}setSearchFacets=e=>{this.searchFacets=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}=D(e,i);(n||c!==this.replacedEnvVars[l].replaced)&&delete this.replacedEnvVars[l]}const{resolvedObj:s,unsetEnvVars:a,replacedValues:r}=J(e);for(const o of a)this.unsetEnvVars.add(o);Object.assign(this.replacedEnvVars,r),Object.assign(this.config,s)};getConfig=()=>this.config;getGlobalConfig=e=>this.config[e];getSearchFacets=()=>this.searchFacets;addRedirect=(e,t,s={})=>{if(!w.instance().canAccessFeature("redirects")&&e!=="/")return;this.config.redirects||(this.config.redirects={});const o=h(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("*")&&z(this.config.wildcardRedirectsTree,o)};getRedirect=e=>{const t=h(e).toLowerCase(),s=W(t,this.config.redirects,this.config.wildcardRedirectsTree);if(!s)return null;if(R(s.to)){const a=h(s.to).toLowerCase();if(!a.endsWith("*")&&$(a,[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 a=JSON.stringify(t),r=s??H(a);return this.#t[e]===r||(this.#t[e]=r,await I(e,a,this.outdir),this.queueEvent("shared-data-updated",e)),e};addRouteSharedData=(e,t,s)=>{const a=L(e),r=this.routesSharedData.get(a)||{};r[t]=s,this.routesSharedData.set(a,r),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(m)||{},s=this.routesPartials.get(e);if(!s||s.length===0)return{};const a=this.getGlobalConfig(O)||{},r=new Set(s),o=Array.from(s);for(let i=0;i<o.length;i++){const n=o[i],c=a[n]?.partials??[];for(const d of c)r.has(d)||(r.add(d),o.push(d))}const l={};for(const i of r)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 a=[g,...this.lifecycleContext?.fs.localeFolders||[]].map(r=>({code:r,name:r}));for(const r of a){const o=A(e,g,r.code,a);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)this.mcpToolHandlers.set(s.name,{...s,importPath:e}),u.verbose("Created MCP tool %s",s.name)};getMcpTools=()=>Array.from(this.mcpToolHandlers.values());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());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())),r=[...(this.config.responseHeaders[e]??[]).filter(o=>!s.has(o.name.toLowerCase())),...t];this.config.responseHeaders[e]=r};getRouteByFsPath=e=>{const t=this.routesByFsPath.get(e);return t?this.getRouteBySlug(t):void 0};getRouteBySlug=(e,t={})=>{const{followRedirect:s=!0}=t,a=this.getRedirect(e);return s&&a?this.routesBySlug.get(h(a.to)):this.routesBySlug.get(e)};hasRouteOrRedirectBySlug=e=>{if(this.routesBySlug.has(e))return!0;const t=this.getRedirect(e);if(!t)return!1;if(!R(t.to))return!0;const s=h(t.to);return this.routesBySlug.has(s)};getRoutesByTemplateId=e=>this.newRoutes.filter(t=>t.templateId===e);getAllRoutesForLocale=(e=g)=>{const t=Array.from(this.routesBySlug.values()),s=e.toLowerCase();return t.filter(a=>e===g?!K(a.fsPath):a.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&&V(e.slug,s,this.outdir)}async resolveRouteStaticData(e,t,s){if(this.serverMode)return q(e.slug,this.outdir);const a={...this,contentDir:this.contentDir,parseMarkdoc:({input:c,context:d,resource:f})=>this.parseMarkdoc({input:c,context:d,deps:{routeSlugs:[e.slug]},resource:f})},r=await e.getStaticData?.(e,a)||{},o=new Set(this.routesDynamicComponents.get(e.slug)),l=this.routesSharedData.get(e.slug)||{};for(const c of Object.values(l)){const d=this.sharedDataMarkdocComponents.get(c);d&&d.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=r?.frontmatter||{};return{...r,frontmatter:{...n,seo:{...n?.seo,title:n?.seo?.title||await e.getNavText?.()}},props:{...r.props,dynamicMarkdocComponents:Array.from(o),metadata:{...r?.props?.metadata,...e.metadata},seo:{title:T,...i,...r.props?.seo},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(""):N(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.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:[]}};async toJson(){const e=[];for(const[s,a]of Object.entries(v))switch(a){case"map":const r=Array.from(this[s].entries());e.push([s,r]);break;case"object":s==="config"&&e.push([s,await this.getConfigWithEnvPlaceholders()]),e.push([s,this[s]]);break;default:throw new Error("Invalid format")}const t=Object.fromEntries(e);return t[E]=_.PLAN_GATES,t}static fromJson(e,t){const s=new P(t);for(const[r,o]of Object.entries(v))switch(o){case"map":s[r]=new Map(e[r]);break;case"object":if(r==="config"){s.setGlobalConfig(e[r]);break}s[r]=e[r];break;default:throw new Error("Invalid format")}s.config[m]=Q(s.config[m]||{});const a=e[E];return a&&G("PLAN_GATES",a),s}async getConfigWithEnvPlaceholders(){const e=JSON.parse(JSON.stringify(this.config));for(const t in this.replacedEnvVars){const{original:s}=this.replacedEnvVars[t],a=t.split(":"),r=a.pop(),{error:o,value:l}=D(e,a);if(o||!M(l)&&!Array.isArray(l)){await S.panicOnBuild(`Failed to replace env var with env name for ${t}`);continue}l[r]=s}return e}async reportUnsetEnvVars(){if(this.unsetEnvVars.size===0)return;const e=Array.from(this.unsetEnvVars).filter(s=>!Z.includes(s));if(e.length===0)return;const t=`Failed to resolve config. The following environment variables are not set: ${e.join(", ")}`;await S.panicOnBuildContentError(t)}}function Q(b){return k(b,e=>C.Ast.fromJSON(JSON.stringify(e)))}export{P as Store,Me as USER_DEFINED_API_FUNCTIONS_COUNTER_KEY};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `fetch` for requests to Redocly APIs (Reunite main API, feedback, search,
|
|
3
|
+
* Ask AI). Stamps the `x-redocly-client` identification header so portal
|
|
4
|
+
* traffic is attributed correctly — use it instead of bare `fetch` for any
|
|
5
|
+
* Redocly-bound request.
|
|
6
|
+
*/
|
|
7
|
+
export declare function fetchWithClient(input: string | URL, init?: Omit<RequestInit, 'headers'> & {
|
|
8
|
+
headers?: Record<string, string>;
|
|
9
|
+
}): Promise<Response>;
|
|
10
|
+
//# sourceMappingURL=fetch-with-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{envConfig as o}from"../config/env-config.js";const r="realm-server",t=o.REDOCLY_PORTAL_VERSION,E=t?`${r}/${t}`:r;function s(n,e={}){return fetch(n,{...e,headers:{...e.headers,"x-redocly-client":E}})}export{s as fetchWithClient};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare class SandboxContext {
|
|
2
|
+
#private;
|
|
3
|
+
readonly serverOutDir: string;
|
|
4
|
+
static register({ serverOutDir, readRoots }: {
|
|
5
|
+
serverOutDir: string;
|
|
6
|
+
readRoots?: string[];
|
|
7
|
+
}): void;
|
|
8
|
+
static resolve(fallbackServerOutDir: string): SandboxContext;
|
|
9
|
+
private constructor();
|
|
10
|
+
get tmpDir(): string;
|
|
11
|
+
get execArgv(): string[];
|
|
12
|
+
get env(): {
|
|
13
|
+
TMPDIR: string;
|
|
14
|
+
TMP: string;
|
|
15
|
+
TEMP: string;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=sandbox-context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as a}from"node:fs";import{dirname as l,join as m}from"node:path";class s{serverOutDir;static#e;static register({serverOutDir:e,readRoots:t}){s.#e=new s(e,t)}static resolve(e){return s.#e??new s(e)}#t;constructor(e,t=[]){this.serverOutDir=e,this.#t=s.#n(e,t)}get tmpDir(){return`${this.serverOutDir}/.data/tmp`}get execArgv(){return["--permission",...this.#t.map(e=>`--allow-fs-read=${e}/*`),`--allow-fs-write=${this.serverOutDir}/.data/*`,"--allow-addons"]}get env(){return{TMPDIR:this.tmpDir,TMP:this.tmpDir,TEMP:this.tmpDir}}static#r(e){if(!e)return e;const r=e.indexOf("/node_modules/");return r!==-1?e.slice(0,r):s.#s(e)??s.#i(e)??e}static#s(e){let t=e;for(;;){if(a(m(t,"node_modules",".pnpm")))return t;const r=l(t);if(r===t)return;t=r}}static#i(e){let t=e;for(;;){if(a(m(t,"node_modules")))return t;const r=l(t);if(r===t)return;t=r}}static#n(e,t){const r=[s.#r(e),...t].filter(Boolean).map(i=>i.replace(/\/+$/,"")).filter(Boolean),n=[...new Set(r)];return n.filter(i=>!n.some(o=>o!==i&&i.startsWith(`${o}/`)))}}export{s as SandboxContext};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{envConfig as
|
|
1
|
+
import{envConfig as s}from"../../config/env-config.js";import{fetchWithClient as a}from"../../utils/fetch-with-client.js";const d=(r,e)=>r.secureMethods?.includes(e)??!1;function u(r={}){return async(e,i)=>{const t=e.req.method;if(!d(r,t))return await i();const n=e.req.header("apiKey");if(!n)return e.json({message:"API key is required"},401);try{if(!s.BH_API_URL)return e.json({message:"API key validation service not configured"},500);const o=new URL("api-keys-verify",s.BH_API_URL).toString();if(!(await a(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n})})).ok)return e.json({message:"Invalid API key"},401);await i()}catch{return e.json({message:"API key validation failed"},400)}}}export{u as apiKeyMiddleware};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{KvService as l}from"../../persistence/kv/services/kv-service.js";import{DEFAULT_AUTHENTICATED_TEAM as
|
|
1
|
+
import{KvService as l}from"../../persistence/kv/services/kv-service.js";import{DEFAULT_AUTHENTICATED_TEAM as h}from"../../../constants/common.js";import{envConfig as s}from"../../config/env-config.js";import{fetchWithClient as T}from"../../utils/fetch-with-client.js";import{CACHE_CONTROL_NO_STORE_HEADER_VALUE as y,JWT_SECRET_KEY as p}from"../../constants/common.js";import*as m from"../jwt/jwt.js";import{AlgorithmTypes as I}from"../jwt/types.js";const f=60,E=e=>["POST","PUT","DELETE","PATCH"].includes(e),_=e=>["GET"].includes(e);function S({serverOutDir:e,protectReadMethods:t=!0}){return async(r,a)=>await w(r,a,e,t)}const w=async(e,t,r,a=!0)=>{e.header("Cache-Control",y);const n=e.req.method,i=E(n)||_(n)&&a,o=e.req.header("apiKey");if(o)return await C(e,t,o,r);const u=e.req.header("authorization")?.replace("Bearer ","");return u?await g(e,t,u):i?e.json({message:"API key is required"},401):await t()},C=async(e,t,r,a)=>{if(!s.BH_API_URL||!s.ORGANIZATION_ID)return e.json({message:"API key validation service not configured"},500);try{const n=await l.getInstance({baseDbDir:a});let i=await v(n,r);if(i)return e.set("apiKeyTeams",i.teams),await t();const o=new URL(`/api/orgs/${s.ORGANIZATION_ID}/session`,s.BH_API_URL).toString(),c=await T(o,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!c.ok)return e.json({message:"Invalid API key"},401);const A=(await c.json())?.user?.teams?.[s.ORGANIZATION_ID]??[],d=[h,...A];return e.set("apiKeyTeams",d),await n.set(["api-keys","reunite",r],{valid:!0,teams:d},{ttlInSeconds:f}),await t()}catch{return e.json({message:"API key validation failed"},400)}},g=async(e,t,r)=>{try{const a=await m.verify(r,p,I.HS256),n=m.decode(r).payload.isInternalConnection;return!a||!n?e.json({message:"API key is required"},401):await t()}catch{return e.json({message:"API key validation failed"},400)}},v=async(e,t)=>{try{return await e.get(["api-keys","reunite",t])}catch{return null}};export{S as catalogAuthMiddleware};
|