@aiquants/markdown-explorer-host 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -84,6 +84,7 @@ const explorer = createMarkdownExplorer({ ...applicationConfig, ...host })
84
84
  - The failure codes a host's answers carry (`MARKDOWN_EXPLORER_FAILURE_CODES`) and the error mapper (`createExplorerErrorMapper`).
85
85
  - The scopes: the scopes the edit grant asks for (`editConsentScopesOf`, `WRITE_SCOPE_REQUESTS`) and the scope port over a host's reader of granted scopes (`createTokenInfoScopePort`).
86
86
  - The workspace directories shared with readers (`resolveSharedWorkspaceRoot`, `sharedWorkspaceRootsOf`).
87
+ - The document path classification (`routeDocumentPath`, `DocumentRoute`): a path sorted into a workspace path, a GCS or Drive URI, denied or invalid, with the deny rules passed in — the classification the host's reads share.
87
88
  - The directory tree (`createDirectoryTree`), for a host that walks storage without assembling a whole host.
88
89
  - The document limits a host's own checks share: the text preview's bytes (`TEXT_PREVIEW_BYTES`) and the parse cache's budget (`parseCacheMaxBytesOf`).
89
90
 
package/dist/index.d.ts CHANGED
@@ -76,6 +76,24 @@ declare const createExplorerHost: <P>(setup: ExplorerHostSetup, ports: ExplorerH
76
76
  type ExplorerErrorMapper = (error: unknown, uri: string) => unknown;
77
77
  declare const createExplorerErrorMapper: (log: ExplorerHostLog) => ExplorerErrorMapper;
78
78
  type CloudReadAs = "reader" | "service-account";
79
+ type DocumentRoute = {
80
+ readonly kind: "workspace";
81
+ readonly relativePath: string;
82
+ } | {
83
+ readonly kind: "drive";
84
+ readonly uri: string;
85
+ readonly uriAsRead: string;
86
+ } | {
87
+ readonly kind: "gcs";
88
+ readonly uri: string;
89
+ readonly bucket: string;
90
+ readonly uriAsRead: string;
91
+ } | {
92
+ readonly kind: "denied";
93
+ } | {
94
+ readonly kind: "invalid";
95
+ };
96
+ declare const routeDocumentPath: (documentPath: string, deny: ExplorerPathRules) => DocumentRoute;
79
97
  declare const TEXT_PREVIEW_BYTES = 8192;
80
98
  declare const parseCacheMaxBytesOf: (conversion: Pick<MarkdownConversionLimits, "maxHtmlBytes">) => number;
81
99
  declare const editConsentScopesOf: (sources: MarkdownExplorerSourceSettings) => readonly string[];
@@ -112,4 +130,4 @@ type DirectoryTree = {
112
130
  readonly listCloudDirectory: (uri: string, credential: string | null, readAs: CloudReadAs, signal: AbortSignal) => Promise<ExplorerEntry[]>;
113
131
  };
114
132
  declare const createDirectoryTree: ({ storage, mapError }: DirectoryTreeOptions) => DirectoryTree;
115
- export { type CredentialPort, type DirectoryTree, type DirectoryTreeOptions, type EditAuditEvent, type ExplorerErrorMapper, type ExplorerHost, type ExplorerHostLog, type ExplorerHostPorts, type ExplorerHostSetup, GCS_BUCKET_NAME_RULE, type GrantedScopesOf, MARKDOWN_EXPLORER_EDIT_MODES, MARKDOWN_EXPLORER_FAILURE_CODES, MY_DRIVE_ROOT, type MarkdownExplorerEditMode, type MarkdownExplorerSourceKind, type MarkdownExplorerSourceRules, type MarkdownExplorerSourceSetting, type MarkdownExplorerSourceSettings, SHARED_DRIVES_ROOT, SHARED_WITH_ME_ROOT, type ScopePort, type SharedWorkspaceRoot, TEXT_PREVIEW_BYTES, type TokenInfoScopePortOptions, WRITE_SCOPE_REQUESTS, type WritableStorage, createDirectoryTree, createExplorerErrorMapper, createExplorerHost, createTokenInfoScopePort, editConsentScopesOf, isGcsBucketName, parseCacheMaxBytesOf, parseMarkdownExplorerSources, resolveSharedWorkspaceRoot, sharedWorkspaceRootsOf };
133
+ export { type CredentialPort, type DirectoryTree, type DirectoryTreeOptions, type DocumentRoute, type EditAuditEvent, type ExplorerErrorMapper, type ExplorerHost, type ExplorerHostLog, type ExplorerHostPorts, type ExplorerHostSetup, GCS_BUCKET_NAME_RULE, type GrantedScopesOf, MARKDOWN_EXPLORER_EDIT_MODES, MARKDOWN_EXPLORER_FAILURE_CODES, MY_DRIVE_ROOT, type MarkdownExplorerEditMode, type MarkdownExplorerSourceKind, type MarkdownExplorerSourceRules, type MarkdownExplorerSourceSetting, type MarkdownExplorerSourceSettings, SHARED_DRIVES_ROOT, SHARED_WITH_ME_ROOT, type ScopePort, type SharedWorkspaceRoot, TEXT_PREVIEW_BYTES, type TokenInfoScopePortOptions, WRITE_SCOPE_REQUESTS, type WritableStorage, createDirectoryTree, createExplorerErrorMapper, createExplorerHost, createTokenInfoScopePort, editConsentScopesOf, isGcsBucketName, parseCacheMaxBytesOf, parseMarkdownExplorerSources, resolveSharedWorkspaceRoot, routeDocumentPath, sharedWorkspaceRootsOf };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{isDeniedPath as _o,legacyTextEncodingOf as $o}from"@aiquants/markdown-explorer/server/core";import{toStorageError as wt}from"@aiquants/storage-api/web";import{decodeText as Qr,decodeTextLeniently as Zr,ExplorerError as et}from"@aiquants/markdown-explorer/server/core";var rt=Object.freeze([".png",".jpg",".jpeg",".gif",".svg",".webp",".ico",".bmp",".tiff",".avif"]),tt="image/svg+xml",ot=Object.freeze([["video",[".mp4",".webm",".mov",".avi",".mkv",".ogv"]],["audio",[".mp3",".wav",".ogg",".m4a",".flac",".aac",".wma"]],["pdf",[".pdf"]]]),nt=new Set(["text/markdown","text/x-markdown","application/vnd.google-apps.document"]),st=Object.freeze([".md",".markdown",".mdx"]),qe=new Set(["","application/octet-stream","binary/octet-stream","text/plain","application/x-empty"]),j=e=>e.replace(/;.*$/su,"").trim().toLowerCase(),Xe=(e,r)=>{if(j(r).startsWith("image/"))return!0;let t=e.toLowerCase();return rt.some(o=>t.endsWith(o))},Ye=(e,r)=>{let t=j(r);return t===tt?"svg":t.startsWith("image/")?"raster":e.toLowerCase().endsWith(".svg")?"svg":"raster"},Je=(e,r)=>{let t=j(r),o=e.toLowerCase();for(let[a,d]of ot)if((a==="pdf"?t==="application/pdf":t.startsWith(`${a}/`))||d.some(c=>o.endsWith(c)))return a;return null},me=(e,r)=>{let t=j(r);if(nt.has(t))return!0;let o=e.toLowerCase();return qe.has(t)&&st.some(a=>o.endsWith(a))},it="application/vnd.google-apps.",Qe="application/vnd.google-apps.folder",at=new Set(["application/json","application/xml","application/yaml","application/x-yaml","application/javascript","application/toml"]),ct=new Set(["","application/octet-stream"]),fe=e=>j(e).startsWith(it),Ze="application/vnd.google-apps.spreadsheet",De="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dt=new Map([["text/csv","csv"],["text/tab-separated-values","tsv"],[De,"workbook"],["application/vnd.ms-excel.sheet.macroenabled.12","workbook"],["application/vnd.oasis.opendocument.spreadsheet","workbook"]]),lt="application/vnd.ms-excel",ut=Object.freeze([[".csv","csv"],[".tsv","tsv"],[".tab","tsv"],[".xlsx","workbook"],[".xlsm","workbook"],[".ods","workbook"]]),pt=Object.freeze({format:"workbook",firstSheetText:"csv"}),mt=e=>qe.has(e)||Te(e)||e===lt,er=(e,r)=>{let t=j(r);if(t===Ze)return pt;let o=dt.get(t);if(o!==void 0)return{format:o,firstSheetText:null};if(!mt(t))return null;let a=e.toLowerCase(),d=ut.find(([u])=>a.endsWith(u));return d===void 0?null:{format:d[1],firstSheetText:null}},Te=e=>{let r=j(e);return r.startsWith("text/")||at.has(r)||r.endsWith("+json")||r.endsWith("+xml")},rr=e=>ct.has(j(e)),tr=(e,r,t)=>{let o=Qr(e,!r,t);return o===null||o.includes("\0")?null:o},or=(e,r,t)=>{let o=Zr(e,!r,t);return o.includes("\0")?null:o},Q=e=>[e.mtimeNs===null?"":e.mtimeNs.toString(),e.mtime===null?"":String(e.mtime.getTime()),String(e.size)].join("."),ft="application/vnd.google-apps.document",gt=Object.freeze({kind:"inline"}),yt=Object.freeze({kind:"draft"}),re=(e,r)=>e===null?null:j(r.mimeType)===ft?sr("document",r):e==="save"&&r.version!==null&&r.canEdit!==!1?gt:yt,nr=(e,r)=>e===null||j(r.mimeType)!==Ze?null:sr("spreadsheets",r),sr=(e,r)=>r.canEdit===!1?null:{kind:"external",href:`https://docs.google.com/${e}/d/${encodeURIComponent(r.id)}/edit`},Me=e=>{let r;try{r=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e)}catch{return null}return r.includes("\0")?null:r},ge=e=>{let r=Me(e);if(r===null)throw new et("unsupported");return r};var ir=(e,r,t)=>{let{storage:o}=r,{loader:a,router:d,mapError:u}=t;if(typeof o?.readStream!="function")throw new TypeError("[markdown-explorer] the asset port needs the storage client's readStream");if(typeof a?.statDocumentTarget!="function")throw new TypeError("[markdown-explorer] the asset port needs the document loader's statDocumentTarget (createDocumentLoader)");if(typeof d?.documentTargetOf!="function")throw new TypeError("[markdown-explorer] the asset port needs the document router's documentTargetOf (createDocumentRouter)");if(typeof u!="function")throw new TypeError("[markdown-explorer] the asset port needs the host's error mapper (createExplorerErrorMapper)");let{deny:c}=e;return async({principal:y,signal:b},D,_,{delivery:h})=>{let{readUri:O,meta:v,name:M,callOptions:A}=await a.statDocumentTarget(d.documentTargetOf(D,_),y,{deniedSegments:c,signal:b,revisions:!1}),C=h==="workbook"?{...A,exportPreference:[De]}:A,I=v.version,L=I===null?C:{...C,ifVersionMatch:I};return{name:M,contentType:v.mimeType,size:fe(v.mimeType)?null:v.size,version:Q(v),open:async H=>{try{return await o.readStream(O,H===null?L:{...L,range:H})}catch(N){throw u(N,O)}},bridge:{uri:O,storageVersion:I,readFailure:H=>u(wt(H,{operation:"readStream",uri:O}),O)}}}};var B=e=>e===""?"an empty string":e===null?"null":typeof e;var G=(e,r)=>{let t=e.principalKeyOf(r);if(typeof t=="string"&&t!=="")return t;throw new TypeError(`[markdown-explorer] the host's principalKeyOf must answer a non-empty string, the reader's stable key; got ${B(t)}`)};var U=e=>typeof e=="string"&&e!=="";import{MarkdownConversionTimeoutError as Vt,MarkdownResourceExhaustedError as qt}from"@aiquants/markdown/service-client";import{decodeTextLeniently as Xt,EXPLORER_MAX_HEADINGS as Yt,ExplorerError as z,isDeniedPath as Jt}from"@aiquants/markdown-explorer/server/core";import{storagePaths as Pe}from"@aiquants/storage-api/web";import{ExplorerError as _t}from"@aiquants/markdown-explorer/server/core";import{storagePaths as $t}from"@aiquants/storage-api/web";var ye=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null};var Et=80,ht="an object that could not be inspected",xt=e=>{let r=0,t=0;for(let o of e){if(r===Et)return JSON.stringify(`${e.slice(0,t)}\u2026`);r+=1,t+=o.length}return JSON.stringify(e)},St=e=>Array.isArray(e)?"an array":ye(e)?"a plain object":`a non-plain object (${Object.prototype.toString.call(e)})`,E=e=>{if(typeof e=="string")return xt(e);if(typeof e=="bigint")return`${String(e)}n`;if(Object.is(e,-0))return"-0";if(typeof e=="function")return"a function";if(typeof e=="object"&&e!==null)try{return St(e)}catch{return ht}return String(e)};import{ExplorerError as mr,MAX_DOCUMENT_PATH_LENGTH as Ct}from"@aiquants/markdown-explorer/server/core";import{storagePaths as We}from"@aiquants/storage-api/web";import{isDeniedPath as Ae}from"@aiquants/markdown-explorer/server/core";import{fromFileUri as kt,isStorageError as ar,storagePaths as Ce,toFileUri as Pt}from"@aiquants/storage-api/web";var we=(e,r,t)=>Ae(e,r)||t!==r&&Ae(e,t),Rt=e=>ar(e,"not_found"),bt=["failed_precondition","invalid_argument","is_a_directory"],cr=({storage:e,log:r,workspaceRoot:t})=>{let o=new Set,a=async(u,c)=>kt(await e.realPath(Pt(u),{authMode:"oauth2",signal:c})),d=async(u,c)=>{try{return await a(u,c)}catch(w){if(!Rt(w))throw w;return o.has(u)||(o.add(u),r.warn(`[markdown-explorer] the shared workspace directory ${u} is missing (not_found); reads treat it as containing nothing while it stays missing`)),null}};return async(u,c,w,y)=>{let b;try{b=await a(u,y)}catch(h){if(!ar(h))throw h;if(h.code==="not_found")return{kind:"missing"};if(h.code==="permission_denied")return{kind:"outside"};let O=bt.find(v=>v===h.code);if(O!==void 0)return{kind:"unfollowable",code:O};throw h}let D=await a(t,y);return(await Promise.all(c.map(h=>h===t?D:d(h,y)))).some(h=>h!==null&&Ce.isInsideDirectory(b,h))&&Ce.isInsideDirectory(b,D)?Ae(w,Ce.relativeToDirectory(b,D))?{kind:"denied"}:{kind:"inside",realPath:b}:{kind:"outside"}}},dr=e=>{switch(e.kind){case"inside":case"missing":return null;case"outside":case"unfollowable":return"not-found";case"denied":return"forbidden"}};import{storagePaths as _e}from"@aiquants/storage-api/web";var Ot="gdrive://shared",vt="gdrive://drives",Dt="gdrive://shared-with-me",Tt=new Set([Ot,vt,Dt]),pr=e=>e.every(r=>r!==""&&r!=="."&&r!==".."),$e=(e,r)=>r.includes("\\")||!pr(r.split("/"))?!1:e==="."||r===e||r.startsWith(`${e}/`),X=e=>{if(typeof e!="string"||!e.startsWith(_e.GCS_SCHEME))throw new RangeError(`a GCS root must be written gcs://<bucket>[/<prefix>]; got ${E(e)}`);let r=e.slice(_e.GCS_SCHEME.length),t=r.indexOf("/"),o=t<0?r:r.slice(0,t);if(o==="")throw new RangeError(`a GCS root must name a bucket after gcs://; got ${E(e)}`);return Object.freeze({uri:e,bucket:o,prefix:t<0?"":r.slice(t+1)})},lr=(e,r)=>{if(r!==""){let t=r.split("/"),o=t.at(-1)===""?t.slice(0,-1):t;if(o.length===0||!pr(o))return!1}return e===""||r===e||r.startsWith(`${e}/`)},ur=e=>{let r=e.slice(_e.GCS_SCHEME.length),t=r.indexOf("/");return t<0?"":r.slice(t+1)},Ie=(e,r)=>r.bucket===e.bucket&&lr(e.prefix,ur(r.uri))&&lr(e.prefix,ur(r.uriAsRead)),Mt=e=>e.kind==="drive"&&!Tt.has(e.uri),te=(e,r)=>{switch(e.kind){case"workspace":return r.kind==="workspace"&&e.roots.some(t=>$e(t,r.relativePath));case"gcs":return r.kind==="gcs"&&e.roots.some(t=>Ie(X(t),r));case"drive":return Mt(r)}};var Ee="gdrive://",At=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u,K=(e,r)=>{if(e.length>Ct)return{kind:"invalid"};let t=We.storagePathAsRead(e);if(we(r,e,t))return{kind:"denied"};if(e.startsWith(Ee))return e.length>Ee.length?{kind:"drive",uri:e,uriAsRead:t}:{kind:"invalid"};if(e.startsWith(We.GCS_SCHEME)){let o=e.slice(We.GCS_SCHEME.length),a=o.indexOf("/"),d=a<0?o:o.slice(0,a);return d===""?{kind:"invalid"}:{kind:"gcs",uri:e,bucket:d,uriAsRead:t}}return At.test(e)?{kind:"invalid"}:{kind:"workspace",relativePath:e}},fr=({sources:e,deny:r,refuseOutsideSharedWorkspace:t})=>{let o=d=>e.some(c=>c.kind==="gcs"&&c.serviceAccount&&te(c,d))?"service-account":"reader",a=(d,u)=>{switch(d.kind){case"workspace":return{kind:"workspace",relativePath:d.relativePath};case"drive":return{kind:"cloud",uri:d.uri,uriAsRead:d.uriAsRead,readUri:u,readAs:"reader"};case"gcs":return{kind:"cloud",uri:d.uri,uriAsRead:d.uriAsRead,readUri:d.uri,readAs:o(d)};case"denied":throw new mr("forbidden");case"invalid":throw new mr("invalid")}};return{documentTargetOf:(d,u)=>a(K(d,r),u),documentReadOf:(d,u)=>{let c=K(d,r),w=a(c,u),y=e.find(b=>te(b,c));if(y!==void 0)return{target:w,lang:y.lang};if(c.kind==="workspace")return t(c.relativePath);throw new Error(`[markdown-explorer] no source contains the admitted document path ${E(d)}`)}}};var he=(e,r,t)=>{let o=e.startsWith($t.GCS_SCHEME);if(!(o||e.startsWith(Ee)))throw new RangeError(`[cloud-read] not a GCS or Google Drive URI: ${E(e)}`);if(t==="service-account"){if(!o)throw new RangeError(`[cloud-read] only GCS is read as the service account; a Google Drive URI is always read with the reader's credential: ${E(e)}`);return{authMode:"service_account"}}if(t!=="reader")throw new RangeError(`[cloud-read] readAs must be "reader" or "service-account"; got ${E(t)}`);if(!U(r))throw new _t("unauthorized");return{accessToken:r,authMode:"oauth2"}};import{ExplorerError as It}from"@aiquants/markdown-explorer/server/core";import{storagePaths as gr}from"@aiquants/storage-api/web";var oe=(e,r)=>({root:gr.resolveWorkspacePath(e,r),directory:r}),ne=(e,r)=>{let t=e.flatMap(o=>o.kind==="workspace"?o.roots:[]);return Object.freeze([...new Set(t)].map(o=>oe(r,o)))},yr=(e,r)=>e.some(t=>gr.isInsideDirectory(r,t.root)),xe=(e,r,t)=>{throw e.length>0&&r.error("[markdown-explorer] refused a workspace document path outside the directories shared with readers:",t),new It("forbidden")};import{buildStorageTree as Wt,toFileUri as Lt}from"@aiquants/storage-api/web";var Ht=3e5,Se=e=>{try{return decodeURIComponent(e)}catch{return e}},wr=(e,r)=>e==="."?r:`${e}/${r}`,Er=(e,r)=>{let t=(e==="."?r:r.slice(e.length+1)).split("/");return t.slice(0,-1).map((o,a)=>wr(e,t.slice(0,a+1).join("/")))},hr=e=>e===null?{}:{modifiedAt:e.getTime()},xr=(e,r)=>e.map(t=>{let o=Se(t.name),a=wr(r,t.relativePath),d=hr(t.mtime);return t.isDir?{name:o,path:a,type:"directory",...d,children:xr(t.children??[],r)}:t.mimeType===""?{name:o,path:a,type:"file",...d}:{name:o,path:a,type:"file",mimeType:t.mimeType,...d}}),se=e=>e,Sr=(e,r)=>{let t=r.slice(e.length+1),o=t.endsWith("/")?t.slice(0,-1):t;if(o==="")return null;let a=o.split("/");return a.slice(0,-1).map((d,u)=>se(`${e}/${a.slice(0,u+1).join("/")}/`))},jt=e=>{let r=Se(e.name),t=se(e.uri),o=hr(e.mtime);return e.isDir?{name:r,path:t,type:"directory",...o,lazy:!0,children:[]}:e.mimeType===""?{name:r,path:t,type:"file",...o}:{name:r,path:t,type:"file",mimeType:e.mimeType,...o}},Le=e=>e.map(jt),He=({storage:e,mapError:r})=>{if(typeof e?.walkDirectory!="function"||typeof e.listDirectory!="function")throw new TypeError("[markdown-explorer] the directory tree needs the storage client's walkDirectory and listDirectory");if(typeof r!="function")throw new TypeError("[markdown-explorer] the directory tree needs the host's error mapper (createExplorerErrorMapper)");let t=async(d,u,c)=>{let w=Lt(d.root);try{let y=await e.walkDirectory(w,{authMode:"oauth2",excludeGlobs:[...u],timeoutMs:Ht,signal:c});return xr(Wt(y),d.directory)}catch(y){throw r(y,w)}},o=async(d,u,c,w)=>{let y=he(d,u,c);try{return await e.listDirectory(d,{...y,signal:w})}catch(b){throw r(b,d)}};return Object.freeze({listWorkspaceTree:t,listCloudItems:o,listCloudDirectory:async(d,u,c,w)=>Le(await o(d,u,c,w))})};var Ut=Object.freeze(["maxSourceBytes","maxHtmlBytes","deadlineMs"]),ke=e=>{if(typeof e!="object"||e===null)throw new TypeError(`[markdown-explorer] the conversion limits must be an object with maxSourceBytes, maxHtmlBytes and deadlineMs; got ${E(e)}`);for(let r of Ut){let t=e[r];if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] conversion.${r} must be a positive safe integer; got ${E(t)}`)}},kr=(e,r,t,o)=>({deniedPathSegments:r,maxHtmlBytes:e.maxHtmlBytes,validateExistence:!0,signal:t,timeoutMs:e.deadlineMs,includeSourceLines:o});import{ExplorerError as Nt}from"@aiquants/markdown-explorer/server/core";var ie=()=>{let e;return{promise:new Promise((t,o)=>{e={resolve:t,reject:o}}),...e}};var br=2,zt=2*br,Ft=50,je=e=>8*e.maxHtmlBytes,Bt=160,Gt=5*6e4,ae=Object.freeze({kind:"too-large"}),Or=Object.freeze({kind:"overdue"}),Pr=e=>e.outcome.kind==="parsed"?e.outcome.bytes:0,Kt=(e,r)=>!e.cloud||r-e.at<Gt,vr=(e,r,t,o,a,d,u)=>JSON.stringify([e,r,Q(t),o,a,d,u]),Dr=(e,r)=>e.headings.reduce((t,o)=>t+Bt+r(o.text)+r(o.id),r(e.htmlContent)),Rr=e=>{let r=new Map;return(t,o)=>new Promise((a,d)=>{if(o.aborted){d(o.reason);return}let u=r.get(t);u===void 0&&(u={taken:0,waiting:new Set},r.set(t,u));let c=u,w=()=>{o.removeEventListener("abort",y),c.taken+=1;let b=!1;a(()=>{if(b)return;b=!0,c.taken-=1;let[D]=c.waiting;D!==void 0?(c.waiting.delete(D),D()):c.taken===0&&r.delete(t)})},y=()=>{c.waiting.delete(w),d(o.reason)};if(c.taken<e){w();return}c.waiting.add(w),o.addEventListener("abort",y,{once:!0})})},Tr=e=>{let r=new Map,t=0,o=new Map,a=h=>{let O=r.get(h);O!==void 0&&(r.delete(h),t-=Pr(O))},d=()=>{for(let h of r.keys()){if(r.size<=Ft&&t<=e.maxBytes)break;a(h)}},u=(h,O,v)=>{a(h);let M={outcome:v,at:e.now(),cloud:O};r.set(h,M),t+=Pr(M),d()},c=(h,O,v,M)=>{o.get(h)===O&&(o.delete(h),M!==null&&u(h,v,M))},w=Rr(br),y=Rr(zt),b=(h,O,v)=>{let M=ie(),A={answer:M.promise,waiters:0,withdrawal:new AbortController};return o.set(h,A),M.promise.catch(()=>{}),v(A.withdrawal.signal).then(C=>{c(h,A,O,C.kind==="overdue"?null:C),M.resolve(C)},C=>{c(h,A,O,null),M.reject(C)}),A},D=async(h,O,v)=>{O.waiters+=1;let M=ie(),A=!0,C=()=>{A=!1,O.waiters-=1,O.waiters===0&&(o.get(h)===O&&o.delete(h),O.withdrawal.abort()),M.reject(v.reason)};v.aborted?C():v.addEventListener("abort",C,{once:!0});try{return await Promise.race([O.answer,M.promise])}finally{v.removeEventListener("abort",C),A&&(O.waiters-=1)}};return Object.freeze({parse:async(h,O,v,M,A)=>{let C=v?void 0:r.get(h),I;if(C!==void 0&&Kt(C,e.now()))r.delete(h),r.set(h,C),I=C.outcome;else{a(h);let L=v?void 0:o.get(h);I=await D(h,L===void 0?b(h,O,A):L,M)}if(I.kind!=="parsed")throw new Nt("too-large");return I},acquireSourceTurn:y,acquireConversionSlot:w})};var Cr=8192,Qt=(e,r)=>e===null?j(r.mimeType)===Qe:r.isDirectory,Mr=(e,r)=>{let t=new Uint8Array(r),o=0;for(let a of e){if(o>=r)break;let d=a.subarray(0,r-o);t.set(d,o),o+=d.byteLength}return t},Zt=(e,r)=>{try{return Pe.resolveWorkspacePath(e,r)}catch(t){if(t instanceof RangeError)return null;throw t}},Ar=(e,r,t)=>{let{workspaceRoot:o}=e,{storage:a,credentials:d,log:u}=r;if(typeof a?.getResource!="function"||typeof a.readStream!="function"||typeof a.realPath!="function")throw new TypeError("[markdown-explorer] the document loader needs the storage client's getResource, readStream and realPath");if(typeof r.markdown?.convert!="function")throw new TypeError("[markdown-explorer] the document loader needs the markdown service's convert (ExplorerHostPorts.markdown)");if(typeof d?.credentialOf!="function"||typeof d.principalKeyOf!="function")throw new TypeError("[markdown-explorer] the document loader needs the host's credentials (credentialOf and principalKeyOf)");if(typeof r.now!="function")throw new TypeError("[markdown-explorer] the document loader needs the host's clock (ExplorerHostPorts.now)");if(typeof r.heldBytesOf!="function")throw new TypeError("[markdown-explorer] the document loader needs the host's string size (ExplorerHostPorts.heldBytesOf)");if(typeof u?.warn!="function"||typeof u.error!="function")throw new TypeError("[markdown-explorer] the document loader needs the host's records (with warn and error functions)");if(typeof t!="function")throw new TypeError("[markdown-explorer] the document loader needs the host's error mapper (createExplorerErrorMapper)");if(typeof o!="string"||!Pe.isAbsolutePath(o))throw new RangeError(`[markdown-explorer] the workspace root must be an absolute URI-space path; got ${E(o)}`);ke(e.conversion);let c=Object.freeze({maxSourceBytes:e.conversion.maxSourceBytes,maxHtmlBytes:e.conversion.maxHtmlBytes,deadlineMs:e.conversion.deadlineMs}),w=je(c),y=Tr({now:()=>r.now(),maxBytes:w}),b=ne(e.sources,o),D=cr({storage:a,log:u,workspaceRoot:o}),_=m=>({id:G(d,m),accessToken:d.credentialOf(m)}),h=async(m,g)=>C(await a.readStream(m,g),Cr),O=async(m,g,f)=>{let{head:n,truncated:p}=await C(await a.readStream(m,g),c.maxSourceBytes);return p?null:{text:Xt(n,!0,f),editable:Me(n)!==null}},v=async(m,g,f,n,p,x)=>{let s;try{s=await r.markdown.convert({markdownText:m,filePath:g,workspaceRoot:o,userOAuthToken:U(f.accessToken)?f.accessToken:void 0},kr(c,n,p,x))}catch(l){if(l instanceof qt)return ae;if(l instanceof Vt)return u.warn(`[markdown-explorer] converting a Markdown document passed its deadline of ${c.deadlineMs} ms; the converter stopped and its readers are answered too-large:`,g),Or;throw l}if(s.headings.length>Yt)return ae;let i=Dr(s,l=>r.heldBytesOf(l));return i>w?ae:{kind:"parsed",result:s,bytes:i}},M=async(m,g,f,n,p,x,s,i)=>{let l=await y.acquireSourceTurn(n.id,m);try{m.throwIfAborted();let S=await O(f,{...p,signal:m},i);if(S===null)return ae;let P=await y.acquireConversionSlot(n.id,m);try{m.throwIfAborted();let R=await v(S.text,g,n,x,m,s);return R.kind==="parsed"?{...R,editable:S.editable}:R}finally{P()}}finally{l()}},A=(m,g,f,n,p,x,s,i)=>y.parse(vr(m,g,f,n.id,s.deniedSegments,i,s.legacyTextEncoding),p,s.refresh,s.signal,async l=>M(l,m,g,n,x,s.deniedSegments,i,s.legacyTextEncoding)),C=async(m,g)=>{let f=m.getReader(),n=[],p=0;for(;p<=g;){let{done:x,value:s}=await f.read();if(x)return{head:Mr(n,p),truncated:!1};n.push(s),p+=s.byteLength}return f.cancel().catch(x=>u.warn("[markdown-explorer] cancelling a stream after reading its head failed",x)),{head:Mr(n,g),truncated:!0}},I=m=>{if(m.kind==="cloud")return{uri:m.uri,readUri:m.readUri,documentPath:m.uri,pathAsRead:m.uriAsRead,workspacePath:null};if(Pe.isAbsolutePath(m.relativePath))throw new z("invalid");let g=Zt(o,m.relativePath);if(g===null||!yr(b,g))return xe(b,u,m.relativePath);let f=Pe.toWorkspaceUri(o,m.relativePath);return{uri:f,readUri:f,documentPath:m.relativePath,pathAsRead:m.relativePath,workspacePath:g}},L=async(m,g,f)=>{let{uri:n,readUri:p,documentPath:x,pathAsRead:s,workspacePath:i}=I(m),l=i===null;if(we(f.deniedSegments,x,s))throw new z("forbidden");if(i!==null){let T=dr(await D(i,b.map($=>$.root),f.deniedSegments,f.signal));if(T!==null)throw u.error("[markdown-explorer] refused a workspace document by the file its symbolic links reach:",{documentPath:x,refusal:T}),new z(T)}let S=m.kind==="cloud"?he(p,g.accessToken,m.readAs):{authMode:"oauth2"},P={...S,signal:f.signal},R;try{R=await a.getResource(p,f.revisions===!0?{...P,revisions:!0}:P)}catch(T){throw t(T,n)}if(Jt(f.deniedSegments,R.name))throw new z("forbidden");if(Qt(i,R))throw new z("unsupported");return{uri:n,readUri:p,documentPath:x,cloud:l,meta:R,name:Se(R.name),sourceOptions:S,callOptions:P}},H=async(m,g,f)=>{let{uri:n,readUri:p,documentPath:x,cloud:s,meta:i,name:l,sourceOptions:S,callOptions:P}=await L(m,g,{deniedSegments:f.deniedSegments,signal:f.signal,revisions:!1});try{let R=Q(i);if(Xe(x,i.mimeType))return{kind:"image",name:l,imageType:Ye(x,i.mimeType),version:R};let T=Je(x,i.mimeType);if(T!==null)return{kind:"media",name:l,mediaType:T,version:R};if(me(l,i.mimeType)){if(i.size>c.maxSourceBytes)throw new z("too-large");let pe=re(f.editMode,i),ve=await A(n,p,i,g,s,S,f,pe?.kind==="inline"||pe?.kind==="draft");return{kind:"markdown",name:l,htmlContent:ve.result.htmlContent,headings:ve.result.headings,lang:f.lang,edit:pe?.kind==="external"||ve.editable?pe:null}}let $=er(l,i.mimeType);if($!==null)return{kind:"spreadsheet",name:l,format:$.format,firstSheetText:$.firstSheetText,edit:nr(f.editMode,i),version:R};if(fe(i.mimeType))return{kind:"file",name:l,version:R};let W=Te(i.mimeType);if(!(W||rr(i.mimeType)))return{kind:"file",name:l,version:R};let{head:ee,truncated:Oe}=await h(p,P),Ve=W?or(ee,Oe,f.legacyTextEncoding):tr(ee,Oe,f.legacyTextEncoding);return Ve===null?{kind:"file",name:l,version:R}:{kind:"text",name:l,version:R,text:Ve,truncated:Oe,lang:f.lang}}catch(R){throw t(R,n)}},N=async(m,g)=>{if(m.meta.size>c.maxSourceBytes)throw new z("too-large");let f=m.callOptions.signal;if(f===void 0)throw new Error("[markdown-explorer] reading a source for the editor needs the request's signal");let n=await y.acquireSourceTurn(g.id,f);try{let{head:p,truncated:x}=await C(await a.readStream(m.readUri,m.callOptions),c.maxSourceBytes);if(x)throw new z("too-large");return ge(p)}catch(p){throw t(p,m.uri)}finally{n()}},k=async(m,g,f,n)=>{let p=m.callOptions.signal;if(p===void 0)throw new Error("[markdown-explorer] previewing a draft needs the request's signal");let x=await y.acquireConversionSlot(g.id,p);try{let s=await v(f,m.uri,g,n,p,!0);if(s.kind!=="parsed")throw new z("too-large");return{htmlContent:s.result.htmlContent,headings:s.result.headings}}finally{x()}};return Object.freeze({loadMarkdownDoc:async(m,g,f)=>H(m,_(g),f),statDocumentTarget:async(m,g,f)=>L(m,_(g),f),readMarkdownSourceForEditing:async(m,g)=>N(m,_(g)),previewMarkdownDraft:async(m,g,f,n)=>k(m,_(g),f,n)})};import{ExplorerError as q}from"@aiquants/markdown-explorer/server/core";import{isStorageError as oo}from"@aiquants/storage-api/web";import{ExplorerError as F}from"@aiquants/markdown-explorer/server/core";import{Code as eo,isStorageError as Y,isStreamLimitRejection as ro}from"@aiquants/storage-api/web";var V=Object.freeze({rootUnavailable:"root-unavailable",driveScopeInsufficient:"drive-scope-insufficient",storageBusy:"storage-busy",storageTimeout:"storage-timeout",documentChanged:"changed"});var to=Object.freeze(["ACCESS_TOKEN_SCOPE_INSUFFICIENT","insufficientPermissions","insufficient authentication scopes"]),Ue=e=>e instanceof Error&&to.some(r=>e.message.includes(r)),Ne=e=>{if(typeof e?.warn!="function")throw new TypeError("[markdown-explorer] the error mapper needs the host's records (with a warn function)");return(r,t)=>t.startsWith("gdrive://")&&Ue(r)?(e.warn(`[markdown-explorer] Google Drive rejected the reader's token for a missing scope: ${t}`),new F("forbidden",{code:V.driveScopeInsufficient,cause:r})):Y(r,"not_found")?new F("not-found",{cause:r}):Y(r,"permission_denied")?new F(r.connectCode===eo.Unauthenticated?"unauthorized":"forbidden",{cause:r}):Y(r,"is_a_directory")?new F("unsupported",{cause:r}):ro(r)?(e.warn(`[markdown-explorer] The storage service refused a stream because the ${r.streamLimit.scope} is at its stream limit: ${t}: ${r.message}`),new F("failed",{code:V.storageBusy,cause:r})):Y(r,"resource_exhausted")?new F("too-large",{cause:r}):Y(r,"deadline_exceeded")?(e.warn(`[markdown-explorer] A storage call ran out of time: ${t}: ${r.message}`),new F("failed",{code:V.storageTimeout,cause:r})):Y(r,"invalid_argument")?new F("invalid",{cause:r}):Y(r,"conflict")?new F("not-found",{code:V.documentChanged,cause:r}):r};var _r=(e,r)=>{if(!Array.isArray(e))throw new TypeError("[markdown-explorer] the edit policy needs the editing sources (createSources' editingSources)");if(typeof r?.warn!="function")throw new TypeError("[markdown-explorer] the edit policy needs the host's records (with a warn function)");return async(o,a)=>{let d=!1;for(let{source:u,edit:c}of e){if(c==="preview"&&d||!u.boundary.contains(a))continue;let{confirm:w}=u.boundary,y=w===void 0;if(!y&&w!==void 0)try{y=(await w(o,a)).inside}catch(b){r.warn(`[MarkdownEdit] the editing source ${u.id} could not confirm a document, which it therefore does not offer for editing:`,b)}if(y){if(c==="save")return"save";d=!0}}return d?"preview":null}},no=e=>new TextEncoder().encode(e).byteLength,so=e=>({id:e.id,modifiedAt:e.mtime===null?null:e.mtime.toISOString(),size:e.size,author:e.author===""?null:e.author,kept:e.keepForever,current:e.isHead}),$r=(e,r,t)=>{let{storage:o,credentials:a,scopes:d,log:u}=r,{loader:c,router:w,editModeOf:y,mapError:b}=t;if(typeof o?.updateFile!="function"||typeof o.listRevisions!="function"||typeof o.readRevision!="function")throw new TypeError("[markdown-explorer] the edit ports need the storage client's updateFile, listRevisions and readRevision");if(typeof a?.principalKeyOf!="function")throw new TypeError("[markdown-explorer] the edit ports need the host's credentials (with a principalKeyOf function)");if(typeof d?.missingWrite!="function")throw new TypeError("[markdown-explorer] the edit ports need the host's scopes (with a missingWrite function)");if(typeof u?.error!="function")throw new TypeError("[markdown-explorer] the edit ports need the host's records (with an error function)");if(typeof r.audit!="function")throw new TypeError("[markdown-explorer] the edit ports need the host's audit (ExplorerHostPorts.audit)");if(typeof c?.statDocumentTarget!="function"||typeof c.readMarkdownSourceForEditing!="function"||typeof c.previewMarkdownDraft!="function")throw new TypeError("[markdown-explorer] the edit ports need the document loader's statDocumentTarget, readMarkdownSourceForEditing and previewMarkdownDraft (createDocumentLoader)");if(typeof w?.documentTargetOf!="function")throw new TypeError("[markdown-explorer] the edit ports need the document router's documentTargetOf (createDocumentRouter)");if(typeof y!="function")throw new TypeError("[markdown-explorer] the edit ports need the edit policy (createEditModeOf)");if(typeof b!="function")throw new TypeError("[markdown-explorer] the edit ports need the host's error mapper (createExplorerErrorMapper)");ke(e.conversion);let{maxSourceBytes:D}=e.conversion,{deny:_}=e,h=Object.freeze({kind:"grant",href:e.grantHref}),O=k=>{let m=K(k,_);return m.kind==="drive"?"drive":m.kind==="gcs"?"gcs":null},v=(k,m,g)=>{let f=w.documentTargetOf(k,m);return f.kind==="cloud"&&g==="save"?{...f,readAs:"reader"}:f},M=async(k,m,g,f)=>{let n=await y(k,m);if(n===null)throw new q("forbidden");let p=await c.statDocumentTarget(v(m,g,n),k.principal,{deniedSegments:_,signal:k.signal,revisions:f});if(!me(p.name,p.meta.mimeType))throw new q("unsupported");return{editMode:n,stated:p}},A=async(k,m)=>{let g=await d.missingWrite(k.principal,m,k.signal);if(g===!0)return!0;if(g==="unknown"||g===!1)return!1;throw new TypeError(`[markdown-explorer] the host's scopes.missingWrite must answer true, false or "unknown"; got ${B(g)}`)},C=async(k,m,g)=>{let{editMode:f,stated:n}=g;if(f!=="save"||n.meta.canEdit===!1)throw new q("forbidden");if(re(f,n.meta)?.kind!=="inline"||n.meta.version===null)throw new q("unsupported");let p=O(m);return p!==null&&await A(k,p)?h:{stated:n,version:n.meta.version,storage:p}},I=async(k,m,g)=>C(k,m,await M(k,m,g,!1)),L=async(k,m,g)=>{let f=await I(k,m,g);if("kind"in f)throw new q("unauthorized");return{text:await c.readMarkdownSourceForEditing(f.stated,k.principal),version:f.version}},H=async(k,m,g)=>{let{editMode:f,stated:n}=await M(k,m,g,!0);if(f!=="save")throw new q("forbidden");if(n.meta.revisions!=="kept")throw new q("unsupported");return n};return Object.freeze({source:async(k,m,g)=>{let f=await M(k,m,g,!0);if(re(f.editMode,f.stated.meta)?.kind==="draft")return{kind:"draft",text:await c.readMarkdownSourceForEditing(f.stated,k.principal)};let n=await C(k,m,f);return"kind"in n?n:{kind:"edit",text:await c.readMarkdownSourceForEditing(n.stated,k.principal),version:n.version,history:n.stated.meta.revisions==="kept"}},save:async(k,m,g,f)=>{let n=await I(k,m,g);if("kind"in n)return n;let{stated:p,storage:x}=n,s={principalKey:G(a,k.principal),path:m,baseVersion:f.baseVersion,bytes:no(f.text)};try{let i=await o.updateFile(p.meta.uri,f.text,{...p.callOptions,ifVersionMatch:f.baseVersion,keepRevision:x==="drive",mimeType:p.meta.mimeType});if(i.version===null)throw new Error(`[markdown-explorer] the storage wrote ${p.meta.uri} but reported no version`);return r.audit({kind:"saved",...s,version:i.version}),{kind:"saved",version:i.version}}catch(i){if(oo(i,"conflict")){let l=await L(k,m,g);return r.audit({kind:"conflict",...s,version:l.version}),{kind:"conflict",version:l.version,text:l.text}}if(Ue(i))return r.audit({kind:"grant-needed",...s,version:null}),h;throw u.error("[MarkdownEdit] save failed",{...s,error:i}),b(i,p.uri)}},preview:async(k,m,g,f)=>{let{stated:n}=await M(k,m,g,!1);return await c.previewMarkdownDraft(n,k.principal,f,_)},revisions:async(k,m,g)=>{let f=await H(k,m,g);try{return(await o.listRevisions(f.meta.uri,f.callOptions)).map(so).reverse()}catch(n){throw b(n,f.uri)}},revision:async(k,m,g,f)=>{let n=await H(k,m,g),p;try{p=await o.readRevision(n.meta.uri,f,n.callOptions)}catch(x){throw b(x,n.uri)}if(p.byteLength>D)throw new q("too-large");return ge(p)}})};import{ExplorerError as Z}from"@aiquants/markdown-explorer/server/core";import{isStorageError as Do,isStreamLimitRejection as To,storagePaths as Mo}from"@aiquants/storage-api/web";import{isDeniedPath as Ur,isExplorerDocumentLang as ao,isExplorerSourceId as co}from"@aiquants/markdown-explorer/server/core";var ze='3 to 222 lowercase letters, digits, "-", "_" or ".", starting and ending with a letter or digit, each dot-separated part 1 to 63 characters',io=/^[a-z0-9][a-z0-9._-]{1,220}[a-z0-9]$/u;var Fe=e=>typeof e=="string"&&io.test(e)&&e.split(".").every(r=>r.length>=1&&r.length<=63);var J="gdrive://id:root",ce="gdrive://shared",de="gdrive://shared-with-me",Be=Object.freeze(["save","preview"]),Re=Object.freeze({min:1,max:16}),Ir=16,Wr=64,lo="ja",Lr=Object.freeze(["id","kind","label","roots","serviceAccount","edit","lang"]),Hr=Object.freeze(["id","kind","roots"]),jr=Object.freeze(["workspace","drive","gcs"]),uo=/^gdrive:\/\/id:[A-Za-z0-9_-]{10,128}$/u,Nr=/\p{Cc}/u,po="id:",mo=e=>{let{setting:r,deny:t,allowWorkspaceSave:o}=e;if(typeof r!="string"||r.trim()==="")throw new TypeError(`[markdown-explorer] the sources setting needs a name for its refusals; got ${E(r)}`);if(typeof o!="boolean")throw new TypeError(`[markdown-explorer] ${r} allowWorkspaceSave must be true or false; got ${E(o)}`);return{refuse:(a,d)=>{throw new Error(`[markdown-explorer] ${r} ${a}; got ${d}`)},deny:t}},fo=(e,r,{refuse:t,deny:o})=>{if(typeof e!="string")return t("workspace roots must be strings",`${r}: ${E(e)}`);if(e.trim()==="")return t("workspace roots must not be blank",`${r}: ${E(e)}`);if(e.startsWith("/"))return t("workspace roots must be relative to the workspace root, not absolute",`${r}: ${E(e)}`);if(e.includes("\\"))return t("workspace roots must not contain a backslash",`${r}: ${E(e)}`);let a=e.split("/").filter(u=>u!==""&&u!==".");if(a.includes(".."))return t("workspace roots must not contain a .. segment",`${r}: ${E(e)}`);let d=a.length===0?".":a.join("/");return Ur(o,d)?t("workspace roots must not be refused by the deny rules",`${r}: ${E(e)}`):d},go=(e,r,{refuse:t,deny:o})=>{if(typeof e!="string")return t("gcs roots must be strings",`${r}: ${E(e)}`);let a;try{a=X(e)}catch{return t("gcs roots must be written gcs://<bucket>[/<prefix>]",`${r}: ${E(e)}`)}if(e.endsWith("/"))return t("gcs roots must be written without a trailing /",`${r}: ${E(e)}`);if(!Fe(a.bucket))return t(`gcs roots must name a Cloud Storage bucket (${ze})`,`${r}: ${E(e)}`);if(a.prefix!==""){let d=a.prefix.split("/");if(d.some(u=>u===""||u==="."||u===".."))return t("gcs root prefixes must not have an empty, . or .. segment",`${r}: ${E(e)}`);if(a.prefix.includes("\\")||a.prefix.includes("%")||Nr.test(a.prefix))return t("gcs root prefixes must not contain a backslash, % or a control character",`${r}: ${E(e)}`);if(d[0]?.startsWith(po))return t('gcs root prefixes must not start with "id:"',`${r}: ${E(e)}`)}return Ur(o,e)?t("gcs roots must not be refused by the deny rules",`${r}: ${E(e)}`):e},yo=(e,r,{refuse:t})=>e===J||e===ce||e===de||typeof e=="string"&&uo.test(e)?e:t(`drive roots must be ${J}, ${ce}, ${de} or gdrive://id:<id> (10 to 128 letters, digits, "_" or "-"); name paths are refused`,`${r}: ${E(e)}`),be=(e,r,t)=>{if(e==="workspace")return r==="."||t===r||t.startsWith(`${r}/`);let o=X(r),a=X(t);return o.bucket===a.bucket&&(o.prefix===""||a.prefix===o.prefix||a.prefix.startsWith(`${o.prefix}/`))},wo=(e,r,t,o)=>{let{refuse:a}=o;if(!Array.isArray(r))return a("roots must be an array",`${t}: ${E(r)}`);if(e==="drive")return r.length!==1?a("a drive source must have exactly one root (configure one source per drive root)",`${t}: ${E(r)}`):Object.freeze([yo(r[0],t,o)]);if(r.length<1||r.length>Ir)return a(`a ${e} source must have 1 to ${Ir} roots`,`${t}: ${E(r)}`);let d=Array.from(r,u=>e==="workspace"?fo(u,t,o):go(u,t,o));if(e==="workspace"&&d.includes(".")&&d.length>1)return a('"." (the whole workspace) must be the only root of its source',`${t}: ${E(r)}`);for(let[u,c]of d.entries())for(let w of d.slice(u+1)){if(c===w)return a("roots of one source must be unique",`${t}: ${E(c)}`);if(be(e,c,w)||be(e,w,c))return a("roots of one source must not nest",`${t}: ${E(c)} and ${E(w)}`)}return Object.freeze(d)},Eo=(e,r,{refuse:t})=>{if(typeof e!="string")return t("label must be a string",`${r}: ${E(e)}`);let o=e.trim();return o===""?t("label must not be blank",`${r}: ${E(e)}`):[...o].length>Wr?t(`label must be at most ${Wr} characters`,`${r}: ${E(e)}`):Nr.test(e)?t("label must not contain a control character",`${r}: ${E(e)}`):o},ho=(e,r,t,{refuse:o})=>{if(!Object.hasOwn(e,"serviceAccount"))return!1;if(r!=="gcs")return o("serviceAccount may be set only on a gcs source (Drive and the workspace are never read as the service account)",t);let{serviceAccount:a}=e;return typeof a!="boolean"?o("serviceAccount must be true or false",`${t}: ${E(a)}`):a},xo=(e,r,t,{refuse:o})=>{if(!Object.hasOwn(e,"edit"))return null;let{edit:a}=e,d=Be.find(u=>u===a);return d===void 0?o(`edit must be ${Be.map(u=>E(u)).join(" or ")}`,`${t}: ${E(a)}`):d==="save"&&r?o(`edit must not be "save" on a source read as the service account (a save writes with the reader's own account)`,t):d},So=(e,r,{refuse:t})=>{if(!Object.hasOwn(e,"lang"))return lo;let{lang:o}=e;return ao(o)?o:t('lang must be a canonical BCP 47 language tag (such as "ja" or "en-US")',`${r}: ${E(o)}`)},ko=(e,r,t)=>{let{refuse:o}=t,a=`element ${r}`;if(!ye(e))return o("elements must be objects",`${a}: ${E(e)}`);let d=Object.keys(e).find(v=>!Lr.includes(v));if(d!==void 0)return o(`elements may have only the keys ${Lr.join(", ")} (unknown key ${E(d)})`,a);let u=Hr.find(v=>!Object.hasOwn(e,v));if(u!==void 0)return o(`elements must have the keys ${Hr.join(", ")} (missing ${E(u)})`,a);let{id:c,kind:w}=e;if(!co(c))return o('id must use lowercase letters, digits and "-" and start with a letter or digit',`${a}: ${E(c)}`);let y=jr.find(v=>v===w);if(y===void 0)return o(`kind must be one of ${jr.join(", ")}`,`${a}: ${E(w)}`);let b=wo(y,e.roots,a,t),D=ho(e,y,a,t),_=xo(e,D,a,t),h=So(e,a,t),O=y==="drive"&&b[0]===J;return Object.hasOwn(e,"label")?Object.freeze({id:c,kind:y,label:Eo(e.label,a,t),roots:b,serviceAccount:D,edit:_,lang:h}):O?Object.freeze({id:c,kind:y,label:null,roots:b,serviceAccount:D,edit:_,lang:h}):o(`label is required except for a drive source rooted at ${J}`,a)},Po=(e,r)=>{if(e.kind!==r.kind)return!1;let{kind:t}=e;return t==="drive"?!0:e.roots.some(o=>r.roots.some(a=>be(t,o,a)||be(t,a,o)))},Ro=(e,r)=>{let t=mo(r),{refuse:o}=t;if(!Array.isArray(e)||e.length<Re.min||e.length>Re.max)return o(`must be an array of ${Re.min} to ${Re.max} sources`,E(e));let a=Array.from(e,(w,y)=>ko(w,y,t)),d=new Set,u=new Set,c=new Set;for(let[w,y]of a.entries()){d.has(y.id)&&o("ids must be unique",`element ${w}: ${E(y.id)}`),d.add(y.id),y.label!==null&&(u.has(y.label)&&o("labels must be unique after trimming",`element ${w}: ${E(y.label)}`),u.add(y.label));for(let b of y.roots){let D=`${y.kind}\0${b}`;c.has(D)&&o(`the same ${y.kind} root must not appear in two sources`,`element ${w}: ${E(b)}`),c.add(D)}for(let[b,D]of a.slice(0,w).entries())D.lang!==y.lang&&Po(D,y)&&o("sources that can show the same document must have the same lang (any two drive sources, and two workspace or two gcs sources whose roots nest)",`element ${w}: ${E(y.lang)} (element ${b}: ${E(D.lang)})`)}if(!r.allowWorkspaceSave){let w=a.findIndex(y=>y.kind==="workspace"&&y.edit==="save");w>=0&&o('must not let readers save a workspace source ("edit": "save"; the host does not allow saving its workspace)',`element ${w}`)}return Object.freeze(a)};import{ExplorerError as bo}from"@aiquants/markdown-explorer/server/core";import{isStorageError as Oo,MAX_PLACEMENT_ANCESTORS as zr,MAX_PLACEMENT_URIS as Fr}from"@aiquants/storage-api/web";var Ge=3e4,Br=1e4,vo="[markdown-explorer] the storage-api binary does not answer IsWithin; rebuild it",Gr=e=>{let{isWithin:r,ttlMs:t,maxEntries:o,schedule:a,now:d,logger:u}=e,c=Object.freeze([...e.roots]);if(c.length===0||c.length>zr||new Set(c).size!==c.length)throw new RangeError(`[markdown-explorer] a Drive boundary needs 1 to ${zr} unique roots; got ${String(c.length)} roots, ${String(new Set(c).size)} unique`);if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] the Drive placement TTL must be a positive integer; got ${E(t)}`);if(!Number.isSafeInteger(o)||o<=0)throw new RangeError(`[markdown-explorer] the Drive placement entry limit must be a positive integer; got ${E(o)}`);if(typeof r!="function")throw new TypeError("[markdown-explorer] a Drive boundary needs the storage client's isWithin");if(typeof a!="function")throw new TypeError("[markdown-explorer] a Drive boundary needs the host's schedule (ExplorerHostPorts.schedule)");if(typeof d!="function")throw new TypeError("[markdown-explorer] a Drive boundary needs the host's clock (ExplorerHostPorts.now)");if(typeof u!="function")throw new TypeError("[markdown-explorer] a Drive boundary needs a logger for its root states");let w=new Map,y=new Map,b=new Map,D=new Map,_=new Set,h=(s,i)=>`${s.id}\0${i}`,O=(s,i,l)=>{s.delete(i),s.set(i,l);for(let S of s.keys()){if(s.size<=o)break;s.delete(S)}},v=(s,i)=>{let l=s.get(i);if(l!==void 0){if(l.expiresAt>d())return l;s.delete(i)}},M=s=>{if(!U(s.accessToken))throw new bo("unauthorized")},A=s=>{if(!c.includes(s))throw new RangeError(`[markdown-explorer] ${E(s)} is not a configured Drive root`)},C=(s,i)=>{let l=`${s}\0${i}`;_.has(l)||(_.add(l),u(`[markdown-explorer] the Drive source root ${s} is ${i} for a reader`,{root:s,state:i}))},I=(s,i)=>{switch(s.state){case"within":return Object.freeze({state:"within",roots:new Set(s.ancestorIndexes.flatMap(l=>c.slice(l,l+1))),resolvedUri:s.resolvedUri,complete:!0,expiresAt:i});case"outside":return Object.freeze({state:"outside",expiresAt:i});case"not_found":return Object.freeze({state:"not-found",expiresAt:i});case"trashed":return Object.freeze({state:"trashed",expiresAt:i})}},L=(s,i)=>{let l=h(s.reader,i);return b.get(l)?.batch===s&&b.delete(l),s.answers.get(i)},H=async(s,i)=>{try{s.controller.signal.throwIfAborted();let l=await r(i,c,{accessToken:s.reader.accessToken,authMode:"oauth2",signal:s.controller.signal});if(l.placements.length!==i.length||l.ancestorStates.length!==c.length)throw new Error("[markdown-explorer] isWithin answered a different number of placements or root states than it was asked for");let S=d()+t;for(let[P,R]of l.ancestorStates.entries()){let T=c[P];if(T===void 0)continue;let $=R==="not_a_container"?"not-a-container":R;O(y,h(s.reader,T),{state:$,expiresAt:S}),C(T,$)}for(let[P,R]of i.entries()){let T=l.placements[P];if(T===void 0)continue;let $=I(T,S);O(w,h(s.reader,R),$),L(s,R)?.resolve($)}}catch(l){let S=Oo(l,"unimplemented")?new Error(vo,{cause:l}):l;for(let P of i)L(s,P)?.reject(S)}},N=s=>{D.get(s.reader.id)===s&&D.delete(s.reader.id);for(let i=0;i<s.uris.length;i+=Fr)H(s,s.uris.slice(i,i+Fr))},k=(s,i)=>{let l=h(s,i),S=b.get(l);if(S!==void 0&&!S.batch.controller.signal.aborted)return S;let P=D.get(s.id);if(P===void 0||P.controller.signal.aborted){let $={reader:s,uris:[],controller:new AbortController,waiters:0,answers:new Map};D.set(s.id,$);try{a(()=>N($))}catch(W){throw D.delete(s.id),W}if(D.get(s.id)!==$)throw new TypeError("[markdown-explorer] the host's schedule ran a Drive placement round before returning; it must run the round after the current task");P=$}let R=ie();R.promise.catch(()=>{}),P.uris.push(i),P.answers.set(i,R);let T={batch:P,answer:R.promise};return b.set(l,T),T},m=(s,i)=>{let{batch:l}=s;return l.waiters+=1,new Promise((S,P)=>{let R=!0,T=()=>{R&&(R=!1,l.waiters-=1,l.waiters===0&&l.controller.abort(i.reason),P(i.reason))};if(i.aborted){T();return}i.addEventListener("abort",T,{once:!0}),s.answer.then($=>{R&&(R=!1,i.removeEventListener("abort",T),l.waiters-=1,S($))},$=>{R&&(R=!1,i.removeEventListener("abort",T),l.waiters-=1,P($))})})},g=async(s,i,l,S)=>{M(s),S!==void 0&&A(S);let P=v(w,h(s,i));return P!==void 0&&(P.state!=="within"||S===void 0||P.complete||P.roots.has(S))?P:m(k(s,i),l)};return Object.freeze({roots:c,placementOf:g,placementsOf:async(s,i,l)=>{M(s);let S=[...new Set(i)],P=await Promise.all(S.map(R=>g(s,R,l)));return new Map(S.map((R,T)=>[R,P[T]]))},admit:(s,i,l,S)=>{A(l);for(let P of i){let R=h(s,P),T=v(w,R);if(T?.state==="within"){if(T.roots.has(l))continue;O(w,R,Object.freeze({...T,roots:new Set([...T.roots,l]),expiresAt:T.complete?T.expiresAt:Math.min(T.expiresAt,S)}));continue}O(w,R,Object.freeze({state:"within",roots:new Set([l]),resolvedUri:P,complete:!1,expiresAt:S}))}},expiryOf:(s,i)=>{let l=v(w,h(s,i));return l===void 0?null:l.expiresAt},rootStateOf:async(s,i,l)=>{M(s),A(i);let S=v(y,h(s,i));if(S!==void 0)return S.state;await m(k(s,i),l);let P=v(y,h(s,i));if(P===void 0)throw new Error(`[markdown-explorer] isWithin answered no state for the Drive root ${i}`);return P.state}})};var Ke=e=>new Z("not-found",{code:V.rootUnavailable,cause:e}),Kr=async e=>{try{return await e}catch(r){throw r instanceof Z&&(r.reason==="not-found"||r.reason==="forbidden")?Ke(r):r}},le=e=>e.length===1?e[0]:void 0,Vr=e=>({name:e.uri.slice(Mo.GCS_SCHEME.length),path:e.uri,type:"directory",lazy:!0,children:[]}),Co=new Set([J,ce,de]),qr=e=>Co.has(e),Ao=e=>Object.freeze(e.map(r=>r.replace(/[\\?[\]!]/gu,"\\$&"))),Xr=(e,r,t)=>{let{sources:o,workspaceRoot:a,deny:d}=e,{storage:u,credentials:c,log:w}=r;if(typeof c?.credentialOf!="function"||typeof c.principalKeyOf!="function")throw new TypeError("[markdown-explorer] the sources need the host's credentials (credentialOf and principalKeyOf)");if(typeof r.myDriveLabelOf!="function")throw new TypeError("[markdown-explorer] the sources need the host's My Drive label (myDriveLabelOf)");if(typeof u?.listAncestors!="function"||typeof u.isWithin!="function")throw new TypeError("[markdown-explorer] the sources need the storage client's listAncestors and isWithin");if(typeof r.schedule!="function")throw new TypeError("[markdown-explorer] the sources need the host's schedule (ExplorerHostPorts.schedule)");if(typeof r.now!="function")throw new TypeError("[markdown-explorer] the sources need the host's clock (ExplorerHostPorts.now)");if(typeof w?.warn!="function"||typeof w.info!="function")throw new TypeError("[markdown-explorer] the sources need the host's records (with warn and info functions)");let y=He({storage:u,mapError:t}),b=Ao(d),D=n=>r.myDriveLabelOf(n),_=n=>({id:G(c,n),accessToken:c.credentialOf(n)}),h=(n,p)=>n instanceof Z?n:Do(n,"resource_exhausted")&&!To(n)?new Z("failed",{cause:n}):t(n,p),O=async(n,p)=>{try{return await p()}catch(x){throw h(x,n)}},v=n=>p=>te(n,K(p,d)),M=n=>n.label===null?D:n.label,A=async(n,p,x,s,i)=>{if(!U(s))return null;try{let l=await u.listAncestors(p,x,{accessToken:s,authMode:"oauth2",signal:i});return l.state!=="within"||se(l.resolvedUri)!==p?null:l.containerUris.map(se)}catch(l){return i.aborted||w.warn("[markdown-explorer] could not find the folders above a document, so the tree does not reveal it:",{sourceId:n,documentPath:p,error:l}),null}},C=n=>{let p=n.roots;return Object.freeze({id:n.id,label:M(n),cacheScope:"shared",boundary:Object.freeze({contains:v(n)}),tree:async({signal:x})=>{let s=le(p);return s!==void 0?Kr(y.listWorkspaceTree(oe(a,s),b,x)):Promise.all(p.map(async i=>({name:i,path:i,type:"directory",children:await y.listWorkspaceTree(oe(a,i),b,x)})))},ancestors:async(x,s)=>{let i=K(s,d);if(i.kind!=="workspace")return null;let l=p.find(P=>$e(P,i.relativePath));if(l===void 0||l===i.relativePath)return null;let S=Er(l,i.relativePath);return le(p)===void 0?[l,...S]:S}})},I=n=>{let p=n.roots.map(X),x=n.serviceAccount?"service-account":"reader";return Object.freeze({id:n.id,label:M(n),cacheScope:n.serviceAccount?"shared":"principal",boundary:Object.freeze({contains:v(n)}),tree:async({principal:s,signal:i})=>{let l=c.credentialOf(s),S=le(p);if(S!==void 0)return Kr(y.listCloudDirectory(S.uri,l,x,i));if(x==="reader"&&!U(l))throw new Z("unauthorized");return p.map(Vr)},children:async({principal:s,signal:i},l,S)=>y.listCloudDirectory(S,c.credentialOf(s),x,i),ancestors:async({principal:s,signal:i},l)=>{let S=K(l,d);if(S.kind!=="gcs")return null;let P=p.find(T=>Ie(T,S));if(P===void 0)return null;let R;return x==="reader"?R=await A(n.id,l,P.uri,c.credentialOf(s),i):R=S.uri===S.uriAsRead?Sr(P.uri,S.uri):null,R===null||le(p)!==void 0?R:[Vr(P).path,...R]}})},L=(n,p)=>Object.freeze({id:n.id,label:M(n),cacheScope:"principal",boundary:Object.freeze({contains:v(n)}),tree:async({principal:x,signal:s})=>y.listCloudDirectory(p,c.credentialOf(x),"reader",s),children:async({principal:x,signal:s},i,l)=>y.listCloudDirectory(l,c.credentialOf(x),"reader",s),ancestors:async({principal:x,signal:s},i)=>A(n.id,i,p,c.credentialOf(x),s)}),H=async(n,p,x,s,i,l)=>{let S=await y.listCloudItems(i,x.accessToken,"reader",l),P=S.filter(W=>W.targetUri!==""),R=P.length===0?new Map:await O(i,()=>n.placementsOf(x,P.map(W=>W.uri),l)),T=S.filter(W=>{if(W.targetUri==="")return!0;let ee=R.get(W.uri);return ee?.state==="within"&&ee.roots.has(p)}),$=S.filter(W=>W.targetUri==="").map(W=>W.uri);if(s===p)n.admit(x,$,p,r.now()+Ge);else{let W=n.expiryOf(x,s);W!==null&&n.admit(x,$,p,W)}return Le(T)},N=(n,p,x)=>Object.freeze({id:n.id,label:M(n),cacheScope:"principal",boundary:Object.freeze({contains:v(n),confirm:({principal:s,signal:i},l)=>O(l,async()=>{let S=_(s);if(await x.rootStateOf(S,p,i)!=="usable")throw Ke();let P=await x.placementOf(S,l,i,p);if(P.state==="within")return P.roots.has(p)?{inside:!0,readPath:P.resolvedUri}:{inside:!1};if(P.state==="outside")return{inside:!1};throw new Z("not-found")})}),tree:async({principal:s,signal:i})=>{let l=_(s);if(await O(p,()=>x.rootStateOf(l,p,i))!=="usable")throw Ke();return H(x,p,l,p,p,i)},children:async({principal:s,signal:i},l,S)=>H(x,p,_(s),l,S,i),ancestors:async({principal:s,signal:i},l)=>A(n.id,l,p,c.credentialOf(s),i)}),k=o.flatMap(n=>n.kind==="drive"?n.roots:[]),m=(()=>{let n=k.filter(p=>!qr(p));return n.length===0?null:Gr({roots:n,isWithin:(p,x,s)=>u.isWithin(p,x,s),ttlMs:Ge,maxEntries:Br,schedule:p=>r.schedule(p),now:()=>r.now(),logger:(p,x)=>w.info(p,x)})})(),g=n=>{if(n.kind==="workspace")return C(n);if(n.kind==="gcs")return I(n);let p=le(n.roots);if(p===void 0)throw new Error(`[markdown-explorer] the drive source ${n.id} must have exactly one root`);if(qr(p))return L(n,p);if(m===null)throw new Error(`[markdown-explorer] the drive source ${n.id} has no Drive boundary`);return N(n,p,m)},f=o.map(n=>({setting:n,source:g(n)}));return Object.freeze({sources:Object.freeze(f.map(({source:n})=>n)),editingSources:Object.freeze(f.flatMap(({setting:n,source:p})=>n.edit===null?[]:[Object.freeze({source:p,edit:n.edit})])),hasDriveSource:k.length>0})};var Io=(e,r)=>{if(typeof e!="object"||e===null)throw new TypeError(`[markdown-explorer] the host's setup must be an object; got ${E(e)}`);if(typeof r!="object"||r===null)throw new TypeError(`[markdown-explorer] the host's ports must be an object; got ${E(r)}`);if(typeof e.notices!="object"||e.notices===null)throw new TypeError(`[markdown-explorer] the host's setup needs its notices (with the Drive scope notice); got ${E(e.notices)}`);let{credentials:t,scopes:o}=r;if(typeof t?.credentialOf!="function"||typeof t.principalKeyOf!="function")throw new TypeError("[markdown-explorer] the host needs the credentials' credentialOf and principalKeyOf (ExplorerHostPorts.credentials)");if(typeof o?.missingDriveRead!="function")throw new TypeError("[markdown-explorer] the host needs the scopes' missingDriveRead (ExplorerHostPorts.scopes)");_o(e.deny,"/");let a=Object.freeze([...e.deny]);if(e.legacyTextEncoding!==null&&typeof e.legacyTextEncoding!="string")throw new TypeError(`[markdown-explorer] legacyTextEncoding must be an encoding label or null; got ${E(e.legacyTextEncoding)}`);let d=e.legacyTextEncoding===null?null:$o(e.legacyTextEncoding),u=Object.freeze({...e,deny:a,legacyTextEncoding:d}),c=Ne(r.log),w=Ar(u,r,c),{maxSourceBytes:y,maxHtmlBytes:b}=u.conversion,D=ne(u.sources,u.workspaceRoot),_=fr({sources:u.sources,deny:a,refuseOutsideSharedWorkspace:k=>xe(D,r.log,k)}),{sources:h,editingSources:O,hasDriveSource:v}=Xr(u,r,c),M=_r(O,r.log),A=$r(u,r,{loader:w,router:_,editModeOf:M,mapError:c}),C=ir(u,r,{loader:w,router:_,mapError:c}),{driveScope:I}=u.notices;return Object.freeze({sources:h,document:async(k,m,g)=>{let{principal:f,signal:n,refresh:p}=k,{target:x,lang:s}=_.documentReadOf(m,g);return w.loadMarkdownDoc(x,f,{deniedSegments:a,signal:n,refresh:p,editMode:await M(k,m),legacyTextEncoding:d,lang:s})},asset:C,edit:A,notices:async({principal:k,signal:m})=>{if(!v)return[];if(!U(t.credentialOf(k)))return[];let g=await o.missingDriveRead(k,m);if(g===!0)return[I];if(g==="unknown")return[];if(g===!1)return[];throw new TypeError(`[markdown-explorer] the host's scopes.missingDriveRead must answer true, false or "unknown"; got ${B(g)}`)},deny:a,principalKey:k=>G(t,k),textMaxBytes:y,editMaxBytes:y,sanitizer:Object.freeze({maxHtmlBytes:b})})};var Wo=Object.freeze(["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive"]),ue=Object.freeze({drive:"https://www.googleapis.com/auth/drive",gcs:"https://www.googleapis.com/auth/devstorage.read_write"}),Jr=Object.freeze({drive:Object.freeze([ue.drive]),gcs:Object.freeze([ue.gcs,"https://www.googleapis.com/auth/devstorage.full_control","https://www.googleapis.com/auth/cloud-platform"])}),Yr=(e,r)=>r.some(t=>e.has(t)),Lo=e=>typeof e=="string"&&Object.hasOwn(Jr,e),Ho=e=>{try{return typeof e.has=="function"}catch{return!1}},jo=({grantedScopesOf:e,principalKeyOf:r,log:t})=>{if(typeof e!="function")throw new TypeError("[scope-check] grantedScopesOf must be a function that reads the reader's granted scopes");if(typeof r!="function")throw new TypeError("[scope-check] principalKeyOf must be a function that gives the reader's stable key");if(typeof t?.error!="function")throw new TypeError("[scope-check] log must be the host's records (with an error function)");let o=new WeakSet,a=async(d,u)=>{let c=await e(d,u);if(c===null)return null;if(typeof c=="object"&&Ho(c))return c;throw new TypeError(`[scope-check] grantedScopesOf must answer a set of scopes or null; got ${B(c)}`)};return{missingDriveRead:async(d,u)=>{let c=await a(d,u);if(c===null)return"unknown";let w=!Yr(c,Wo);return w&&!o.has(c)&&(t.error("[scope-check] The reader's credential lacks the Google Drive read scope, so the explorer cannot list or read the reader's Drive (the reader may have left Drive access unchecked when signing in)",{principal:r(d)}),o.add(c)),w},missingWrite:async(d,u,c)=>{if(!Lo(u))throw new RangeError(`[scope-check] the editor writes only "drive" and "gcs" with the reader's account; got ${E(u)}`);let w=await a(d,c);return w===null?"unknown":!Yr(w,Jr[u])}}};var Uo=Object.freeze(["drive","gcs"]),No=e=>{let r=new Set(e.flatMap(t=>t.edit==="save"?[t.kind]:[]));return Object.freeze(Uo.filter(t=>r.has(t)).map(t=>ue[t]))};export{ze as GCS_BUCKET_NAME_RULE,Be as MARKDOWN_EXPLORER_EDIT_MODES,V as MARKDOWN_EXPLORER_FAILURE_CODES,J as MY_DRIVE_ROOT,ce as SHARED_DRIVES_ROOT,de as SHARED_WITH_ME_ROOT,Cr as TEXT_PREVIEW_BYTES,ue as WRITE_SCOPE_REQUESTS,He as createDirectoryTree,Ne as createExplorerErrorMapper,Io as createExplorerHost,jo as createTokenInfoScopePort,No as editConsentScopesOf,Fe as isGcsBucketName,je as parseCacheMaxBytesOf,Ro as parseMarkdownExplorerSources,oe as resolveSharedWorkspaceRoot,ne as sharedWorkspaceRootsOf};
1
+ import{isDeniedPath as _o,legacyTextEncodingOf as $o}from"@aiquants/markdown-explorer/server/core";import{toStorageError as wt}from"@aiquants/storage-api/web";import{decodeText as Qr,decodeTextLeniently as Zr,ExplorerError as et}from"@aiquants/markdown-explorer/server/core";var rt=Object.freeze([".png",".jpg",".jpeg",".gif",".svg",".webp",".ico",".bmp",".tiff",".avif"]),tt="image/svg+xml",ot=Object.freeze([["video",[".mp4",".webm",".mov",".avi",".mkv",".ogv"]],["audio",[".mp3",".wav",".ogg",".m4a",".flac",".aac",".wma"]],["pdf",[".pdf"]]]),nt=new Set(["text/markdown","text/x-markdown","application/vnd.google-apps.document"]),st=Object.freeze([".md",".markdown",".mdx"]),qe=new Set(["","application/octet-stream","binary/octet-stream","text/plain","application/x-empty"]),j=e=>e.replace(/;.*$/su,"").trim().toLowerCase(),Xe=(e,r)=>{if(j(r).startsWith("image/"))return!0;let t=e.toLowerCase();return rt.some(o=>t.endsWith(o))},Ye=(e,r)=>{let t=j(r);return t===tt?"svg":t.startsWith("image/")?"raster":e.toLowerCase().endsWith(".svg")?"svg":"raster"},Je=(e,r)=>{let t=j(r),o=e.toLowerCase();for(let[a,d]of ot)if((a==="pdf"?t==="application/pdf":t.startsWith(`${a}/`))||d.some(c=>o.endsWith(c)))return a;return null},me=(e,r)=>{let t=j(r);if(nt.has(t))return!0;let o=e.toLowerCase();return qe.has(t)&&st.some(a=>o.endsWith(a))},it="application/vnd.google-apps.",Qe="application/vnd.google-apps.folder",at=new Set(["application/json","application/xml","application/yaml","application/x-yaml","application/javascript","application/toml"]),ct=new Set(["","application/octet-stream"]),fe=e=>j(e).startsWith(it),Ze="application/vnd.google-apps.spreadsheet",De="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dt=new Map([["text/csv","csv"],["text/tab-separated-values","tsv"],[De,"workbook"],["application/vnd.ms-excel.sheet.macroenabled.12","workbook"],["application/vnd.oasis.opendocument.spreadsheet","workbook"]]),lt="application/vnd.ms-excel",ut=Object.freeze([[".csv","csv"],[".tsv","tsv"],[".tab","tsv"],[".xlsx","workbook"],[".xlsm","workbook"],[".ods","workbook"]]),pt=Object.freeze({format:"workbook",firstSheetText:"csv"}),mt=e=>qe.has(e)||Te(e)||e===lt,er=(e,r)=>{let t=j(r);if(t===Ze)return pt;let o=dt.get(t);if(o!==void 0)return{format:o,firstSheetText:null};if(!mt(t))return null;let a=e.toLowerCase(),d=ut.find(([u])=>a.endsWith(u));return d===void 0?null:{format:d[1],firstSheetText:null}},Te=e=>{let r=j(e);return r.startsWith("text/")||at.has(r)||r.endsWith("+json")||r.endsWith("+xml")},rr=e=>ct.has(j(e)),tr=(e,r,t)=>{let o=Qr(e,!r,t);return o===null||o.includes("\0")?null:o},or=(e,r,t)=>{let o=Zr(e,!r,t);return o.includes("\0")?null:o},Q=e=>[e.mtimeNs===null?"":e.mtimeNs.toString(),e.mtime===null?"":String(e.mtime.getTime()),String(e.size)].join("."),ft="application/vnd.google-apps.document",gt=Object.freeze({kind:"inline"}),yt=Object.freeze({kind:"draft"}),re=(e,r)=>e===null?null:j(r.mimeType)===ft?sr("document",r):e==="save"&&r.version!==null&&r.canEdit!==!1?gt:yt,nr=(e,r)=>e===null||j(r.mimeType)!==Ze?null:sr("spreadsheets",r),sr=(e,r)=>r.canEdit===!1?null:{kind:"external",href:`https://docs.google.com/${e}/d/${encodeURIComponent(r.id)}/edit`},Me=e=>{let r;try{r=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e)}catch{return null}return r.includes("\0")?null:r},ge=e=>{let r=Me(e);if(r===null)throw new et("unsupported");return r};var ir=(e,r,t)=>{let{storage:o}=r,{loader:a,router:d,mapError:u}=t;if(typeof o?.readStream!="function")throw new TypeError("[markdown-explorer] the asset port needs the storage client's readStream");if(typeof a?.statDocumentTarget!="function")throw new TypeError("[markdown-explorer] the asset port needs the document loader's statDocumentTarget (createDocumentLoader)");if(typeof d?.documentTargetOf!="function")throw new TypeError("[markdown-explorer] the asset port needs the document router's documentTargetOf (createDocumentRouter)");if(typeof u!="function")throw new TypeError("[markdown-explorer] the asset port needs the host's error mapper (createExplorerErrorMapper)");let{deny:c}=e;return async({principal:y,signal:b},D,_,{delivery:h})=>{let{readUri:O,meta:v,name:M,callOptions:A}=await a.statDocumentTarget(d.documentTargetOf(D,_),y,{deniedSegments:c,signal:b,revisions:!1}),C=h==="workbook"?{...A,exportPreference:[De]}:A,I=v.version,L=I===null?C:{...C,ifVersionMatch:I};return{name:M,contentType:v.mimeType,size:fe(v.mimeType)?null:v.size,version:Q(v),open:async H=>{try{return await o.readStream(O,H===null?L:{...L,range:H})}catch(N){throw u(N,O)}},bridge:{uri:O,storageVersion:I,readFailure:H=>u(wt(H,{operation:"readStream",uri:O}),O)}}}};var G=e=>e===""?"an empty string":e===null?"null":typeof e;var K=(e,r)=>{let t=e.principalKeyOf(r);if(typeof t=="string"&&t!=="")return t;throw new TypeError(`[markdown-explorer] the host's principalKeyOf must answer a non-empty string, the reader's stable key; got ${G(t)}`)};var U=e=>typeof e=="string"&&e!=="";import{MarkdownConversionTimeoutError as Vt,MarkdownResourceExhaustedError as qt}from"@aiquants/markdown/service-client";import{decodeTextLeniently as Xt,EXPLORER_MAX_HEADINGS as Yt,ExplorerError as F,isDeniedPath as Jt}from"@aiquants/markdown-explorer/server/core";import{storagePaths as Pe}from"@aiquants/storage-api/web";import{ExplorerError as _t}from"@aiquants/markdown-explorer/server/core";import{storagePaths as $t}from"@aiquants/storage-api/web";var ye=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null};var Et=80,ht="an object that could not be inspected",xt=e=>{let r=0,t=0;for(let o of e){if(r===Et)return JSON.stringify(`${e.slice(0,t)}\u2026`);r+=1,t+=o.length}return JSON.stringify(e)},St=e=>Array.isArray(e)?"an array":ye(e)?"a plain object":`a non-plain object (${Object.prototype.toString.call(e)})`,E=e=>{if(typeof e=="string")return xt(e);if(typeof e=="bigint")return`${String(e)}n`;if(Object.is(e,-0))return"-0";if(typeof e=="function")return"a function";if(typeof e=="object"&&e!==null)try{return St(e)}catch{return ht}return String(e)};import{ExplorerError as mr,MAX_DOCUMENT_PATH_LENGTH as Ct}from"@aiquants/markdown-explorer/server/core";import{storagePaths as We}from"@aiquants/storage-api/web";import{isDeniedPath as Ae}from"@aiquants/markdown-explorer/server/core";import{fromFileUri as kt,isStorageError as ar,storagePaths as Ce,toFileUri as Pt}from"@aiquants/storage-api/web";var we=(e,r,t)=>Ae(e,r)||t!==r&&Ae(e,t),Rt=e=>ar(e,"not_found"),bt=["failed_precondition","invalid_argument","is_a_directory"],cr=({storage:e,log:r,workspaceRoot:t})=>{let o=new Set,a=async(u,c)=>kt(await e.realPath(Pt(u),{authMode:"oauth2",signal:c})),d=async(u,c)=>{try{return await a(u,c)}catch(w){if(!Rt(w))throw w;return o.has(u)||(o.add(u),r.warn(`[markdown-explorer] the shared workspace directory ${u} is missing (not_found); reads treat it as containing nothing while it stays missing`)),null}};return async(u,c,w,y)=>{let b;try{b=await a(u,y)}catch(h){if(!ar(h))throw h;if(h.code==="not_found")return{kind:"missing"};if(h.code==="permission_denied")return{kind:"outside"};let O=bt.find(v=>v===h.code);if(O!==void 0)return{kind:"unfollowable",code:O};throw h}let D=await a(t,y);return(await Promise.all(c.map(h=>h===t?D:d(h,y)))).some(h=>h!==null&&Ce.isInsideDirectory(b,h))&&Ce.isInsideDirectory(b,D)?Ae(w,Ce.relativeToDirectory(b,D))?{kind:"denied"}:{kind:"inside",realPath:b}:{kind:"outside"}}},dr=e=>{switch(e.kind){case"inside":case"missing":return null;case"outside":case"unfollowable":return"not-found";case"denied":return"forbidden"}};import{storagePaths as _e}from"@aiquants/storage-api/web";var Ot="gdrive://shared",vt="gdrive://drives",Dt="gdrive://shared-with-me",Tt=new Set([Ot,vt,Dt]),pr=e=>e.every(r=>r!==""&&r!=="."&&r!==".."),$e=(e,r)=>r.includes("\\")||!pr(r.split("/"))?!1:e==="."||r===e||r.startsWith(`${e}/`),X=e=>{if(typeof e!="string"||!e.startsWith(_e.GCS_SCHEME))throw new RangeError(`a GCS root must be written gcs://<bucket>[/<prefix>]; got ${E(e)}`);let r=e.slice(_e.GCS_SCHEME.length),t=r.indexOf("/"),o=t<0?r:r.slice(0,t);if(o==="")throw new RangeError(`a GCS root must name a bucket after gcs://; got ${E(e)}`);return Object.freeze({uri:e,bucket:o,prefix:t<0?"":r.slice(t+1)})},lr=(e,r)=>{if(r!==""){let t=r.split("/"),o=t.at(-1)===""?t.slice(0,-1):t;if(o.length===0||!pr(o))return!1}return e===""||r===e||r.startsWith(`${e}/`)},ur=e=>{let r=e.slice(_e.GCS_SCHEME.length),t=r.indexOf("/");return t<0?"":r.slice(t+1)},Ie=(e,r)=>r.bucket===e.bucket&&lr(e.prefix,ur(r.uri))&&lr(e.prefix,ur(r.uriAsRead)),Mt=e=>e.kind==="drive"&&!Tt.has(e.uri),te=(e,r)=>{switch(e.kind){case"workspace":return r.kind==="workspace"&&e.roots.some(t=>$e(t,r.relativePath));case"gcs":return r.kind==="gcs"&&e.roots.some(t=>Ie(X(t),r));case"drive":return Mt(r)}};var Ee="gdrive://",At=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u,z=(e,r)=>{if(e.length>Ct)return{kind:"invalid"};let t=We.storagePathAsRead(e);if(we(r,e,t))return{kind:"denied"};if(e.startsWith(Ee))return e.length>Ee.length?{kind:"drive",uri:e,uriAsRead:t}:{kind:"invalid"};if(e.startsWith(We.GCS_SCHEME)){let o=e.slice(We.GCS_SCHEME.length),a=o.indexOf("/"),d=a<0?o:o.slice(0,a);return d===""?{kind:"invalid"}:{kind:"gcs",uri:e,bucket:d,uriAsRead:t}}return At.test(e)?{kind:"invalid"}:{kind:"workspace",relativePath:e}},fr=({sources:e,deny:r,refuseOutsideSharedWorkspace:t})=>{let o=d=>e.some(c=>c.kind==="gcs"&&c.serviceAccount&&te(c,d))?"service-account":"reader",a=(d,u)=>{switch(d.kind){case"workspace":return{kind:"workspace",relativePath:d.relativePath};case"drive":return{kind:"cloud",uri:d.uri,uriAsRead:d.uriAsRead,readUri:u,readAs:"reader"};case"gcs":return{kind:"cloud",uri:d.uri,uriAsRead:d.uriAsRead,readUri:d.uri,readAs:o(d)};case"denied":throw new mr("forbidden");case"invalid":throw new mr("invalid")}};return{documentTargetOf:(d,u)=>a(z(d,r),u),documentReadOf:(d,u)=>{let c=z(d,r),w=a(c,u),y=e.find(b=>te(b,c));if(y!==void 0)return{target:w,lang:y.lang};if(c.kind==="workspace")return t(c.relativePath);throw new Error(`[markdown-explorer] no source contains the admitted document path ${E(d)}`)}}};var he=(e,r,t)=>{let o=e.startsWith($t.GCS_SCHEME);if(!(o||e.startsWith(Ee)))throw new RangeError(`[cloud-read] not a GCS or Google Drive URI: ${E(e)}`);if(t==="service-account"){if(!o)throw new RangeError(`[cloud-read] only GCS is read as the service account; a Google Drive URI is always read with the reader's credential: ${E(e)}`);return{authMode:"service_account"}}if(t!=="reader")throw new RangeError(`[cloud-read] readAs must be "reader" or "service-account"; got ${E(t)}`);if(!U(r))throw new _t("unauthorized");return{accessToken:r,authMode:"oauth2"}};import{ExplorerError as It}from"@aiquants/markdown-explorer/server/core";import{storagePaths as gr}from"@aiquants/storage-api/web";var oe=(e,r)=>({root:gr.resolveWorkspacePath(e,r),directory:r}),ne=(e,r)=>{let t=e.flatMap(o=>o.kind==="workspace"?o.roots:[]);return Object.freeze([...new Set(t)].map(o=>oe(r,o)))},yr=(e,r)=>e.some(t=>gr.isInsideDirectory(r,t.root)),xe=(e,r,t)=>{throw e.length>0&&r.error("[markdown-explorer] refused a workspace document path outside the directories shared with readers:",t),new It("forbidden")};import{buildStorageTree as Wt,toFileUri as Lt}from"@aiquants/storage-api/web";var Ht=3e5,Se=e=>{try{return decodeURIComponent(e)}catch{return e}},wr=(e,r)=>e==="."?r:`${e}/${r}`,Er=(e,r)=>{let t=(e==="."?r:r.slice(e.length+1)).split("/");return t.slice(0,-1).map((o,a)=>wr(e,t.slice(0,a+1).join("/")))},hr=e=>e===null?{}:{modifiedAt:e.getTime()},xr=(e,r)=>e.map(t=>{let o=Se(t.name),a=wr(r,t.relativePath),d=hr(t.mtime);return t.isDir?{name:o,path:a,type:"directory",...d,children:xr(t.children??[],r)}:t.mimeType===""?{name:o,path:a,type:"file",...d}:{name:o,path:a,type:"file",mimeType:t.mimeType,...d}}),se=e=>e,Sr=(e,r)=>{let t=r.slice(e.length+1),o=t.endsWith("/")?t.slice(0,-1):t;if(o==="")return null;let a=o.split("/");return a.slice(0,-1).map((d,u)=>se(`${e}/${a.slice(0,u+1).join("/")}/`))},jt=e=>{let r=Se(e.name),t=se(e.uri),o=hr(e.mtime);return e.isDir?{name:r,path:t,type:"directory",...o,lazy:!0,children:[]}:e.mimeType===""?{name:r,path:t,type:"file",...o}:{name:r,path:t,type:"file",mimeType:e.mimeType,...o}},Le=e=>e.map(jt),He=({storage:e,mapError:r})=>{if(typeof e?.walkDirectory!="function"||typeof e.listDirectory!="function")throw new TypeError("[markdown-explorer] the directory tree needs the storage client's walkDirectory and listDirectory");if(typeof r!="function")throw new TypeError("[markdown-explorer] the directory tree needs the host's error mapper (createExplorerErrorMapper)");let t=async(d,u,c)=>{let w=Lt(d.root);try{let y=await e.walkDirectory(w,{authMode:"oauth2",excludeGlobs:[...u],timeoutMs:Ht,signal:c});return xr(Wt(y),d.directory)}catch(y){throw r(y,w)}},o=async(d,u,c,w)=>{let y=he(d,u,c);try{return await e.listDirectory(d,{...y,signal:w})}catch(b){throw r(b,d)}};return Object.freeze({listWorkspaceTree:t,listCloudItems:o,listCloudDirectory:async(d,u,c,w)=>Le(await o(d,u,c,w))})};var Ut=Object.freeze(["maxSourceBytes","maxHtmlBytes","deadlineMs"]),ke=e=>{if(typeof e!="object"||e===null)throw new TypeError(`[markdown-explorer] the conversion limits must be an object with maxSourceBytes, maxHtmlBytes and deadlineMs; got ${E(e)}`);for(let r of Ut){let t=e[r];if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] conversion.${r} must be a positive safe integer; got ${E(t)}`)}},kr=(e,r,t,o)=>({deniedPathSegments:r,maxHtmlBytes:e.maxHtmlBytes,validateExistence:!0,signal:t,timeoutMs:e.deadlineMs,includeSourceLines:o});import{ExplorerError as Nt}from"@aiquants/markdown-explorer/server/core";var ie=()=>{let e;return{promise:new Promise((t,o)=>{e={resolve:t,reject:o}}),...e}};var br=2,zt=2*br,Ft=50,je=e=>8*e.maxHtmlBytes,Bt=160,Gt=5*6e4,ae=Object.freeze({kind:"too-large"}),Or=Object.freeze({kind:"overdue"}),Pr=e=>e.outcome.kind==="parsed"?e.outcome.bytes:0,Kt=(e,r)=>!e.cloud||r-e.at<Gt,vr=(e,r,t,o,a,d,u)=>JSON.stringify([e,r,Q(t),o,a,d,u]),Dr=(e,r)=>e.headings.reduce((t,o)=>t+Bt+r(o.text)+r(o.id),r(e.htmlContent)),Rr=e=>{let r=new Map;return(t,o)=>new Promise((a,d)=>{if(o.aborted){d(o.reason);return}let u=r.get(t);u===void 0&&(u={taken:0,waiting:new Set},r.set(t,u));let c=u,w=()=>{o.removeEventListener("abort",y),c.taken+=1;let b=!1;a(()=>{if(b)return;b=!0,c.taken-=1;let[D]=c.waiting;D!==void 0?(c.waiting.delete(D),D()):c.taken===0&&r.delete(t)})},y=()=>{c.waiting.delete(w),d(o.reason)};if(c.taken<e){w();return}c.waiting.add(w),o.addEventListener("abort",y,{once:!0})})},Tr=e=>{let r=new Map,t=0,o=new Map,a=h=>{let O=r.get(h);O!==void 0&&(r.delete(h),t-=Pr(O))},d=()=>{for(let h of r.keys()){if(r.size<=Ft&&t<=e.maxBytes)break;a(h)}},u=(h,O,v)=>{a(h);let M={outcome:v,at:e.now(),cloud:O};r.set(h,M),t+=Pr(M),d()},c=(h,O,v,M)=>{o.get(h)===O&&(o.delete(h),M!==null&&u(h,v,M))},w=Rr(br),y=Rr(zt),b=(h,O,v)=>{let M=ie(),A={answer:M.promise,waiters:0,withdrawal:new AbortController};return o.set(h,A),M.promise.catch(()=>{}),v(A.withdrawal.signal).then(C=>{c(h,A,O,C.kind==="overdue"?null:C),M.resolve(C)},C=>{c(h,A,O,null),M.reject(C)}),A},D=async(h,O,v)=>{O.waiters+=1;let M=ie(),A=!0,C=()=>{A=!1,O.waiters-=1,O.waiters===0&&(o.get(h)===O&&o.delete(h),O.withdrawal.abort()),M.reject(v.reason)};v.aborted?C():v.addEventListener("abort",C,{once:!0});try{return await Promise.race([O.answer,M.promise])}finally{v.removeEventListener("abort",C),A&&(O.waiters-=1)}};return Object.freeze({parse:async(h,O,v,M,A)=>{let C=v?void 0:r.get(h),I;if(C!==void 0&&Kt(C,e.now()))r.delete(h),r.set(h,C),I=C.outcome;else{a(h);let L=v?void 0:o.get(h);I=await D(h,L===void 0?b(h,O,A):L,M)}if(I.kind!=="parsed")throw new Nt("too-large");return I},acquireSourceTurn:y,acquireConversionSlot:w})};var Cr=8192,Qt=(e,r)=>e===null?j(r.mimeType)===Qe:r.isDirectory,Mr=(e,r)=>{let t=new Uint8Array(r),o=0;for(let a of e){if(o>=r)break;let d=a.subarray(0,r-o);t.set(d,o),o+=d.byteLength}return t},Zt=(e,r)=>{try{return Pe.resolveWorkspacePath(e,r)}catch(t){if(t instanceof RangeError)return null;throw t}},Ar=(e,r,t)=>{let{workspaceRoot:o}=e,{storage:a,credentials:d,log:u}=r;if(typeof a?.getResource!="function"||typeof a.readStream!="function"||typeof a.realPath!="function")throw new TypeError("[markdown-explorer] the document loader needs the storage client's getResource, readStream and realPath");if(typeof r.markdown?.convert!="function")throw new TypeError("[markdown-explorer] the document loader needs the markdown service's convert (ExplorerHostPorts.markdown)");if(typeof d?.credentialOf!="function"||typeof d.principalKeyOf!="function")throw new TypeError("[markdown-explorer] the document loader needs the host's credentials (credentialOf and principalKeyOf)");if(typeof r.now!="function")throw new TypeError("[markdown-explorer] the document loader needs the host's clock (ExplorerHostPorts.now)");if(typeof r.heldBytesOf!="function")throw new TypeError("[markdown-explorer] the document loader needs the host's string size (ExplorerHostPorts.heldBytesOf)");if(typeof u?.warn!="function"||typeof u.error!="function")throw new TypeError("[markdown-explorer] the document loader needs the host's records (with warn and error functions)");if(typeof t!="function")throw new TypeError("[markdown-explorer] the document loader needs the host's error mapper (createExplorerErrorMapper)");if(typeof o!="string"||!Pe.isAbsolutePath(o))throw new RangeError(`[markdown-explorer] the workspace root must be an absolute URI-space path; got ${E(o)}`);ke(e.conversion);let c=Object.freeze({maxSourceBytes:e.conversion.maxSourceBytes,maxHtmlBytes:e.conversion.maxHtmlBytes,deadlineMs:e.conversion.deadlineMs}),w=je(c),y=Tr({now:()=>r.now(),maxBytes:w}),b=ne(e.sources,o),D=cr({storage:a,log:u,workspaceRoot:o}),_=m=>({id:K(d,m),accessToken:d.credentialOf(m)}),h=async(m,g)=>C(await a.readStream(m,g),Cr),O=async(m,g,f)=>{let{head:n,truncated:p}=await C(await a.readStream(m,g),c.maxSourceBytes);return p?null:{text:Xt(n,!0,f),editable:Me(n)!==null}},v=async(m,g,f,n,p,x)=>{let s;try{s=await r.markdown.convert({markdownText:m,filePath:g,workspaceRoot:o,userOAuthToken:U(f.accessToken)?f.accessToken:void 0},kr(c,n,p,x))}catch(l){if(l instanceof qt)return ae;if(l instanceof Vt)return u.warn(`[markdown-explorer] converting a Markdown document passed its deadline of ${c.deadlineMs} ms; the converter stopped and its readers are answered too-large:`,g),Or;throw l}if(s.headings.length>Yt)return ae;let i=Dr(s,l=>r.heldBytesOf(l));return i>w?ae:{kind:"parsed",result:s,bytes:i}},M=async(m,g,f,n,p,x,s,i)=>{let l=await y.acquireSourceTurn(n.id,m);try{m.throwIfAborted();let S=await O(f,{...p,signal:m},i);if(S===null)return ae;let P=await y.acquireConversionSlot(n.id,m);try{m.throwIfAborted();let R=await v(S.text,g,n,x,m,s);return R.kind==="parsed"?{...R,editable:S.editable}:R}finally{P()}}finally{l()}},A=(m,g,f,n,p,x,s,i)=>y.parse(vr(m,g,f,n.id,s.deniedSegments,i,s.legacyTextEncoding),p,s.refresh,s.signal,async l=>M(l,m,g,n,x,s.deniedSegments,i,s.legacyTextEncoding)),C=async(m,g)=>{let f=m.getReader(),n=[],p=0;for(;p<=g;){let{done:x,value:s}=await f.read();if(x)return{head:Mr(n,p),truncated:!1};n.push(s),p+=s.byteLength}return f.cancel().catch(x=>u.warn("[markdown-explorer] cancelling a stream after reading its head failed",x)),{head:Mr(n,g),truncated:!0}},I=m=>{if(m.kind==="cloud")return{uri:m.uri,readUri:m.readUri,documentPath:m.uri,pathAsRead:m.uriAsRead,workspacePath:null};if(Pe.isAbsolutePath(m.relativePath))throw new F("invalid");let g=Zt(o,m.relativePath);if(g===null||!yr(b,g))return xe(b,u,m.relativePath);let f=Pe.toWorkspaceUri(o,m.relativePath);return{uri:f,readUri:f,documentPath:m.relativePath,pathAsRead:m.relativePath,workspacePath:g}},L=async(m,g,f)=>{let{uri:n,readUri:p,documentPath:x,pathAsRead:s,workspacePath:i}=I(m),l=i===null;if(we(f.deniedSegments,x,s))throw new F("forbidden");if(i!==null){let T=dr(await D(i,b.map($=>$.root),f.deniedSegments,f.signal));if(T!==null)throw u.error("[markdown-explorer] refused a workspace document by the file its symbolic links reach:",{documentPath:x,refusal:T}),new F(T)}let S=m.kind==="cloud"?he(p,g.accessToken,m.readAs):{authMode:"oauth2"},P={...S,signal:f.signal},R;try{R=await a.getResource(p,f.revisions===!0?{...P,revisions:!0}:P)}catch(T){throw t(T,n)}if(Jt(f.deniedSegments,R.name))throw new F("forbidden");if(Qt(i,R))throw new F("unsupported");return{uri:n,readUri:p,documentPath:x,cloud:l,meta:R,name:Se(R.name),sourceOptions:S,callOptions:P}},H=async(m,g,f)=>{let{uri:n,readUri:p,documentPath:x,cloud:s,meta:i,name:l,sourceOptions:S,callOptions:P}=await L(m,g,{deniedSegments:f.deniedSegments,signal:f.signal,revisions:!1});try{let R=Q(i);if(Xe(x,i.mimeType))return{kind:"image",name:l,imageType:Ye(x,i.mimeType),version:R};let T=Je(x,i.mimeType);if(T!==null)return{kind:"media",name:l,mediaType:T,version:R};if(me(l,i.mimeType)){if(i.size>c.maxSourceBytes)throw new F("too-large");let pe=re(f.editMode,i),ve=await A(n,p,i,g,s,S,f,pe?.kind==="inline"||pe?.kind==="draft");return{kind:"markdown",name:l,htmlContent:ve.result.htmlContent,headings:ve.result.headings,lang:f.lang,edit:pe?.kind==="external"||ve.editable?pe:null}}let $=er(l,i.mimeType);if($!==null)return{kind:"spreadsheet",name:l,format:$.format,firstSheetText:$.firstSheetText,edit:nr(f.editMode,i),version:R};if(fe(i.mimeType))return{kind:"file",name:l,version:R};let W=Te(i.mimeType);if(!(W||rr(i.mimeType)))return{kind:"file",name:l,version:R};let{head:ee,truncated:Oe}=await h(p,P),Ve=W?or(ee,Oe,f.legacyTextEncoding):tr(ee,Oe,f.legacyTextEncoding);return Ve===null?{kind:"file",name:l,version:R}:{kind:"text",name:l,version:R,text:Ve,truncated:Oe,lang:f.lang}}catch(R){throw t(R,n)}},N=async(m,g)=>{if(m.meta.size>c.maxSourceBytes)throw new F("too-large");let f=m.callOptions.signal;if(f===void 0)throw new Error("[markdown-explorer] reading a source for the editor needs the request's signal");let n=await y.acquireSourceTurn(g.id,f);try{let{head:p,truncated:x}=await C(await a.readStream(m.readUri,m.callOptions),c.maxSourceBytes);if(x)throw new F("too-large");return ge(p)}catch(p){throw t(p,m.uri)}finally{n()}},k=async(m,g,f,n)=>{let p=m.callOptions.signal;if(p===void 0)throw new Error("[markdown-explorer] previewing a draft needs the request's signal");let x=await y.acquireConversionSlot(g.id,p);try{let s=await v(f,m.uri,g,n,p,!0);if(s.kind!=="parsed")throw new F("too-large");return{htmlContent:s.result.htmlContent,headings:s.result.headings}}finally{x()}};return Object.freeze({loadMarkdownDoc:async(m,g,f)=>H(m,_(g),f),statDocumentTarget:async(m,g,f)=>L(m,_(g),f),readMarkdownSourceForEditing:async(m,g)=>N(m,_(g)),previewMarkdownDraft:async(m,g,f,n)=>k(m,_(g),f,n)})};import{ExplorerError as q}from"@aiquants/markdown-explorer/server/core";import{isStorageError as oo}from"@aiquants/storage-api/web";import{ExplorerError as B}from"@aiquants/markdown-explorer/server/core";import{Code as eo,isStorageError as Y,isStreamLimitRejection as ro}from"@aiquants/storage-api/web";var V=Object.freeze({rootUnavailable:"root-unavailable",driveScopeInsufficient:"drive-scope-insufficient",storageBusy:"storage-busy",storageTimeout:"storage-timeout",documentChanged:"changed"});var to=Object.freeze(["ACCESS_TOKEN_SCOPE_INSUFFICIENT","insufficientPermissions","insufficient authentication scopes"]),Ue=e=>e instanceof Error&&to.some(r=>e.message.includes(r)),Ne=e=>{if(typeof e?.warn!="function")throw new TypeError("[markdown-explorer] the error mapper needs the host's records (with a warn function)");return(r,t)=>t.startsWith("gdrive://")&&Ue(r)?(e.warn(`[markdown-explorer] Google Drive rejected the reader's token for a missing scope: ${t}`),new B("forbidden",{code:V.driveScopeInsufficient,cause:r})):Y(r,"not_found")?new B("not-found",{cause:r}):Y(r,"permission_denied")?new B(r.connectCode===eo.Unauthenticated?"unauthorized":"forbidden",{cause:r}):Y(r,"is_a_directory")?new B("unsupported",{cause:r}):ro(r)?(e.warn(`[markdown-explorer] The storage service refused a stream because the ${r.streamLimit.scope} is at its stream limit: ${t}: ${r.message}`),new B("failed",{code:V.storageBusy,cause:r})):Y(r,"resource_exhausted")?new B("too-large",{cause:r}):Y(r,"deadline_exceeded")?(e.warn(`[markdown-explorer] A storage call ran out of time: ${t}: ${r.message}`),new B("failed",{code:V.storageTimeout,cause:r})):Y(r,"invalid_argument")?new B("invalid",{cause:r}):Y(r,"conflict")?new B("not-found",{code:V.documentChanged,cause:r}):r};var _r=(e,r)=>{if(!Array.isArray(e))throw new TypeError("[markdown-explorer] the edit policy needs the editing sources (createSources' editingSources)");if(typeof r?.warn!="function")throw new TypeError("[markdown-explorer] the edit policy needs the host's records (with a warn function)");return async(o,a)=>{let d=!1;for(let{source:u,edit:c}of e){if(c==="preview"&&d||!u.boundary.contains(a))continue;let{confirm:w}=u.boundary,y=w===void 0;if(!y&&w!==void 0)try{y=(await w(o,a)).inside}catch(b){r.warn(`[MarkdownEdit] the editing source ${u.id} could not confirm a document, which it therefore does not offer for editing:`,b)}if(y){if(c==="save")return"save";d=!0}}return d?"preview":null}},no=e=>new TextEncoder().encode(e).byteLength,so=e=>({id:e.id,modifiedAt:e.mtime===null?null:e.mtime.toISOString(),size:e.size,author:e.author===""?null:e.author,kept:e.keepForever,current:e.isHead}),$r=(e,r,t)=>{let{storage:o,credentials:a,scopes:d,log:u}=r,{loader:c,router:w,editModeOf:y,mapError:b}=t;if(typeof o?.updateFile!="function"||typeof o.listRevisions!="function"||typeof o.readRevision!="function")throw new TypeError("[markdown-explorer] the edit ports need the storage client's updateFile, listRevisions and readRevision");if(typeof a?.principalKeyOf!="function")throw new TypeError("[markdown-explorer] the edit ports need the host's credentials (with a principalKeyOf function)");if(typeof d?.missingWrite!="function")throw new TypeError("[markdown-explorer] the edit ports need the host's scopes (with a missingWrite function)");if(typeof u?.error!="function")throw new TypeError("[markdown-explorer] the edit ports need the host's records (with an error function)");if(typeof r.audit!="function")throw new TypeError("[markdown-explorer] the edit ports need the host's audit (ExplorerHostPorts.audit)");if(typeof c?.statDocumentTarget!="function"||typeof c.readMarkdownSourceForEditing!="function"||typeof c.previewMarkdownDraft!="function")throw new TypeError("[markdown-explorer] the edit ports need the document loader's statDocumentTarget, readMarkdownSourceForEditing and previewMarkdownDraft (createDocumentLoader)");if(typeof w?.documentTargetOf!="function")throw new TypeError("[markdown-explorer] the edit ports need the document router's documentTargetOf (createDocumentRouter)");if(typeof y!="function")throw new TypeError("[markdown-explorer] the edit ports need the edit policy (createEditModeOf)");if(typeof b!="function")throw new TypeError("[markdown-explorer] the edit ports need the host's error mapper (createExplorerErrorMapper)");ke(e.conversion);let{maxSourceBytes:D}=e.conversion,{deny:_}=e,h=Object.freeze({kind:"grant",href:e.grantHref}),O=k=>{let m=z(k,_);return m.kind==="drive"?"drive":m.kind==="gcs"?"gcs":null},v=(k,m,g)=>{let f=w.documentTargetOf(k,m);return f.kind==="cloud"&&g==="save"?{...f,readAs:"reader"}:f},M=async(k,m,g,f)=>{let n=await y(k,m);if(n===null)throw new q("forbidden");let p=await c.statDocumentTarget(v(m,g,n),k.principal,{deniedSegments:_,signal:k.signal,revisions:f});if(!me(p.name,p.meta.mimeType))throw new q("unsupported");return{editMode:n,stated:p}},A=async(k,m)=>{let g=await d.missingWrite(k.principal,m,k.signal);if(g===!0)return!0;if(g==="unknown"||g===!1)return!1;throw new TypeError(`[markdown-explorer] the host's scopes.missingWrite must answer true, false or "unknown"; got ${G(g)}`)},C=async(k,m,g)=>{let{editMode:f,stated:n}=g;if(f!=="save"||n.meta.canEdit===!1)throw new q("forbidden");if(re(f,n.meta)?.kind!=="inline"||n.meta.version===null)throw new q("unsupported");let p=O(m);return p!==null&&await A(k,p)?h:{stated:n,version:n.meta.version,storage:p}},I=async(k,m,g)=>C(k,m,await M(k,m,g,!1)),L=async(k,m,g)=>{let f=await I(k,m,g);if("kind"in f)throw new q("unauthorized");return{text:await c.readMarkdownSourceForEditing(f.stated,k.principal),version:f.version}},H=async(k,m,g)=>{let{editMode:f,stated:n}=await M(k,m,g,!0);if(f!=="save")throw new q("forbidden");if(n.meta.revisions!=="kept")throw new q("unsupported");return n};return Object.freeze({source:async(k,m,g)=>{let f=await M(k,m,g,!0);if(re(f.editMode,f.stated.meta)?.kind==="draft")return{kind:"draft",text:await c.readMarkdownSourceForEditing(f.stated,k.principal)};let n=await C(k,m,f);return"kind"in n?n:{kind:"edit",text:await c.readMarkdownSourceForEditing(n.stated,k.principal),version:n.version,history:n.stated.meta.revisions==="kept"}},save:async(k,m,g,f)=>{let n=await I(k,m,g);if("kind"in n)return n;let{stated:p,storage:x}=n,s={principalKey:K(a,k.principal),path:m,baseVersion:f.baseVersion,bytes:no(f.text)};try{let i=await o.updateFile(p.meta.uri,f.text,{...p.callOptions,ifVersionMatch:f.baseVersion,keepRevision:x==="drive",mimeType:p.meta.mimeType});if(i.version===null)throw new Error(`[markdown-explorer] the storage wrote ${p.meta.uri} but reported no version`);return r.audit({kind:"saved",...s,version:i.version}),{kind:"saved",version:i.version}}catch(i){if(oo(i,"conflict")){let l=await L(k,m,g);return r.audit({kind:"conflict",...s,version:l.version}),{kind:"conflict",version:l.version,text:l.text}}if(Ue(i))return r.audit({kind:"grant-needed",...s,version:null}),h;throw u.error("[MarkdownEdit] save failed",{...s,error:i}),b(i,p.uri)}},preview:async(k,m,g,f)=>{let{stated:n}=await M(k,m,g,!1);return await c.previewMarkdownDraft(n,k.principal,f,_)},revisions:async(k,m,g)=>{let f=await H(k,m,g);try{return(await o.listRevisions(f.meta.uri,f.callOptions)).map(so).reverse()}catch(n){throw b(n,f.uri)}},revision:async(k,m,g,f)=>{let n=await H(k,m,g),p;try{p=await o.readRevision(n.meta.uri,f,n.callOptions)}catch(x){throw b(x,n.uri)}if(p.byteLength>D)throw new q("too-large");return ge(p)}})};import{ExplorerError as Z}from"@aiquants/markdown-explorer/server/core";import{isStorageError as Do,isStreamLimitRejection as To,storagePaths as Mo}from"@aiquants/storage-api/web";import{isDeniedPath as Ur,isExplorerDocumentLang as ao,isExplorerSourceId as co}from"@aiquants/markdown-explorer/server/core";var ze='3 to 222 lowercase letters, digits, "-", "_" or ".", starting and ending with a letter or digit, each dot-separated part 1 to 63 characters',io=/^[a-z0-9][a-z0-9._-]{1,220}[a-z0-9]$/u;var Fe=e=>typeof e=="string"&&io.test(e)&&e.split(".").every(r=>r.length>=1&&r.length<=63);var J="gdrive://id:root",ce="gdrive://shared",de="gdrive://shared-with-me",Be=Object.freeze(["save","preview"]),Re=Object.freeze({min:1,max:16}),Ir=16,Wr=64,lo="ja",Lr=Object.freeze(["id","kind","label","roots","serviceAccount","edit","lang"]),Hr=Object.freeze(["id","kind","roots"]),jr=Object.freeze(["workspace","drive","gcs"]),uo=/^gdrive:\/\/id:[A-Za-z0-9_-]{10,128}$/u,Nr=/\p{Cc}/u,po="id:",mo=e=>{let{setting:r,deny:t,allowWorkspaceSave:o}=e;if(typeof r!="string"||r.trim()==="")throw new TypeError(`[markdown-explorer] the sources setting needs a name for its refusals; got ${E(r)}`);if(typeof o!="boolean")throw new TypeError(`[markdown-explorer] ${r} allowWorkspaceSave must be true or false; got ${E(o)}`);return{refuse:(a,d)=>{throw new Error(`[markdown-explorer] ${r} ${a}; got ${d}`)},deny:t}},fo=(e,r,{refuse:t,deny:o})=>{if(typeof e!="string")return t("workspace roots must be strings",`${r}: ${E(e)}`);if(e.trim()==="")return t("workspace roots must not be blank",`${r}: ${E(e)}`);if(e.startsWith("/"))return t("workspace roots must be relative to the workspace root, not absolute",`${r}: ${E(e)}`);if(e.includes("\\"))return t("workspace roots must not contain a backslash",`${r}: ${E(e)}`);let a=e.split("/").filter(u=>u!==""&&u!==".");if(a.includes(".."))return t("workspace roots must not contain a .. segment",`${r}: ${E(e)}`);let d=a.length===0?".":a.join("/");return Ur(o,d)?t("workspace roots must not be refused by the deny rules",`${r}: ${E(e)}`):d},go=(e,r,{refuse:t,deny:o})=>{if(typeof e!="string")return t("gcs roots must be strings",`${r}: ${E(e)}`);let a;try{a=X(e)}catch{return t("gcs roots must be written gcs://<bucket>[/<prefix>]",`${r}: ${E(e)}`)}if(e.endsWith("/"))return t("gcs roots must be written without a trailing /",`${r}: ${E(e)}`);if(!Fe(a.bucket))return t(`gcs roots must name a Cloud Storage bucket (${ze})`,`${r}: ${E(e)}`);if(a.prefix!==""){let d=a.prefix.split("/");if(d.some(u=>u===""||u==="."||u===".."))return t("gcs root prefixes must not have an empty, . or .. segment",`${r}: ${E(e)}`);if(a.prefix.includes("\\")||a.prefix.includes("%")||Nr.test(a.prefix))return t("gcs root prefixes must not contain a backslash, % or a control character",`${r}: ${E(e)}`);if(d[0]?.startsWith(po))return t('gcs root prefixes must not start with "id:"',`${r}: ${E(e)}`)}return Ur(o,e)?t("gcs roots must not be refused by the deny rules",`${r}: ${E(e)}`):e},yo=(e,r,{refuse:t})=>e===J||e===ce||e===de||typeof e=="string"&&uo.test(e)?e:t(`drive roots must be ${J}, ${ce}, ${de} or gdrive://id:<id> (10 to 128 letters, digits, "_" or "-"); name paths are refused`,`${r}: ${E(e)}`),be=(e,r,t)=>{if(e==="workspace")return r==="."||t===r||t.startsWith(`${r}/`);let o=X(r),a=X(t);return o.bucket===a.bucket&&(o.prefix===""||a.prefix===o.prefix||a.prefix.startsWith(`${o.prefix}/`))},wo=(e,r,t,o)=>{let{refuse:a}=o;if(!Array.isArray(r))return a("roots must be an array",`${t}: ${E(r)}`);if(e==="drive")return r.length!==1?a("a drive source must have exactly one root (configure one source per drive root)",`${t}: ${E(r)}`):Object.freeze([yo(r[0],t,o)]);if(r.length<1||r.length>Ir)return a(`a ${e} source must have 1 to ${Ir} roots`,`${t}: ${E(r)}`);let d=Array.from(r,u=>e==="workspace"?fo(u,t,o):go(u,t,o));if(e==="workspace"&&d.includes(".")&&d.length>1)return a('"." (the whole workspace) must be the only root of its source',`${t}: ${E(r)}`);for(let[u,c]of d.entries())for(let w of d.slice(u+1)){if(c===w)return a("roots of one source must be unique",`${t}: ${E(c)}`);if(be(e,c,w)||be(e,w,c))return a("roots of one source must not nest",`${t}: ${E(c)} and ${E(w)}`)}return Object.freeze(d)},Eo=(e,r,{refuse:t})=>{if(typeof e!="string")return t("label must be a string",`${r}: ${E(e)}`);let o=e.trim();return o===""?t("label must not be blank",`${r}: ${E(e)}`):[...o].length>Wr?t(`label must be at most ${Wr} characters`,`${r}: ${E(e)}`):Nr.test(e)?t("label must not contain a control character",`${r}: ${E(e)}`):o},ho=(e,r,t,{refuse:o})=>{if(!Object.hasOwn(e,"serviceAccount"))return!1;if(r!=="gcs")return o("serviceAccount may be set only on a gcs source (Drive and the workspace are never read as the service account)",t);let{serviceAccount:a}=e;return typeof a!="boolean"?o("serviceAccount must be true or false",`${t}: ${E(a)}`):a},xo=(e,r,t,{refuse:o})=>{if(!Object.hasOwn(e,"edit"))return null;let{edit:a}=e,d=Be.find(u=>u===a);return d===void 0?o(`edit must be ${Be.map(u=>E(u)).join(" or ")}`,`${t}: ${E(a)}`):d==="save"&&r?o(`edit must not be "save" on a source read as the service account (a save writes with the reader's own account)`,t):d},So=(e,r,{refuse:t})=>{if(!Object.hasOwn(e,"lang"))return lo;let{lang:o}=e;return ao(o)?o:t('lang must be a canonical BCP 47 language tag (such as "ja" or "en-US")',`${r}: ${E(o)}`)},ko=(e,r,t)=>{let{refuse:o}=t,a=`element ${r}`;if(!ye(e))return o("elements must be objects",`${a}: ${E(e)}`);let d=Object.keys(e).find(v=>!Lr.includes(v));if(d!==void 0)return o(`elements may have only the keys ${Lr.join(", ")} (unknown key ${E(d)})`,a);let u=Hr.find(v=>!Object.hasOwn(e,v));if(u!==void 0)return o(`elements must have the keys ${Hr.join(", ")} (missing ${E(u)})`,a);let{id:c,kind:w}=e;if(!co(c))return o('id must use lowercase letters, digits and "-" and start with a letter or digit',`${a}: ${E(c)}`);let y=jr.find(v=>v===w);if(y===void 0)return o(`kind must be one of ${jr.join(", ")}`,`${a}: ${E(w)}`);let b=wo(y,e.roots,a,t),D=ho(e,y,a,t),_=xo(e,D,a,t),h=So(e,a,t),O=y==="drive"&&b[0]===J;return Object.hasOwn(e,"label")?Object.freeze({id:c,kind:y,label:Eo(e.label,a,t),roots:b,serviceAccount:D,edit:_,lang:h}):O?Object.freeze({id:c,kind:y,label:null,roots:b,serviceAccount:D,edit:_,lang:h}):o(`label is required except for a drive source rooted at ${J}`,a)},Po=(e,r)=>{if(e.kind!==r.kind)return!1;let{kind:t}=e;return t==="drive"?!0:e.roots.some(o=>r.roots.some(a=>be(t,o,a)||be(t,a,o)))},Ro=(e,r)=>{let t=mo(r),{refuse:o}=t;if(!Array.isArray(e)||e.length<Re.min||e.length>Re.max)return o(`must be an array of ${Re.min} to ${Re.max} sources`,E(e));let a=Array.from(e,(w,y)=>ko(w,y,t)),d=new Set,u=new Set,c=new Set;for(let[w,y]of a.entries()){d.has(y.id)&&o("ids must be unique",`element ${w}: ${E(y.id)}`),d.add(y.id),y.label!==null&&(u.has(y.label)&&o("labels must be unique after trimming",`element ${w}: ${E(y.label)}`),u.add(y.label));for(let b of y.roots){let D=`${y.kind}\0${b}`;c.has(D)&&o(`the same ${y.kind} root must not appear in two sources`,`element ${w}: ${E(b)}`),c.add(D)}for(let[b,D]of a.slice(0,w).entries())D.lang!==y.lang&&Po(D,y)&&o("sources that can show the same document must have the same lang (any two drive sources, and two workspace or two gcs sources whose roots nest)",`element ${w}: ${E(y.lang)} (element ${b}: ${E(D.lang)})`)}if(!r.allowWorkspaceSave){let w=a.findIndex(y=>y.kind==="workspace"&&y.edit==="save");w>=0&&o('must not let readers save a workspace source ("edit": "save"; the host does not allow saving its workspace)',`element ${w}`)}return Object.freeze(a)};import{ExplorerError as bo}from"@aiquants/markdown-explorer/server/core";import{isStorageError as Oo,MAX_PLACEMENT_ANCESTORS as zr,MAX_PLACEMENT_URIS as Fr}from"@aiquants/storage-api/web";var Ge=3e4,Br=1e4,vo="[markdown-explorer] the storage-api binary does not answer IsWithin; rebuild it",Gr=e=>{let{isWithin:r,ttlMs:t,maxEntries:o,schedule:a,now:d,logger:u}=e,c=Object.freeze([...e.roots]);if(c.length===0||c.length>zr||new Set(c).size!==c.length)throw new RangeError(`[markdown-explorer] a Drive boundary needs 1 to ${zr} unique roots; got ${String(c.length)} roots, ${String(new Set(c).size)} unique`);if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] the Drive placement TTL must be a positive integer; got ${E(t)}`);if(!Number.isSafeInteger(o)||o<=0)throw new RangeError(`[markdown-explorer] the Drive placement entry limit must be a positive integer; got ${E(o)}`);if(typeof r!="function")throw new TypeError("[markdown-explorer] a Drive boundary needs the storage client's isWithin");if(typeof a!="function")throw new TypeError("[markdown-explorer] a Drive boundary needs the host's schedule (ExplorerHostPorts.schedule)");if(typeof d!="function")throw new TypeError("[markdown-explorer] a Drive boundary needs the host's clock (ExplorerHostPorts.now)");if(typeof u!="function")throw new TypeError("[markdown-explorer] a Drive boundary needs a logger for its root states");let w=new Map,y=new Map,b=new Map,D=new Map,_=new Set,h=(s,i)=>`${s.id}\0${i}`,O=(s,i,l)=>{s.delete(i),s.set(i,l);for(let S of s.keys()){if(s.size<=o)break;s.delete(S)}},v=(s,i)=>{let l=s.get(i);if(l!==void 0){if(l.expiresAt>d())return l;s.delete(i)}},M=s=>{if(!U(s.accessToken))throw new bo("unauthorized")},A=s=>{if(!c.includes(s))throw new RangeError(`[markdown-explorer] ${E(s)} is not a configured Drive root`)},C=(s,i)=>{let l=`${s}\0${i}`;_.has(l)||(_.add(l),u(`[markdown-explorer] the Drive source root ${s} is ${i} for a reader`,{root:s,state:i}))},I=(s,i)=>{switch(s.state){case"within":return Object.freeze({state:"within",roots:new Set(s.ancestorIndexes.flatMap(l=>c.slice(l,l+1))),resolvedUri:s.resolvedUri,complete:!0,expiresAt:i});case"outside":return Object.freeze({state:"outside",expiresAt:i});case"not_found":return Object.freeze({state:"not-found",expiresAt:i});case"trashed":return Object.freeze({state:"trashed",expiresAt:i})}},L=(s,i)=>{let l=h(s.reader,i);return b.get(l)?.batch===s&&b.delete(l),s.answers.get(i)},H=async(s,i)=>{try{s.controller.signal.throwIfAborted();let l=await r(i,c,{accessToken:s.reader.accessToken,authMode:"oauth2",signal:s.controller.signal});if(l.placements.length!==i.length||l.ancestorStates.length!==c.length)throw new Error("[markdown-explorer] isWithin answered a different number of placements or root states than it was asked for");let S=d()+t;for(let[P,R]of l.ancestorStates.entries()){let T=c[P];if(T===void 0)continue;let $=R==="not_a_container"?"not-a-container":R;O(y,h(s.reader,T),{state:$,expiresAt:S}),C(T,$)}for(let[P,R]of i.entries()){let T=l.placements[P];if(T===void 0)continue;let $=I(T,S);O(w,h(s.reader,R),$),L(s,R)?.resolve($)}}catch(l){let S=Oo(l,"unimplemented")?new Error(vo,{cause:l}):l;for(let P of i)L(s,P)?.reject(S)}},N=s=>{D.get(s.reader.id)===s&&D.delete(s.reader.id);for(let i=0;i<s.uris.length;i+=Fr)H(s,s.uris.slice(i,i+Fr))},k=(s,i)=>{let l=h(s,i),S=b.get(l);if(S!==void 0&&!S.batch.controller.signal.aborted)return S;let P=D.get(s.id);if(P===void 0||P.controller.signal.aborted){let $={reader:s,uris:[],controller:new AbortController,waiters:0,answers:new Map};D.set(s.id,$);try{a(()=>N($))}catch(W){throw D.delete(s.id),W}if(D.get(s.id)!==$)throw new TypeError("[markdown-explorer] the host's schedule ran a Drive placement round before returning; it must run the round after the current task");P=$}let R=ie();R.promise.catch(()=>{}),P.uris.push(i),P.answers.set(i,R);let T={batch:P,answer:R.promise};return b.set(l,T),T},m=(s,i)=>{let{batch:l}=s;return l.waiters+=1,new Promise((S,P)=>{let R=!0,T=()=>{R&&(R=!1,l.waiters-=1,l.waiters===0&&l.controller.abort(i.reason),P(i.reason))};if(i.aborted){T();return}i.addEventListener("abort",T,{once:!0}),s.answer.then($=>{R&&(R=!1,i.removeEventListener("abort",T),l.waiters-=1,S($))},$=>{R&&(R=!1,i.removeEventListener("abort",T),l.waiters-=1,P($))})})},g=async(s,i,l,S)=>{M(s),S!==void 0&&A(S);let P=v(w,h(s,i));return P!==void 0&&(P.state!=="within"||S===void 0||P.complete||P.roots.has(S))?P:m(k(s,i),l)};return Object.freeze({roots:c,placementOf:g,placementsOf:async(s,i,l)=>{M(s);let S=[...new Set(i)],P=await Promise.all(S.map(R=>g(s,R,l)));return new Map(S.map((R,T)=>[R,P[T]]))},admit:(s,i,l,S)=>{A(l);for(let P of i){let R=h(s,P),T=v(w,R);if(T?.state==="within"){if(T.roots.has(l))continue;O(w,R,Object.freeze({...T,roots:new Set([...T.roots,l]),expiresAt:T.complete?T.expiresAt:Math.min(T.expiresAt,S)}));continue}O(w,R,Object.freeze({state:"within",roots:new Set([l]),resolvedUri:P,complete:!1,expiresAt:S}))}},expiryOf:(s,i)=>{let l=v(w,h(s,i));return l===void 0?null:l.expiresAt},rootStateOf:async(s,i,l)=>{M(s),A(i);let S=v(y,h(s,i));if(S!==void 0)return S.state;await m(k(s,i),l);let P=v(y,h(s,i));if(P===void 0)throw new Error(`[markdown-explorer] isWithin answered no state for the Drive root ${i}`);return P.state}})};var Ke=e=>new Z("not-found",{code:V.rootUnavailable,cause:e}),Kr=async e=>{try{return await e}catch(r){throw r instanceof Z&&(r.reason==="not-found"||r.reason==="forbidden")?Ke(r):r}},le=e=>e.length===1?e[0]:void 0,Vr=e=>({name:e.uri.slice(Mo.GCS_SCHEME.length),path:e.uri,type:"directory",lazy:!0,children:[]}),Co=new Set([J,ce,de]),qr=e=>Co.has(e),Ao=e=>Object.freeze(e.map(r=>r.replace(/[\\?[\]!]/gu,"\\$&"))),Xr=(e,r,t)=>{let{sources:o,workspaceRoot:a,deny:d}=e,{storage:u,credentials:c,log:w}=r;if(typeof c?.credentialOf!="function"||typeof c.principalKeyOf!="function")throw new TypeError("[markdown-explorer] the sources need the host's credentials (credentialOf and principalKeyOf)");if(typeof r.myDriveLabelOf!="function")throw new TypeError("[markdown-explorer] the sources need the host's My Drive label (myDriveLabelOf)");if(typeof u?.listAncestors!="function"||typeof u.isWithin!="function")throw new TypeError("[markdown-explorer] the sources need the storage client's listAncestors and isWithin");if(typeof r.schedule!="function")throw new TypeError("[markdown-explorer] the sources need the host's schedule (ExplorerHostPorts.schedule)");if(typeof r.now!="function")throw new TypeError("[markdown-explorer] the sources need the host's clock (ExplorerHostPorts.now)");if(typeof w?.warn!="function"||typeof w.info!="function")throw new TypeError("[markdown-explorer] the sources need the host's records (with warn and info functions)");let y=He({storage:u,mapError:t}),b=Ao(d),D=n=>r.myDriveLabelOf(n),_=n=>({id:K(c,n),accessToken:c.credentialOf(n)}),h=(n,p)=>n instanceof Z?n:Do(n,"resource_exhausted")&&!To(n)?new Z("failed",{cause:n}):t(n,p),O=async(n,p)=>{try{return await p()}catch(x){throw h(x,n)}},v=n=>p=>te(n,z(p,d)),M=n=>n.label===null?D:n.label,A=async(n,p,x,s,i)=>{if(!U(s))return null;try{let l=await u.listAncestors(p,x,{accessToken:s,authMode:"oauth2",signal:i});return l.state!=="within"||se(l.resolvedUri)!==p?null:l.containerUris.map(se)}catch(l){return i.aborted||w.warn("[markdown-explorer] could not find the folders above a document, so the tree does not reveal it:",{sourceId:n,documentPath:p,error:l}),null}},C=n=>{let p=n.roots;return Object.freeze({id:n.id,label:M(n),cacheScope:"shared",boundary:Object.freeze({contains:v(n)}),tree:async({signal:x})=>{let s=le(p);return s!==void 0?Kr(y.listWorkspaceTree(oe(a,s),b,x)):Promise.all(p.map(async i=>({name:i,path:i,type:"directory",children:await y.listWorkspaceTree(oe(a,i),b,x)})))},ancestors:async(x,s)=>{let i=z(s,d);if(i.kind!=="workspace")return null;let l=p.find(P=>$e(P,i.relativePath));if(l===void 0||l===i.relativePath)return null;let S=Er(l,i.relativePath);return le(p)===void 0?[l,...S]:S}})},I=n=>{let p=n.roots.map(X),x=n.serviceAccount?"service-account":"reader";return Object.freeze({id:n.id,label:M(n),cacheScope:n.serviceAccount?"shared":"principal",boundary:Object.freeze({contains:v(n)}),tree:async({principal:s,signal:i})=>{let l=c.credentialOf(s),S=le(p);if(S!==void 0)return Kr(y.listCloudDirectory(S.uri,l,x,i));if(x==="reader"&&!U(l))throw new Z("unauthorized");return p.map(Vr)},children:async({principal:s,signal:i},l,S)=>y.listCloudDirectory(S,c.credentialOf(s),x,i),ancestors:async({principal:s,signal:i},l)=>{let S=z(l,d);if(S.kind!=="gcs")return null;let P=p.find(T=>Ie(T,S));if(P===void 0)return null;let R;return x==="reader"?R=await A(n.id,l,P.uri,c.credentialOf(s),i):R=S.uri===S.uriAsRead?Sr(P.uri,S.uri):null,R===null||le(p)!==void 0?R:[Vr(P).path,...R]}})},L=(n,p)=>Object.freeze({id:n.id,label:M(n),cacheScope:"principal",boundary:Object.freeze({contains:v(n)}),tree:async({principal:x,signal:s})=>y.listCloudDirectory(p,c.credentialOf(x),"reader",s),children:async({principal:x,signal:s},i,l)=>y.listCloudDirectory(l,c.credentialOf(x),"reader",s),ancestors:async({principal:x,signal:s},i)=>A(n.id,i,p,c.credentialOf(x),s)}),H=async(n,p,x,s,i,l)=>{let S=await y.listCloudItems(i,x.accessToken,"reader",l),P=S.filter(W=>W.targetUri!==""),R=P.length===0?new Map:await O(i,()=>n.placementsOf(x,P.map(W=>W.uri),l)),T=S.filter(W=>{if(W.targetUri==="")return!0;let ee=R.get(W.uri);return ee?.state==="within"&&ee.roots.has(p)}),$=S.filter(W=>W.targetUri==="").map(W=>W.uri);if(s===p)n.admit(x,$,p,r.now()+Ge);else{let W=n.expiryOf(x,s);W!==null&&n.admit(x,$,p,W)}return Le(T)},N=(n,p,x)=>Object.freeze({id:n.id,label:M(n),cacheScope:"principal",boundary:Object.freeze({contains:v(n),confirm:({principal:s,signal:i},l)=>O(l,async()=>{let S=_(s);if(await x.rootStateOf(S,p,i)!=="usable")throw Ke();let P=await x.placementOf(S,l,i,p);if(P.state==="within")return P.roots.has(p)?{inside:!0,readPath:P.resolvedUri}:{inside:!1};if(P.state==="outside")return{inside:!1};throw new Z("not-found")})}),tree:async({principal:s,signal:i})=>{let l=_(s);if(await O(p,()=>x.rootStateOf(l,p,i))!=="usable")throw Ke();return H(x,p,l,p,p,i)},children:async({principal:s,signal:i},l,S)=>H(x,p,_(s),l,S,i),ancestors:async({principal:s,signal:i},l)=>A(n.id,l,p,c.credentialOf(s),i)}),k=o.flatMap(n=>n.kind==="drive"?n.roots:[]),m=(()=>{let n=k.filter(p=>!qr(p));return n.length===0?null:Gr({roots:n,isWithin:(p,x,s)=>u.isWithin(p,x,s),ttlMs:Ge,maxEntries:Br,schedule:p=>r.schedule(p),now:()=>r.now(),logger:(p,x)=>w.info(p,x)})})(),g=n=>{if(n.kind==="workspace")return C(n);if(n.kind==="gcs")return I(n);let p=le(n.roots);if(p===void 0)throw new Error(`[markdown-explorer] the drive source ${n.id} must have exactly one root`);if(qr(p))return L(n,p);if(m===null)throw new Error(`[markdown-explorer] the drive source ${n.id} has no Drive boundary`);return N(n,p,m)},f=o.map(n=>({setting:n,source:g(n)}));return Object.freeze({sources:Object.freeze(f.map(({source:n})=>n)),editingSources:Object.freeze(f.flatMap(({setting:n,source:p})=>n.edit===null?[]:[Object.freeze({source:p,edit:n.edit})])),hasDriveSource:k.length>0})};var Io=(e,r)=>{if(typeof e!="object"||e===null)throw new TypeError(`[markdown-explorer] the host's setup must be an object; got ${E(e)}`);if(typeof r!="object"||r===null)throw new TypeError(`[markdown-explorer] the host's ports must be an object; got ${E(r)}`);if(typeof e.notices!="object"||e.notices===null)throw new TypeError(`[markdown-explorer] the host's setup needs its notices (with the Drive scope notice); got ${E(e.notices)}`);let{credentials:t,scopes:o}=r;if(typeof t?.credentialOf!="function"||typeof t.principalKeyOf!="function")throw new TypeError("[markdown-explorer] the host needs the credentials' credentialOf and principalKeyOf (ExplorerHostPorts.credentials)");if(typeof o?.missingDriveRead!="function")throw new TypeError("[markdown-explorer] the host needs the scopes' missingDriveRead (ExplorerHostPorts.scopes)");_o(e.deny,"/");let a=Object.freeze([...e.deny]);if(e.legacyTextEncoding!==null&&typeof e.legacyTextEncoding!="string")throw new TypeError(`[markdown-explorer] legacyTextEncoding must be an encoding label or null; got ${E(e.legacyTextEncoding)}`);let d=e.legacyTextEncoding===null?null:$o(e.legacyTextEncoding),u=Object.freeze({...e,deny:a,legacyTextEncoding:d}),c=Ne(r.log),w=Ar(u,r,c),{maxSourceBytes:y,maxHtmlBytes:b}=u.conversion,D=ne(u.sources,u.workspaceRoot),_=fr({sources:u.sources,deny:a,refuseOutsideSharedWorkspace:k=>xe(D,r.log,k)}),{sources:h,editingSources:O,hasDriveSource:v}=Xr(u,r,c),M=_r(O,r.log),A=$r(u,r,{loader:w,router:_,editModeOf:M,mapError:c}),C=ir(u,r,{loader:w,router:_,mapError:c}),{driveScope:I}=u.notices;return Object.freeze({sources:h,document:async(k,m,g)=>{let{principal:f,signal:n,refresh:p}=k,{target:x,lang:s}=_.documentReadOf(m,g);return w.loadMarkdownDoc(x,f,{deniedSegments:a,signal:n,refresh:p,editMode:await M(k,m),legacyTextEncoding:d,lang:s})},asset:C,edit:A,notices:async({principal:k,signal:m})=>{if(!v)return[];if(!U(t.credentialOf(k)))return[];let g=await o.missingDriveRead(k,m);if(g===!0)return[I];if(g==="unknown")return[];if(g===!1)return[];throw new TypeError(`[markdown-explorer] the host's scopes.missingDriveRead must answer true, false or "unknown"; got ${G(g)}`)},deny:a,principalKey:k=>K(t,k),textMaxBytes:y,editMaxBytes:y,sanitizer:Object.freeze({maxHtmlBytes:b})})};var Wo=Object.freeze(["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive"]),ue=Object.freeze({drive:"https://www.googleapis.com/auth/drive",gcs:"https://www.googleapis.com/auth/devstorage.read_write"}),Jr=Object.freeze({drive:Object.freeze([ue.drive]),gcs:Object.freeze([ue.gcs,"https://www.googleapis.com/auth/devstorage.full_control","https://www.googleapis.com/auth/cloud-platform"])}),Yr=(e,r)=>r.some(t=>e.has(t)),Lo=e=>typeof e=="string"&&Object.hasOwn(Jr,e),Ho=e=>{try{return typeof e.has=="function"}catch{return!1}},jo=({grantedScopesOf:e,principalKeyOf:r,log:t})=>{if(typeof e!="function")throw new TypeError("[scope-check] grantedScopesOf must be a function that reads the reader's granted scopes");if(typeof r!="function")throw new TypeError("[scope-check] principalKeyOf must be a function that gives the reader's stable key");if(typeof t?.error!="function")throw new TypeError("[scope-check] log must be the host's records (with an error function)");let o=new WeakSet,a=async(d,u)=>{let c=await e(d,u);if(c===null)return null;if(typeof c=="object"&&Ho(c))return c;throw new TypeError(`[scope-check] grantedScopesOf must answer a set of scopes or null; got ${G(c)}`)};return{missingDriveRead:async(d,u)=>{let c=await a(d,u);if(c===null)return"unknown";let w=!Yr(c,Wo);return w&&!o.has(c)&&(t.error("[scope-check] The reader's credential lacks the Google Drive read scope, so the explorer cannot list or read the reader's Drive (the reader may have left Drive access unchecked when signing in)",{principal:r(d)}),o.add(c)),w},missingWrite:async(d,u,c)=>{if(!Lo(u))throw new RangeError(`[scope-check] the editor writes only "drive" and "gcs" with the reader's account; got ${E(u)}`);let w=await a(d,c);return w===null?"unknown":!Yr(w,Jr[u])}}};var Uo=Object.freeze(["drive","gcs"]),No=e=>{let r=new Set(e.flatMap(t=>t.edit==="save"?[t.kind]:[]));return Object.freeze(Uo.filter(t=>r.has(t)).map(t=>ue[t]))};export{ze as GCS_BUCKET_NAME_RULE,Be as MARKDOWN_EXPLORER_EDIT_MODES,V as MARKDOWN_EXPLORER_FAILURE_CODES,J as MY_DRIVE_ROOT,ce as SHARED_DRIVES_ROOT,de as SHARED_WITH_ME_ROOT,Cr as TEXT_PREVIEW_BYTES,ue as WRITE_SCOPE_REQUESTS,He as createDirectoryTree,Ne as createExplorerErrorMapper,Io as createExplorerHost,jo as createTokenInfoScopePort,No as editConsentScopesOf,Fe as isGcsBucketName,je as parseCacheMaxBytesOf,Ro as parseMarkdownExplorerSources,oe as resolveSharedWorkspaceRoot,z as routeDocumentPath,ne as sharedWorkspaceRootsOf};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiquants/markdown-explorer-host",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "The host half of @aiquants/markdown-explorer's server shared by every host: the sources setting, the source ports, the Drive boundary, document reading with its parse cache, editing and grants, assets and the failure mapping, reaching storage, conversion, credentials, scopes and records only through injected ports, so the same host runs in Node and in a page.",
5
5
  "sideEffects": false,
6
6
  "type": "module",
@@ -41,14 +41,20 @@
41
41
  },
42
42
  "license": "MIT",
43
43
  "peerDependencies": {
44
- "@aiquants/markdown": "^13.0.0",
45
- "@aiquants/markdown-explorer": "^0.35.0",
44
+ "@aiquants/markdown": "^13.3.0",
45
+ "@aiquants/markdown-explorer": "^0.39.0",
46
46
  "@aiquants/storage-api": "^0.15.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@aiquants/markdown": "13.0.0",
50
- "@aiquants/markdown-explorer": "0.35.0",
51
- "@aiquants/storage-api": "0.15.0",
49
+ "@aiquants/auth-core": "0.9.0",
50
+ "@aiquants/directory-tree": "6.1.3",
51
+ "@aiquants/drag-drop-panels": "0.14.1",
52
+ "@aiquants/markdown": "13.3.0",
53
+ "@aiquants/markdown-explorer": "0.39.0",
54
+ "@aiquants/resize-panels": "2.3.0",
55
+ "@aiquants/spreadsheet": "0.20.1",
56
+ "@aiquants/storage-api": "0.15.1",
57
+ "@aiquants/virtualscroll": "3.27.0",
52
58
  "@types/node": "^25.9.1",
53
59
  "@vitest/coverage-v8": "^4.1.10",
54
60
  "rimraf": "^6.1.2",