@aiquants/enrichment-core 0.7.0 → 0.8.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 +6 -7
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -20
- package/dist/index.d.ts +2 -20
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var H=e=>{if(e===null||typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new RangeError(`A canonical JSON number is finite: ${e}`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(H).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${H(t[r])}`).join(",")}}`};import{z as tr}from"zod";var Ke={embedded_image:"\u57CB\u3081\u8FBC\u307F\u753B\u50CF",embedded_chart:"\u57CB\u3081\u8FBC\u307F\u306E\u56F3\u8868",embedded_table:"\u57CB\u3081\u8FBC\u307F\u306E\u8868",attachment:"\u6DFB\u4ED8",archive_member:"\u66F8\u5EAB\u306E\u4E2D\u8EAB",keyframe:"\u5834\u9762\u306E\u753B\u50CF",audio_track:"\u97F3\u58F0",transcript_segment:"\u66F8\u304D\u8D77\u3053\u3057"};var Ce=/^[a-z_]+-(0|[1-9][0-9]*)(\/[a-z_]+-(0|[1-9][0-9]*))*$/,_e=tr.string().regex(Ce,"A tree path joins <asset_type>-<asset_index> segments with '/' from the root down."),oe=e=>{if(!Ce.test(e))throw new RangeError(`not a tree path: ${JSON.stringify(e)}`);return e.split("/").map(t=>{let n=t.lastIndexOf("-");return{kind:t.slice(0,n),digits:t.slice(n+1)}})},fi=e=>oe(e).map(({kind:t,digits:n})=>({assetType:t,assetIndex:Number(n)})),hi=e=>oe(e).length,xt=(e,t)=>e<t?-1:e>t?1:0,At=(e,t)=>{let n=oe(e),r=oe(t);for(let o=0;o<Math.min(n.length,r.length);o+=1){let i=n[o],s=r[o],l=xt(i.kind,s.kind)||i.digits.length-s.digits.length||xt(i.digits,s.digits);if(l!==0)return l}return n.length-r.length},nr=e=>{if(!Object.hasOwn(Ke,e))throw new RangeError(`no name for the asset type ${JSON.stringify(e)}`);return Ke[e]},yi=e=>oe(e).map(({kind:t,digits:n})=>`${nr(t)} ${n}`).join(" > "),ae=e=>e.parentPath===void 0?`${e.assetType}-${e.assetIndex}`:`${e.parentPath}/${e.assetType}-${e.assetIndex}`,gi=e=>oe(e).length===1?null:e.slice(0,e.lastIndexOf("/"));import{z as Q}from"zod";import{z as Ge}from"zod";var ie=Ge.string().uuid().transform(e=>e.toLowerCase()),N=Ge.string().datetime({offset:!0}),Ie=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!Object.hasOwn(e,"__proto__"),d=(e,t,n)=>{e.addIssue({code:Ge.ZodIssueCode.custom,path:[...t],message:n})},rr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:Z|([+-])(\d{2}):?(\d{2}))$/,Re=e=>{let t=N.safeParse(e).success?rr.exec(e):null;if(t===null)return null;let[,n,r,o,i,s,l,c,h,u,y]=t,E=new Date(0);E.setUTCFullYear(Number(n),Number(r)-1,Number(o)),E.setUTCHours(Number(i),Number(s),l===void 0?0:Number(l),0);let A=h===void 0?0:(h==="+"?1:-1)*(Number(u)*3600+Number(y)*60);return{epochSeconds:E.getTime()/1e3-A,fraction:c===void 0?"":c}},$=(e,t)=>{let n=Re(e),r=Re(t);if(n===null||r===null)return!1;if(n.epochSeconds!==r.epochSeconds)return n.epochSeconds<r.epochSeconds;let o=Math.max(n.fraction.length,r.fraction.length);return n.fraction.padEnd(o,"0")<r.fraction.padEnd(o,"0")},or=(e,t)=>{let n=Re(e),r=Re(t);if(n===null||r===null)return null;let o=Math.max(3,n.fraction.length,r.fraction.length),i=10n**BigInt(o),s=(BigInt(r.epochSeconds)-BigInt(n.epochSeconds))*i+BigInt(r.fraction.padEnd(o,"0"))-BigInt(n.fraction.padEnd(o,"0")),l=10n**BigInt(o-3);return Number(s>0n?(s+l-1n)/l:s/l)};var xe=e=>{if(!Number.isInteger(e)||e<1)throw new RangeError(`A requeue chunk reads a positive integer of documents: ${e}`);return(t,n)=>{let r=t.requeued+t.skipped.length;r>e&&d(n,["requeued"],`One chunk settles at most ${e} documents.`),t.nextAfter!==null!=(r===e)&&d(n,["nextAfter"],"A chunk continues exactly when it read the limit.");let o=new Set;for(let[i,s]of t.skipped.entries())o.has(s.metadataId)&&d(n,["skipped",i,"metadataId"],"A chunk keeps a document back once."),o.add(s.metadataId)}};var ar=100,Tt=Q.number().int().min(1).max(Number.MAX_SAFE_INTEGER),xi=Q.object({after:Tt.optional()}).strict(),ir=Q.object({requeued:Q.number().int().nonnegative(),skipped:Q.array(Q.object({metadataId:Q.number().int().min(1),reason:Q.string().min(1)}).strict()),nextAfter:Tt.nullable()}).strict(),Ai=ir.superRefine(xe(ar));var se=class extends Error{statusCode;responseBody;parsedBody;constructor(t,n,r,o){super(t),this.name="EnrichmentClientError",this.statusCode=n,this.responseBody=r,this.parsedBody=o}},Ae=class{baseUrl;apiKey;fetchFn;timeoutMs;constructor(t){if(!t||typeof t.baseUrl!="string"||t.baseUrl.trim().length===0)throw new Error("baseUrl is required and must be a non-empty string for EnrichmentClient.");let n=t.baseUrl.trim().replace(/\/$/,"");if(t.apiKey&&n.startsWith("http://")&&!n.includes("localhost")&&!n.includes("127.0.0.1"))throw new Error("Security Violation: Transmitting Bearer tokens over unencrypted HTTP to non-localhost hosts is strictly prohibited.");this.baseUrl=n,this.apiKey=t.apiKey,this.fetchFn=t.fetchFn??fetch,this.timeoutMs=t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:3e4}async request(t,n,r){let o=`${this.baseUrl}${t}`,i={Accept:"application/json","Content-Type":"application/json","X-Tenant-Id":n};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`);let s=new AbortController,l=setTimeout(()=>s.abort(),this.timeoutMs),c;try{c=await this.fetchFn(o,{method:"POST",headers:i,body:JSON.stringify(r),signal:s.signal})}catch(u){let y=u instanceof Error?u.message:String(u);throw new se(`Network request failed for POST ${o}: ${y}`,0,"")}finally{clearTimeout(l)}if(!c.ok){let u=await c.text().catch(()=>""),y;try{y=JSON.parse(u)}catch{}throw new se(`API request failed with status ${c.status}: ${u}`,c.status,u,y)}let h=await c.text().catch(()=>"");if(h.trim().length!==0)try{return JSON.parse(h)}catch(u){let y=u instanceof Error?u.message:String(u);throw new se(`Failed to parse response JSON from ${o}: ${y}`,c.status,h)}}};import{z as m}from"zod";import{z as Nt}from"zod";var sr=Nt.enum(["google_cloud","google_vision","yomitoku_local","faster_whisper_local","google_speech","ollama_local","openai","anthropic","azure_openai","bedrock","custom_openai_compatible"]),le=Nt.enum(["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"]),he="RESTRICTED";var wi={rrfK:{min:1,max:200,default:60},alpha:{min:0,max:1,default:.7},threshold:{min:0,max:1},limit:{min:1,max:50,default:10},queryLength:{min:1,max:500},filterTextLength:{min:1,max:100}},Dt=le.options.filter(e=>e!==he);if(Dt.length===0)throw new Error("The confidentiality vocabulary left nothing filterable after removing the quarantined level; a validator built from this list would reject every request.");var ki=Dt,Ot=["KEYWORD","SPARSE","DENSE","HYBRID","GRAPH_TRAVERSE"],Pt={KEYWORD:{dense:!1,sparse:!1,graph:!1,lexical:!0},SPARSE:{dense:!1,sparse:!0,graph:!1,lexical:!1},DENSE:{dense:!0,sparse:!1,graph:!1,lexical:!1},HYBRID:{dense:!0,sparse:!0,graph:!0,lexical:!0},GRAPH_TRAVERSE:{dense:!1,sparse:!1,graph:!0,lexical:!1}};function Fi(e){let t=Pt[e];return t.dense&&!t.sparse}function Li(e){let t=Pt[e];return[t.dense,t.sparse,t.graph,t.lexical].filter(Boolean).length>1}var vi=["rrf","linear"],Mi=["vector","graph"],Ui=["FULL","DEGRADED_LEXICAL_ONLY","DEGRADED_PARTIAL"],zi=["vector_search_disabled","graph_search_disabled","circuit_breaker_open:vector","circuit_breaker_open:graph","vector_tier_not_configured","graph_tier_not_configured","no_active_vector_collection","vector_collections_missing","row_scope_permits_no_rows","vector_tier_unavailable","graph_tier_unavailable","vector_tier_timed_out","graph_tier_timed_out","tiers_not_executed"];var lr=m.string().trim().min(1,"tenant_id must be a non-empty string"),Gi=m.string().trim().min(1,"file_uri must be a non-empty string"),wt=m.enum(["PENDING","EXTRACTING","ENRICHING","PROJECTING","SYNCED","FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"]),Bi=m.object({page:m.number().int().positive().optional(),x:m.number().nonnegative().optional(),y:m.number().nonnegative().optional(),width:m.number().positive().optional(),height:m.number().positive().optional(),start_sec:m.number().nonnegative().optional(),end_sec:m.number().nonnegative().optional(),frame_index:m.number().int().nonnegative().optional(),timestamp_sec:m.number().nonnegative().optional(),scene_confidence:m.number().min(0).max(1).optional()}),cr=m.object({title:m.string().trim().min(1),start_sec:m.number().nonnegative(),end_sec:m.number().nonnegative(),summary:m.string()}),dr=m.object({start_sec:m.number().nonnegative(),end_sec:m.number().nonnegative(),speaker:m.string().trim().min(1),text:m.string()}),ur=m.object({label:m.string(),value:m.number(),currency:m.string()}),Vi=m.object({document_type:m.string().optional(),title:m.string().optional(),organization:m.string().optional(),key_entities:m.array(m.string()).optional(),dates:m.array(m.string()).optional(),amounts:m.array(ur).optional(),media_type:m.enum(["video","audio"]).optional(),duration_sec:m.number().nonnegative().optional(),chapters:m.array(cr).optional(),transcript_segments:m.array(dr).optional()}),Yi=m.enum(["CLOSED","OPEN","HALF_OPEN"]),pr=m.enum(Ot),mr=m.object({circuit_breaker_status:m.string(),quality_tier:m.string(),latency_ms:m.number().nonnegative(),total_hits:m.number().int().nonnegative(),fallback_applied:m.boolean(),degraded_reason:m.string().nullable()}),fr=m.enum(["CONTRACT_LEGAL","EMAIL_THREAD","DAILY_REPORT","FINANCIAL_REPORT","TECHNICAL_SPEC","MASTER_DATA","MEDIA_ASSET","GENERAL_DOCUMENT"]),Ji=m.enum(["hierarchical","conversation","section","fixed_size","table_aware","semantic","none","multimodal"]),hr=m.object({metadata_id:m.number().int().positive(),chunk_index:m.number().int().nonnegative(),text:m.string(),score:m.number()}),yr=m.object({metadata_id:m.number().int().positive(),relation:m.string(),target_name:m.string()}),kt=m.object({query:m.string().trim().min(1,"query must not be empty"),tenant_id:lr,domain_key:fr.optional(),limit:m.number().int().positive().optional(),department_id:m.number().int().positive().optional(),search_mode:pr.optional(),strategy_id:m.number().int().positive().optional()}).strict(),Ft=m.object({hits:m.array(hr),graph_hits:m.array(yr),tiers:m.record(m.string(),m.boolean()),metadata:mr});var Lt=class extends Ae{async search(t){let n=kt.parse(t),r=await this.request("/ai/search/hybrid",n.tenant_id,n);return Ft.parse(r)}};import{z as a}from"zod";import{z as S}from"zod";var Ye=["email","pdf","office","image","media","archive","markdown","text","google_native","other"],Qi={email:"\u30E1\u30FC\u30EB",pdf:"PDF",office:"Office \u6587\u66F8",image:"\u753B\u50CF",media:"\u97F3\u58F0\u30FB\u52D5\u753B",archive:"\u66F8\u5EAB",markdown:"Markdown",text:"\u30C6\u30AD\u30B9\u30C8",google_native:"Google \u30CD\u30A4\u30C6\u30A3\u30D6",other:"\u305D\u306E\u4ED6"},gr=[["message/rfc822","email"],["application/pdf","pdf"],["application/vnd.openxmlformats-officedocument.*","office"],["application/msword","office"],["application/vnd.ms-excel","office"],["application/vnd.ms-powerpoint","office"],["application/zip","archive"],["application/x-zip-compressed","archive"],["application/x-zip","archive"],["application/x-tar","archive"],["application/x-gtar","archive"],["application/gzip","archive"],["application/x-gzip","archive"],["application/x-bzip2","archive"],["application/x-xz","archive"],["application/x-7z-compressed","archive"],["application/vnd.rar","archive"],["application/x-rar-compressed","archive"],["application/x-rar","archive"],["application/vnd.google-apps.*","google_native"],["image/svg+xml","text"],["image/emf","other"],["image/x-emf","other"],["image/wmf","other"],["image/x-wmf","other"],["image/*","image"],["audio/*","media"],["video/*","media"],["text/markdown","markdown"],["text/x-markdown","markdown"],["text/*","text"],["application/json","text"],["application/xml","text"]];function es(e){let t=(e.split(";")[0]??"").trim().toLowerCase();for(let[n,r]of gr)if(n.endsWith("*")?t.startsWith(n.slice(0,-1)):t===n)return r;return"other"}var Te=["delete_child_assets","unlock_document","extract_text","analyze_media","extract_assets","ocr_document","ocr_children","resolve_body","enrich_document","project_to_indexes"],Je="record_document_state",$e=[...Te,Je],ts=["EXTRACTING","ENRICHING","PROJECTING"],jt=["FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"],Be=e=>({featureFlagKey:e,whenClosed:"skip",failureStatus:null}),vt=(e,t)=>({featureFlagKey:e,whenClosed:"fail",failureStatus:t}),Kt={delete_child_assets:{key:"delete_child_assets",label:"\u65E7\u7248\u306E\u5B50\u30A2\u30BB\u30C3\u30C8\u524A\u9664",description:"\u3053\u306E\u7248\u3088\u308A\u524D\u306E\u7248\u304C\u751F\u3093\u3060\u5B50\u30A2\u30BB\u30C3\u30C8\u3092\u4FDD\u7BA1\u5C64\u3068\u7D22\u5F15\u304B\u3089\u5916\u3059\u3002",endpoint:"/ai/assets/delete",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:null,fanOut:null},unlock_document:{key:"unlock_document",label:"\u30D1\u30B9\u30EF\u30FC\u30C9\u306E\u89E3\u9664",description:"\u6587\u66F8\u304C\u6301\u3064\u30D1\u30B9\u30EF\u30FC\u30C9 (ZIP\u30FBPDF\u30FBOffice) \u3092\u3001\u6761\u4EF6\u306E\u5F53\u305F\u308B\u30D5\u30A1\u30A4\u30EB\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3067\u5916\u3057\u3001\u89E3\u3044\u305F\u30D5\u30A1\u30A4\u30EB\u3092\u539F\u672C\u306B\u3059\u308B (\u6E90\u3092\u4E0A\u66F8\u304D\u3059\u308B\u304B\u89E3\u3044\u305F\u5199\u3057\u3092\u539F\u672C\u306B\u3057\u3001\u30D1\u30B9\u30EF\u30FC\u30C9\u306E\u7121\u3044\u6587\u66F8\u306F\u98DB\u3070\u3059)\u3002",endpoint:"/ai/documents/unlock",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:null,fanOut:null},extract_text:{key:"extract_text",label:"\u6587\u5B57\u5C64\u306E\u62BD\u51FA",description:"\u6587\u66F8\u304C\u6301\u3064\u6587\u5B57\u5C64 (PDF \u306E\u6587\u5B57\u30FBOffice \u306E\u672C\u6587\u30FB\u30E1\u30FC\u30EB\u306E\u672C\u6587\u3068\u898B\u51FA\u3057) \u3092\u8AAD\u307F\u3001\u4F4D\u7F6E\u60C5\u5831\u3068\u5171\u306B\u4FDD\u5B58\u3059\u308B\u3002",endpoint:"/ai/enrichment/extract",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:null,fanOut:null},analyze_media:{key:"analyze_media",label:"\u30E1\u30C7\u30A3\u30A2\u89E3\u6790",description:"\u97F3\u58F0\u30FB\u52D5\u753B\u3092\u8EE2\u5199\u3057\u3001\u767A\u8A71\u533A\u9593\u4ED8\u304D\u306E\u30C1\u30E3\u30F3\u30AF\u3068\u30AD\u30FC\u30D5\u30EC\u30FC\u30E0\u6570\u3092\u8A18\u9332\u3059\u308B\u3002",endpoint:"/ai/media/analyze",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[Be("ENABLE_MEDIA_ANALYSIS")],capability:"transcription",fanOut:null},extract_assets:{key:"extract_assets",label:"\u5B50\u30A2\u30BB\u30C3\u30C8\u306E\u62BD\u51FA",description:"\u57CB\u3081\u8FBC\u307F\u753B\u50CF\u30FB\u30E1\u30FC\u30EB\u306E\u6DFB\u4ED8\u30FBMarkdown \u304C\u53C2\u7167\u3059\u308B\u753B\u50CF\u30FB\u66F8\u5EAB (ZIP\u30FB7z\u30FBRAR\u30FBtar\u30FBgzip\u30FBbzip2\u30FBxz) \u306E\u4E2D\u8EAB\u3092\u5B50\u30A2\u30BB\u30C3\u30C8\u3068\u3057\u3066\u53D6\u308A\u51FA\u3057 (\u6DFB\u4ED8\u306E\u66F8\u5EAB\u3082\u4E2D\u8EAB\u3078\u5C55\u958B\u3059\u308B)\u3001\u914D\u5099\u306E\u7F6E\u304D\u5834\u3078\u5199\u3057\u3066\u767B\u9332\u3059\u308B\u3002",endpoint:"/ai/assets/extract",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[Be("ENABLE_ASSET_EXTRACTION")],capability:"asset_extraction",fanOut:null},ocr_children:{key:"ocr_children",label:"\u5B50\u30A2\u30BB\u30C3\u30C8\u306E\u8AAD\u307F\u53D6\u308A",description:"\u5207\u308A\u51FA\u3057\u305F\u5B50\u30A2\u30BB\u30C3\u30C8\u3092\u62BD\u51FA\u9806\u306B 1 \u4EF6\u305A\u3064\u8AAD\u307F\u3001\u6587\u5B57\u5C64\u3092\u8AAD\u3081\u308B\u5B50 (\u30C6\u30AD\u30B9\u30C8\u30FB\u30E1\u30FC\u30EB\u30FBOffice\u30FBPDF) \u306F\u305D\u306E\u6587\u5B57\u5C64\u3092\u3001\u8AAD\u3081\u306A\u3044\u5B50\u306F\u7248\u9762\u3092\u5149\u5B66\u8A8D\u8B58\u3067\u8AAD\u3093\u3067 (\u89AA\u306E\u672C\u6587\u3067\u3042\u308B\u7248\u9762\u306E\u8A8D\u8B58\u304C\u65E2\u306B\u8AAD\u3093\u3060\u30DA\u30FC\u30B8\u306B\u8F09\u308B PDF \u306E\u753B\u50CF\u306F\u8AAD\u307F\u76F4\u3055\u306A\u3044)\u3001\u5B50\u3054\u3068\u306B\u672C\u6587\u3068\u51FA\u6240\u3092\u4FDD\u5B58\u3059\u308B\u3002",endpoint:"/ai/ocr/run",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:"ocr",fanOut:"children"},ocr_document:{key:"ocr_document",label:"\u6587\u66F8\u306E OCR",description:"\u6587\u66F8\u81EA\u8EAB\u306E\u7248\u9762 (\u753B\u50CF\u30FBPDF \u306E\u5404\u30DA\u30FC\u30B8) \u3092\u5149\u5B66\u8A8D\u8B58\u306B\u304B\u3051\u308B\u3002",endpoint:"/ai/ocr/run",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[Be("ENABLE_OCR")],capability:"ocr",fanOut:null},resolve_body:{key:"resolve_body",label:"\u672C\u6587\u306E\u78BA\u5B9A",description:"\u6587\u5B57\u5C64\u30FBOCR\u30FB\u8EE2\u5199\u306E\u3069\u308C\u3092\u672C\u6587\u3068\u3059\u308B\u304B\u3092\u6C7A\u3081\u3001\u51FA\u6240\u3092\u8A18\u9332\u3059\u308B\u3002",endpoint:"/ai/enrichment/body",phase:"ENRICHING",failureStatus:"FAILED_ENRICH",gates:[],capability:null,fanOut:null},enrich_document:{key:"enrich_document",label:"\u8981\u7D04\u3068\u69CB\u9020\u5316\u62BD\u51FA",description:"\u672C\u6587\u3092\u30E2\u30C7\u30EB\u3078\u6E21\u3057\u3001\u8981\u7D04\u30FB\u30BF\u30B0\u30FB\u69CB\u9020\u5316\u30C7\u30FC\u30BF\u30FB\u30C9\u30E1\u30A4\u30F3\u5206\u985E\u3092\u5F97\u308B\u3002",endpoint:"/ai/enrichment/document",phase:"ENRICHING",failureStatus:"FAILED_ENRICH",gates:[],capability:"enrichment",fanOut:null},project_to_indexes:{key:"project_to_indexes",label:"\u30D9\u30AF\u30C8\u30EB\u3068\u30B0\u30E9\u30D5\u3078\u306E\u6295\u5F71",description:"\u672C\u6587\u3092\u30C1\u30E3\u30F3\u30AF\u306B\u3057\u3066\u57CB\u3081\u8FBC\u307F\u3001\u30D9\u30AF\u30C8\u30EB\u7D22\u5F15\u3068\u30CA\u30EC\u30C3\u30B8\u30B0\u30E9\u30D5\u3078\u66F8\u304F\u3002",endpoint:"/ai/enrichment/project",phase:"PROJECTING",failureStatus:"FAILED_VECTOR",gates:[vt("ENABLE_VECTOR_INDEXING","FAILED_VECTOR"),vt("ENABLE_GRAPH_INDEXING","FAILED_GRAPH")],capability:null,fanOut:null}},Ve={whenClosed:"fail",failureStatus:"FAILED_EXTRACT"},Mt=[{step:"delete_child_assets",dependsOn:[]},{step:"extract_text",dependsOn:["delete_child_assets"]},{step:"extract_assets",dependsOn:["extract_text"]},{step:"ocr_document",dependsOn:["extract_text"]},{step:"ocr_children",dependsOn:["extract_assets","ocr_document"]},{step:"resolve_body",dependsOn:["ocr_children","ocr_document"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],Ut=[{step:"delete_child_assets",dependsOn:[]},{step:"unlock_document",dependsOn:["delete_child_assets"]},{step:"extract_text",dependsOn:["unlock_document"]},{step:"extract_assets",dependsOn:["extract_text"]},{step:"ocr_document",dependsOn:["extract_text"]},{step:"ocr_children",dependsOn:["extract_assets","ocr_document"]},{step:"resolve_body",dependsOn:["ocr_children","ocr_document"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],Sr=[{step:"delete_child_assets",dependsOn:[]},{step:"extract_text",dependsOn:["delete_child_assets"]},{step:"extract_assets",dependsOn:["extract_text"]},{step:"ocr_children",dependsOn:["extract_assets"]},{step:"resolve_body",dependsOn:["ocr_children"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],zt=[{step:"delete_child_assets",dependsOn:[]},{step:"extract_text",dependsOn:["delete_child_assets"]},{step:"resolve_body",dependsOn:["extract_text"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],Er={email:{kind:"email",steps:Mt},pdf:{kind:"pdf",steps:Ut},office:{kind:"office",steps:Ut},google_native:{kind:"google_native",steps:Mt},image:{kind:"image",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"ocr_document",dependsOn:["delete_child_assets"],gatePolicy:Ve},{step:"resolve_body",dependsOn:["ocr_document"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}]},media:{kind:"media",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"analyze_media",dependsOn:["delete_child_assets"],gatePolicy:Ve},{step:"resolve_body",dependsOn:["analyze_media"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"existing"}]},archive:{kind:"archive",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"unlock_document",dependsOn:["delete_child_assets"]},{step:"extract_assets",dependsOn:["unlock_document"],gatePolicy:Ve},{step:"ocr_children",dependsOn:["extract_assets"]},{step:"resolve_body",dependsOn:["ocr_children"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}]},markdown:{kind:"markdown",steps:Sr},text:{kind:"text",steps:zt},other:{kind:"other",steps:zt}};function ns(e){return Er[e]}function rs(e){let{gates:t}=Kt[e.step],{gatePolicy:n}=e;return n===void 0?t:t.map(r=>({featureFlagKey:r.featureFlagKey,whenClosed:n.whenClosed,failureStatus:n.failureStatus}))}function os(e){let t=new Map(e.steps.map(i=>[i.step,i]));for(let i of e.steps){if(i.gatePolicy!==void 0&&Kt[i.step].gates.length===0)throw new Error(`Flow ${e.kind}: step ${i.step} overrides its gate policy, but the step has no gate to close.`);for(let s of i.dependsOn)if(!t.has(s))throw new Error(`Flow ${e.kind}: step ${i.step} depends on ${s}, which the flow does not contain.`)}let n=[...e.steps],r=new Set,o=[];for(;n.length>0;){let i=n.findIndex(l=>l.dependsOn.every(c=>r.has(c)));if(i===-1)throw new Error(`Flow ${e.kind}: the steps ${n.map(l=>l.step).join(", ")} depend on each other in a cycle.`);let[s]=n.splice(i,1);r.add(s.step),o.push(s)}return o}var Ht={EXTRACTING:0,ENRICHING:1,PROJECTING:2};function as(e,t){return Ht[e]-Ht[t]}import{z as ye}from"zod";function ls(e,t){return Gt(e,t)?t:{known:!1,raw:t}}function Gt(e,t){return e.includes(t)}function br(e){return typeof e!="string"}function cs(e){return br(e)?e.raw:e}function Ne(e){let t=ye.object({known:ye.literal(!1),raw:ye.string()}).strict().refine(n=>!Gt(e,n.raw),{message:"A value the vocabulary knows is carried as itself, never as an unknown term.",path:["raw"]});return ye.union([ye.enum(e),t])}var Cr=S.enum(Ye),Bt=S.enum(Te),ys=S.enum($e),Vt=S.enum(jt),_r=["RECORDED","UNCHANGED","ALREADY_RECORDED"],Rr=S.enum(_r),Ir=S.object({outcome:Rr}).strict(),xr=["history_no_current_row","history_lock_timeout","history_write_failed"],Ar="stale_run",Tr=S.enum(xr),Ze=S.enum(["RUNNING","SUCCEEDED","FAILED"]),Nr=S.enum(["RUNNING","SUCCEEDED","SKIPPED","FAILED"]),Dr=S.enum(["ingest","retry","resync"]),Qe=S.enum(["text_layer","ocr","transcript"]),B=S.number().int().nonnegative().nullable(),Or=S.object({provider:S.string().nullable(),model:S.string().nullable(),engine:S.string().nullable(),prompt_key:S.string().nullable(),prompt_version:S.number().int().nullable(),duration_ms:B,input_chars:B,output_chars:B,pages_read:B,pages_total:B,chunk_count:B,points_upserted:B,collection:S.string().nullable(),embedding_model:S.string().nullable(),strategy_id:S.number().int().positive().nullable(),graph_nodes:B,body_source:Qe.nullable(),detail:S.custom(Ie,"A report's detail holds no own __proto__ member.").pipe(S.record(S.string(),S.unknown()))}).strict(),Pr=["no_pages","no_pages_rendered","covered_by_page_recognition"],wr=S.enum(Pr),qe="gate_closed:",Xe="source_skipped:",We="nothing_to_read:",kr=["no_children","not_protected","superseded","recording_disabled","recording_misconfigured"],Fr=e=>kr.includes(e),Lr=/^[A-Z][A-Z0-9_]*$/;function Yt(e){if(Fr(e))return{kind:e};if(e.startsWith(qe)){let t=e.slice(qe.length);return Lr.test(t)?{kind:"gate_closed",featureFlagKey:t}:null}if(e.startsWith(Xe)){let t=Bt.safeParse(e.slice(Xe.length));return t.success?{kind:"source_skipped",stepKey:t.data}:null}if(e.startsWith(We)){let t=wr.safeParse(e.slice(We.length));return t.success?{kind:"nothing_to_read",token:t.data}:null}return null}function gs(e){let t=vr(e);if(Yt(t)===null)throw new RangeError(`Skip reason ${JSON.stringify(e)} has no text form: ${JSON.stringify(t)} is outside the skip-reason grammar.`);return t}function vr(e){switch(e.kind){case"gate_closed":return`${qe}${e.featureFlagKey}`;case"no_children":case"not_protected":case"superseded":case"recording_disabled":case"recording_misconfigured":return e.kind;case"source_skipped":return`${Xe}${e.stepKey}`;case"nothing_to_read":return`${We}${e.token}`;default:{let t=e;throw new RangeError(`Unknown skip reason kind: ${JSON.stringify(t)}`)}}}var Mr=S.object({id:S.number().int().positive(),runId:S.number().int().positive(),sequence:S.number().int().nonnegative(),stepKey:Ne($e),targetMetadataId:S.number().int().positive(),targetTreePath:_e.nullable(),status:Nr,skipReason:S.string().nullable(),provenance:Or.nullable(),strategyId:S.number().int().positive().nullable(),httpStatus:S.number().int().nullable(),errorCode:S.string().nullable(),errorMessage:S.string().nullable(),startedAt:N,finishedAt:N.nullable(),durationMs:B}).strict();function Ur(e,t){switch(e.stepKey===Je&&Hr(e,t),e.status){case"SKIPPED":e.skipReason===null&&d(t,["skipReason"],"A SKIPPED step must record why it was skipped."),e.provenance!==null&&d(t,["provenance"],"A SKIPPED step read nothing, so it has no report.");return;case"SUCCEEDED":e.provenance===null&&d(t,["provenance"],"A SUCCEEDED step must carry its report."),e.skipReason!==null&&d(t,["skipReason"],"A SUCCEEDED step was not skipped.");return;case"RUNNING":e.finishedAt!==null&&d(t,["finishedAt"],"A RUNNING step has not finished.");return;case"FAILED":e.skipReason!==null&&d(t,["skipReason"],"A FAILED step was not skipped.");return}}var zr=["superseded","recording_disabled","recording_misconfigured"];function Hr(e,t){if(e.strategyId!==null&&d(t,["strategyId"],"The terminal step applies no strategy."),e.httpStatus!==null&&d(t,["httpStatus"],"The terminal step calls no API, so it has no HTTP status."),e.status==="SUCCEEDED"&&e.provenance!==null){Ir.safeParse(e.provenance.detail).success||d(t,["provenance","detail"],"A succeeded terminal step's detail is exactly { outcome }.");for(let[n,r]of Object.entries(e.provenance))n!=="detail"&&r!==null&&d(t,["provenance",n],"A succeeded terminal step reports nothing but its outcome.")}if(e.status==="FAILED"&&(e.provenance!==null&&d(t,["provenance"],"Neither the failure close nor the recovery sweeper writes a terminal step's report."),e.errorCode!==Ar&&!Tr.safeParse(e.errorCode).success&&d(t,["errorCode"],"A failed terminal step names a history error code, or the stale-run code the sweeper writes.")),e.status==="SKIPPED"&&e.skipReason!==null){let n=Yt(e.skipReason);(n===null||!zr.includes(n.kind))&&d(t,["skipReason"],"A skipped terminal step names one of the terminal skip reasons.")}}var jr=Mr.superRefine(Ur),Jt=S.object({id:S.number().int().positive(),tenantId:S.string().min(1),metadataId:S.number().int().positive(),revision:S.number().int().positive(),runUid:S.string().uuid(),jobId:S.string().min(1),attempt:S.number().int().positive(),trigger:Dr,documentKind:Ne(Ye),flowKey:S.string().min(1),status:Ze,retryScheduled:S.boolean(),failedStepKey:Ne(Te).nullable(),errorMessage:S.string().nullable(),requestedBy:S.string().min(1),startedAt:N,finishedAt:N.nullable(),steps:S.array(jr)}).strict();function $t(e,t){e.retryScheduled&&e.status!=="FAILED"&&d(t,["retryScheduled"],"Only a FAILED run can have a retry scheduled.")}var qt=Jt.superRefine($t),Xt=Jt.omit({steps:!0}).superRefine($t);function Kr(e,t){e.sampleCount>0||(e.durationP50Ms!==null&&d(t,["durationP50Ms"],"A step with no sample has no median latency."),e.durationP95Ms!==null&&d(t,["durationP95Ms"],"A step with no sample has no 95th-percentile latency."))}var Ss=S.object({documentKind:Cr,stepKey:Bt,sampleCount:S.number().int().nonnegative(),succeeded:S.number().int().nonnegative(),failed:S.number().int().nonnegative(),skipped:S.number().int().nonnegative(),durationP50Ms:B,durationP95Ms:B,lastStartedAt:N.nullable()}).strict().superRefine(Kr);var en=2,tt=3,tn=64,nn=1e6,nt=4096,rt=.3,rn=1024,on=67108864,an=16777216,sn=500,ln=50,Ts=50,Ns=1e4,Gr=1,de=["classification","metadata","labels","tags","structured_data","text","summary","chunks","assets"],cn=a.enum(de),Br=["RUN","PRE_WRITE","MANUAL","BACKFILL"],dn=a.enum(Br),Vr=["SUCCEEDED","FAILED"],Yr=a.enum(Vr),Jr=["ADDED","REMOVED","MODIFIED","MOVED"],$r=a.enum(Jr),qr=["clause","breadcrumbs"],Xr=a.enum(qr),Wr=["EXACT","WHITESPACE_NORMALIZED","UNVERIFIED"],Zr=a.enum(Wr),Qr=["run","ingest","failure","state","change"],Ds=a.enum(Qr),eo=["LF","CRLF","CR","MIXED","NONE"],Os=a.enum(eo),to=["text","summary","chunks"],Ps=a.enum(to),no=["RECORDED","UNCHANGED"],ro=a.enum(no),un=a.lazy(()=>a.custom(Ie,"A JSON object here holds no own __proto__ member.").pipe(a.record(a.string(),V))),V=a.lazy(()=>a.union([a.string(),a.number().finite(),a.boolean(),a.null(),a.array(V),un])),pn=le.exclude([he]),z=a.number().int().positive(),R=a.number().int().nonnegative(),Oe=a.string().regex(/^[0-9a-f]{64}$/,"A SHA-256 is 64 lowercase hexadecimal digits."),q=(e,t)=>e<t?-1:e>t?1:0,ot=(e,t)=>At(ae(e),ae(t)),ce=(e,t,n,r,o)=>{for(let i=1;i<e.length;i++)t(e[i-1],e[i])>=0&&d(n,[...r,i],o)},oo=a.object({confidentialityLevel:le,departmentId:a.number().int().nullable(),folderPath:a.string().nullable(),createdBy:a.string()}).strict(),ao=a.object({fileName:a.string(),filePath:a.string(),fileId:a.string().nullable(),revision:z,revisionId:a.string().nullable(),fileSize:R,mimeType:a.string(),fileHash:a.string().nullable(),mtime:N}).strict(),io=a.object({labelKey:a.string().min(1),assignedBy:a.string(),confidenceScore:a.number().finite()}).strict(),so=a.string().refine(e=>!e.includes("/")&&Ce.test(`${e}-0`),"An asset type is the kind of a tree path segment: lowercase letters and underscores."),mn=a.object({assetType:so,assetIndex:R.max(Number.MAX_SAFE_INTEGER),mimeType:a.string(),fileSize:R,textSha256:Oe.nullable(),parentPath:_e.optional()}).strict(),lo=mn.pick({assetType:!0,assetIndex:!0,parentPath:!0}).strip(),co=a.object({body:a.string().nullable(),mime:a.string().nullable(),source:Qe.nullable(),isTruncated:a.boolean(),pageOffsets:V}).strict(),uo=a.object({index:R,hash:Oe,whitespaceFreeHash:Oe,charStart:R,charEnd:R,breadcrumbs:a.string(),clause:a.string().nullable(),page:a.number().int().nullable(),sheet:a.string().nullable(),slide:a.number().int().nullable(),startSec:a.number().finite().nullable(),endSec:a.number().finite().nullable(),tokenCount:R,parentOrdinal:R}).strict(),po=a.object({ordinal:R,contentHash:Oe,charLength:R}).strict();function mo(e,t){ce(e.children,(r,o)=>r.index-o.index,t,["children"],"Children are listed in strictly ascending index.");let n=0;e.children.forEach((r,o)=>{r.charStart>r.charEnd&&d(t,["children",o,"charEnd"],"A span ends at or after its start."),r.parentOrdinal===n?n++:r.parentOrdinal>n&&d(t,["children",o,"parentOrdinal"],"Parents are numbered in the order they first appear.")}),(e.parents.length!==n||e.parents.some((r,o)=>r.ordinal!==o))&&d(t,["parents"],"Each parent the children reach is listed exactly once, in ordinal order.")}var fo=a.object({version:a.literal(Gr),children:a.array(uo).min(1),parents:a.array(po)}).strict().superRefine(mo);function ho(e,t){ce(e.labels,(n,r)=>q(n.labelKey,r.labelKey),t,["labels"],"Labels are ordered by labelKey with no key repeated."),ce(e.tags??[],q,t,["tags"],"Tags are ordered with no tag repeated."),e.assets.every(n=>lo.safeParse(n).success)&&(ce(e.assets,ot,t,["assets"],"Assets are ordered by their tree paths in tree order with no path repeated."),yo(e.assets,t))}function yo(e,t){let n=new Set;e.forEach((r,o)=>{Object.hasOwn(r,"parentPath")&&r.parentPath===void 0&&d(t,["assets",o,"parentPath"],"parentPath is absent at depth 1, never undefined."),r.parentPath!==void 0&&!n.has(r.parentPath)&&d(t,["assets",o,"parentPath"],"Each parentPath names an earlier item's tree path."),n.add(ae(r))})}var ws=a.object({classification:oo,metadata:ao,labels:a.array(io),tags:a.array(a.string()).nullable(),structured_data:V,text:co,summary:a.string().nullable(),chunks:fo.nullable(),assets:a.array(mn)}).strict().superRefine(ho),go=["addedCount","removedCount","modifiedCount","movedCount","unchangedCount","charsAdded","charsRemoved"],So={classification:["modifiedCount"],metadata:["modifiedCount"],labels:["addedCount","removedCount","modifiedCount","unchangedCount"],tags:["addedCount","removedCount","unchangedCount"],structured_data:["addedCount","removedCount","modifiedCount"],text:["addedCount","removedCount","unchangedCount","charsAdded","charsRemoved"],summary:["addedCount","removedCount","unchangedCount","charsAdded","charsRemoved"],chunks:["addedCount","removedCount","modifiedCount","movedCount","unchangedCount"],assets:["addedCount","removedCount","modifiedCount","unchangedCount"]};function Eo(e,t){let n=So[e.facet];for(let r of go)n.includes(r)&&e[r]===null&&d(t,[r],`The ${e.facet} facet always counts ${r}.`),!n.includes(r)&&e[r]!==null&&d(t,[r],`${r} does not apply to the ${e.facet} facet.`)}var bo=a.object({facet:cn,addedCount:R.nullable(),removedCount:R.nullable(),modifiedCount:R.nullable(),movedCount:R.nullable(),unchangedCount:R.nullable(),charsAdded:R.nullable(),charsRemoved:R.nullable()}).strict().superRefine(Eo),Wt=new Map(de.map((e,t)=>[e,t])),at=(e,t)=>Wt.get(e)-Wt.get(t),fn=a.array(bo).min(1).superRefine((e,t)=>ce(e,(n,r)=>at(n.facet,r.facet),t,[],"A change lists each changed facet once, in display order.")),it=a.object({field:a.string().min(1),before:V,after:V}).strict(),Zt=a.object({key:a.string().min(1),value:un}).strict(),Co=a.object({key:a.string().min(1),fields:a.array(it).min(1)}).strict(),et=a.string().refine(e=>e===""||e.startsWith("/"),"A JSON Pointer is empty or starts with '/'."),_o=a.discriminatedUnion("op",[a.object({op:a.literal("add"),path:et,value:V}).strict(),a.object({op:a.literal("remove"),path:et,previous:V}).strict(),a.object({op:a.literal("replace"),path:et,value:V,previous:V}).strict()]),Ro=a.object({linesAdded:R,linesRemoved:R,linesUnchanged:R,charsAdded:R,charsRemoved:R,similarity:a.number().min(0).max(1).nullable()}).strict();function Io(e,t){e.linesAdded>e.newLines&&d(t,["linesAdded"],"A hunk adds no more lines than it spans on the new side."),e.linesRemoved>e.oldLines&&d(t,["linesRemoved"],"A hunk removes no more lines than it spans on the old side."),e.linesAdded+e.linesRemoved===0&&d(t,["linesAdded"],"A hunk changes at least one line.")}var xo=a.object({hunk:R,oldStart:R,oldLines:R,newStart:R,newLines:R,firstPage:a.number().int().nullable(),linesAdded:R,linesRemoved:R}).strict().superRefine(Io),hn=(e,t)=>{e.forEach((n,r)=>{n.hunk!==r&&d(t,["hunks",r,"hunk"],"Hunks are numbered from 0 in order.")})},yn={attributes:a.array(it),stats:Ro,hunks:a.array(xo)},ks=a.object(yn).strict().superRefine((e,t)=>hn(e.hunks,t)),Ao=a.object({kind:a.enum(["equal","removed","added"]),text:a.string().min(1)}).strict(),To={context:["equal"],removed:["equal","removed"],added:["equal","added"]};function No(e,t){e.oldNumber===null!=(e.kind==="added")&&d(t,["oldNumber"],"Context and removed lines carry their old number; added lines carry none."),e.newNumber===null!=(e.kind==="removed")&&d(t,["newNumber"],"Context and added lines carry their new number; removed lines carry none."),e.segments.forEach((n,r)=>{To[e.kind].includes(n.kind)||d(t,["segments",r,"kind"],`A ${e.kind} line has no ${n.kind} segment.`)})}var Do=a.object({kind:a.enum(["context","removed","added"]),oldNumber:z.nullable(),newNumber:z.nullable(),page:a.number().int().nullable(),segments:a.array(Ao)}).strict().superRefine(No),Fs=a.object({lines:a.array(Do).max(sn),next:R.nullable()}).strict().superRefine((e,t)=>{e.next!==null&&e.lines.length===0&&d(t,["next"],"An empty page has no next page.")}),gn=a.number().int().min(1).max(sn),Ls=a.number().int().min(1).max(ln),Qt=a.object({index:R,charStart:R,charEnd:R,page:a.number().int().nullable(),sheet:a.string().nullable(),slide:a.number().int().nullable(),startSec:a.number().finite().nullable(),endSec:a.number().finite().nullable(),breadcrumbs:a.string(),tokenCount:R,fidelity:Zr}).strict();function Oo(e,t){e.old===null!=(e.kind==="ADDED")&&d(t,["old"],"Every chunk change but ADDED has an old chunk."),e.new===null!=(e.kind==="REMOVED")&&d(t,["new"],"Every chunk change but REMOVED has a new chunk."),e.pairing===null==(e.kind==="MODIFIED")&&d(t,["pairing"],"A MODIFIED pair names the rule that paired it; no other change has one.")}var Po=a.object({entry:R,kind:$r,pairing:Xr.nullable(),old:Qt.nullable(),new:Qt.nullable()}).strict().superRefine(Oo),wo=a.object({added:R,removed:R,modified:R,moved:R,unchanged:R}).strict();function ko(e,t){e.entries.forEach((o,i)=>{o.entry!==i&&d(t,["entries",i,"entry"],"Chunk entries are numbered from 0 in order.")});let n={ADDED:0,REMOVED:0,MODIFIED:0,MOVED:0};for(let o of e.entries)n[o.kind]++;let r=[["added",n.ADDED],["removed",n.REMOVED],["modified",n.MODIFIED],["moved",n.MOVED]];for(let[o,i]of r)e.stats[o]!==i&&d(t,["stats",o],`The ${o} count equals the number of entries of that kind.`)}var Fo=a.union([a.object({facet:cn,change:a.literal("UNCHANGED")}).strict(),a.object({facet:a.enum(["classification","metadata"]),change:a.literal("CHANGED"),fields:a.array(it).min(1)}).strict(),a.object({facet:a.enum(["labels","assets"]),change:a.literal("CHANGED"),added:a.array(Zt),removed:a.array(Zt),modified:a.array(Co),unchangedCount:R}).strict(),a.object({facet:a.literal("tags"),change:a.literal("CHANGED"),added:a.array(a.string()),removed:a.array(a.string()),unchangedCount:R}).strict(),a.object({facet:a.literal("structured_data"),change:a.literal("CHANGED"),operations:a.array(_o).min(1)}).strict(),a.object({facet:a.enum(["text","summary"]),change:a.literal("CHANGED"),...yn}).strict().superRefine((e,t)=>hn(e.hunks,t)),a.object({facet:a.literal("chunks"),change:a.literal("CHANGED"),stats:wo,entries:a.array(Po),textUnchangedChunkingChanged:a.boolean()}).strict().superRefine(ko)]),vs=a.object({diffEngineVersion:z,facets:a.array(Fo)}).strict().superRefine((e,t)=>{(e.facets.length!==de.length||e.facets.some((n,r)=>n.facet!==de[r]))&&d(t,["facets"],"A comparison carries every facet once, in display order.")}),Pe=e=>a.object({kind:a.literal("readable"),item:e}).strict(),Sn=a.object({kind:a.literal("restricted"),subject:a.literal("run"),startedAt:N,finishedAt:N.nullable(),status:Ze}).strict(),Ms=a.object({kind:a.literal("restricted"),subject:a.literal("ingest"),createdAt:N,updatedAt:N,syncStatus:wt.nullable()}).strict(),Us=a.object({kind:a.literal("restricted"),subject:a.literal("failure"),failedAt:N.nullable(),syncStatus:Vt}).strict(),Lo=a.object({kind:a.literal("restricted"),subject:a.literal("state"),settledAt:N}).strict(),vo=a.object({kind:a.literal("restricted"),subject:a.literal("change"),settledAt:N}).strict();function Mo(e,t){let n=e.cause==="RUN";e.runId!==null!==n&&d(t,["runId"],"A RUN state names its run; no other state does."),e.runOutcome!==null!==n&&d(t,["runOutcome"],"A RUN state carries the worker's outcome; no other state does."),e.changes!==null!=(e.previousStateId!==null)&&d(t,["changes"],"A state carries its counts exactly when its predecessor is readable."),e.diffEngineVersion!==null!=(e.changes!==null)&&d(t,["diffEngineVersion"],"The engine version comes with the counts it produced."),e.modelOnlyChange&&e.changes===null&&d(t,["modelOnlyChange"],"Only a change with counts can be a model-only change."),e.previousStateId===e.stateId&&d(t,["previousStateId"],"A state does not precede itself.")}var Uo=a.object({stateId:z,revision:z,cause:dn,runId:z.nullable(),runOutcome:Yr.nullable(),settledAt:N,actor:a.string().min(1),classification:a.object({confidentialityLevel:pn,departmentId:a.number().int().nullable(),folderPath:a.string().nullable()}).strict(),modelOnlyChange:a.boolean(),previousStateId:z.nullable(),changes:fn.nullable(),diffEngineVersion:z.nullable()}).strict().superRefine(Mo),zo=a.discriminatedUnion("kind",[Pe(Uo),Lo]),Ho=a.discriminatedUnion("kind",[Pe(qt),Sn]),zs=a.discriminatedUnion("kind",[Pe(Xt),Sn]),En=(e,t,n)=>{for(let r=1;r<e.length;r++)$(e[r-1],e[r])&&d(t,[...n,r],"Entries are listed newest first.")},De=e=>e.kind==="readable"?e.item.settledAt:e.settledAt;function jo(e,t){ce(e.revisions,(r,o)=>o.revision-r.revision,t,["revisions"],"Revisions are listed newest first, each once.");let n=e.revisions.filter(r=>r.isCurrent);(n.length!==1||n[0]?.metadataId!==e.document.metadataId||n[0].revision!==e.document.revision)&&d(t,["revisions"],"Exactly one revision is current: the row the history names."),En(e.states.map(De),t,["states"])}var Hs=a.object({document:a.object({metadataId:z,fileName:a.string().min(1),fileUri:a.string().min(1),revision:z,confidentialityLevel:pn}).strict(),revisions:a.array(a.object({metadataId:z,revision:z,revisionId:a.string().nullable(),isCurrent:a.boolean()}).strict()),states:a.array(zo),runs:a.array(Ho)}).strict().superRefine(jo),Ko=a.object({stateId:z,previousStateId:z,metadataId:z,fileName:a.string().min(1),fileUri:a.string().min(1),revision:z,previousRevision:z,cause:dn,actor:a.string().min(1),settledAt:N,changes:fn}).strict().superRefine((e,t)=>{e.previousStateId===e.stateId&&d(t,["previousStateId"],"A state does not precede itself.")}),Go=a.discriminatedUnion("kind",[Pe(Ko),vo]),bn=a.object({settledAt:N,id:z.max(Number.MAX_SAFE_INTEGER)}).strict(),ge="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function Bo(e){let t="";for(let n=0;n<e.length;n+=3){let r=e.length-n,o=e[n]<<16|(r>1?e[n+1]:0)<<8|(r>2?e[n+2]:0);t+=ge[o>>18&63]+ge[o>>12&63],r>1&&(t+=ge[o>>6&63]),r>2&&(t+=ge[o&63])}return t}function Vo(e){if(e.length%4===1)return null;let t=[],n=0,r=0;for(let o of e){let i=ge.indexOf(o);if(i===-1)return null;n=n<<6|i,r+=6,r>=8&&(r-=8,t.push(n>>r&255),n&=(1<<r)-1)}return Uint8Array.from(t)}function Yo(e){let{settledAt:t,id:n}=bn.parse(e);return Bo(new TextEncoder().encode(H({id:n,settledAt:t})))}function Jo(e){let t=Vo(e);if(t===null)return null;let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{return null}let r=bn.safeParse(n);return r.success&&Yo(r.data)===e?r.data:null}var js=a.object({rows:a.array(Go).max(ln),next:a.string().nullable()}).strict().superRefine((e,t)=>{En(e.rows.map(De),t,["rows"]),e.next!==null&&e.rows.length===0&&d(t,["next"],"An empty page has no next page.");let n=e.next===null?null:Jo(e.next);e.next!==null&&n===null&&d(t,["next"],"The next position is a cursor encodeChangeFeedCursor wrote.");let r=e.rows[e.rows.length-1];n!==null&&r!==void 0&&($(n.settledAt,De(r))||$(De(r),n.settledAt))&&d(t,["next"],"The next position is the arriving state of the page's last row."),n!==null&&r?.kind==="readable"&&n.id!==r.item.stateId&&d(t,["next"],"The next position names the arriving state of the page's last readable row.")}),Ks=a.object({outcome:ro}).strict();var Bs=Object.freeze({integrityRun:"integrity_run",resyncRequired:"resync-required"});import{z as p}from"zod";var Cn=[{code:"DEPLOYMENT_DISABLED",status:503,errorCode:5035},{code:"RUN_ALREADY_ACTIVE",status:409,errorCode:4091},{code:"BASIS_INVALID",status:409,errorCode:4092},{code:"RUN_ALREADY_FINISHED",status:409,errorCode:4093},{code:"FORBIDDEN",status:403,errorCode:null}];var _n={INTEGRITY_TOMBSTONE_RETENTION_DAYS:{min:1,max:3650},INTEGRITY_FINDING_SAMPLE_LIMIT:{min:1,max:5e3},INTEGRITY_RUN_HEARTBEAT_TIMEOUT_SECONDS:{min:30,max:3600},INTEGRITY_RUN_RETENTION_COUNT:{min:2,max:100},POLICY_CONFLICT_MAX_TIE_GROUP_SIZE:{min:2,max:60},CHILD_TREE_MAX_NODES:{min:1,max:1e5},CHILD_TREE_MAX_TOTAL_BYTES:{min:1048576,max:4294967296},CHILD_TREE_MAX_SECONDS:{min:60,max:3600},ARCHIVE_MAX_MEMBER_BYTES:{min:65536,max:1073741824},ARCHIVE_MAX_COMPRESSION_RATIO:{min:10,max:1e4},ARCHIVE_READER_MAX_MEMORY_BYTES:{min:268435456,max:17179869184},ARCHIVE_READER_MAX_SECONDS:{min:10,max:3600}};var Xo=e=>{for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)},we=Xo(_n),Rn=e=>Object.hasOwn(we,e),In=(e,t)=>{let{min:n,max:r}=we[e];if(!Number.isInteger(t)||t<n||t>r)throw new RangeError(`${e} \u306F ${n}\u301C${r} \u306E\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)},qs=(e,t)=>{Rn(e)&&In(e,t)},Xs=(e,t)=>{if(!Rn(e))throw new TypeError(`The range table bounds no parameter named ${JSON.stringify(e)}.`);In(e,t)};var ct=p.enum(["QDRANT","NEO4J"]),Wo=p.enum(["PRODUCTION","VARIANT","LABEL"]),Tn=p.enum(["EXPECTED","LIVE","HISTORY","TOMBSTONE","AWAITING_SUCCESSOR","IN_FLIGHT","UNPLACED","UNRECORDED","UNREFERENCED","CHANGED_AFTER_START","PIPELINE_FAILED","PROJECTION_REFUSED","ORPHAN","TOMBSTONE_EXPIRED","UNPROPAGATED_DELETE","STALE_REVISION","MISPLACED","OUT_OF_TIER","UNMARKED_SUPERSEDED","FLAG_DRIFT","VARIANT_FLAG_DRIFT","DETACHED","UNKEYED","MISSING","COUNT_MISMATCH","UNPROJECTED","UNKEYED_ENTITY"]),Nn=Tn.exclude(["EXPECTED","LIVE","HISTORY"]),Zo=p.enum(["POINT","NODE","CHUNK","DOCUMENT"]),Qo=p.enum(["EXPECTED","HEALTHY","RETAINED","INFORMATIONAL","DISCREPANCY"]),ea=p.enum(["NONE","PURGE","FLAG","REPROJECT"]),P=(e,t)=>Object.freeze({disposition:e,repairAction:t}),ta=Object.freeze({EXPECTED:P("EXPECTED","NONE"),LIVE:P("HEALTHY","NONE"),HISTORY:P("RETAINED","NONE"),TOMBSTONE:P("RETAINED","NONE"),AWAITING_SUCCESSOR:P("RETAINED","NONE"),IN_FLIGHT:P("INFORMATIONAL","NONE"),UNPLACED:P("INFORMATIONAL","NONE"),UNRECORDED:P("INFORMATIONAL","NONE"),UNREFERENCED:P("INFORMATIONAL","NONE"),CHANGED_AFTER_START:P("INFORMATIONAL","NONE"),PIPELINE_FAILED:P("INFORMATIONAL","NONE"),PROJECTION_REFUSED:P("INFORMATIONAL","NONE"),ORPHAN:P("DISCREPANCY","PURGE"),TOMBSTONE_EXPIRED:P("DISCREPANCY","PURGE"),UNPROPAGATED_DELETE:P("DISCREPANCY","FLAG"),STALE_REVISION:P("DISCREPANCY","PURGE"),MISPLACED:P("DISCREPANCY","PURGE"),OUT_OF_TIER:P("DISCREPANCY","PURGE"),UNMARKED_SUPERSEDED:P("DISCREPANCY","FLAG"),FLAG_DRIFT:P("DISCREPANCY","REPROJECT"),VARIANT_FLAG_DRIFT:P("DISCREPANCY","NONE"),DETACHED:P("DISCREPANCY","PURGE"),UNKEYED:P("DISCREPANCY","PURGE"),MISSING:P("DISCREPANCY","REPROJECT"),COUNT_MISMATCH:P("DISCREPANCY","REPROJECT"),UNPROJECTED:P("DISCREPANCY","REPROJECT"),UNKEYED_ENTITY:P("DISCREPANCY","NONE")}),na=p.enum(["SCAN","REPAIR"]),ra=p.enum(["RUNNING","COMPLETED","FAILED","CANCELLED","ABANDONED"]),oa=p.enum(["CONSISTENT","INCONSISTENT","UNDETERMINED"]),aa=p.enum(["QDRANT","NEO4J","DOCUMENTS"]),ia=p.enum(["APPLIED","SKIPPED","FAILED"]),sa=p.enum(["RECLASSIFIED","IN_FLIGHT","DESTINATION_PENDING","BASIS_EXHAUSTED","PROJECTION_REFUSED","PIPELINE_FAILED","UNRECORDED","OUTSIDE"]),Dn=100,K=p.number().int().nonnegative(),ke=p.number().int().min(300).max(599),st=["repairedCount","repairFailedCount","repairSkippedCount"],On=p.string().regex(/^[0-9a-f]{64}$/,"A store fingerprint is 64 lowercase hexadecimal digits."),xn=we.INTEGRITY_TOMBSTONE_RETENTION_DAYS,la=p.object({runUid:ie,mode:na,status:ra,requestedBy:p.string().min(1),executor:p.string().min(1),basisRunUid:ie.nullable(),storeFingerprint:On,tombstoneRetentionDays:p.number().int().min(xn.min).max(xn.max),startedAt:N,finishedAt:N.nullable(),verdict:oa.nullable(),errorClass:p.string().min(1).nullable(),reprojectDocuments:K.nullable(),reprojectRebuildDocuments:K.nullable()}).strict(),ca=(e,t)=>{let n=e.status==="COMPLETED";e.mode==="REPAIR"!=(e.basisRunUid!==null)&&d(t,["basisRunUid"],"A REPAIR run names its basis SCAN run, and a SCAN run names none."),n!==(e.verdict!==null)&&d(t,["verdict"],"Only a COMPLETED run has a verdict."),n!==(e.reprojectDocuments!==null)&&d(t,["reprojectDocuments"],"Only a COMPLETED run has the count of documents to re-project.");let{reprojectDocuments:r,reprojectRebuildDocuments:o}=e;r===null||o===null?r!==o&&d(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are counted together with the documents it re-projects."):o>r&&d(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are no more than the documents it re-projects."),e.status==="RUNNING"!=(e.finishedAt===null)&&d(t,["finishedAt"],"Only a RUNNING run has not finished."),e.finishedAt!==null&&$(e.finishedAt,e.startedAt)&&d(t,["finishedAt"],"A run does not finish before it starts."),(e.status==="FAILED"||e.status==="ABANDONED")!=(e.errorClass!==null)&&d(t,["errorClass"],"Only a FAILED or ABANDONED run names an error class.")},dt=la.superRefine(ca),da=p.object({store:ct,scopeKey:p.string().min(1),scopeRole:Wo,itemClass:Tn,unit:Zo,disposition:Qo,repairAction:ea,itemCount:K.nullable(),unmeasuredReason:p.string().min(1).nullable(),measuredAt:N.nullable(),repairedCount:K.nullable(),repairFailedCount:K.nullable(),repairSkippedCount:K.nullable()}).strict(),ua=(e,t)=>{let n=ta[e.itemClass];e.disposition!==n.disposition&&d(t,["disposition"],`A ${e.itemClass} quantity is ${n.disposition}.`),e.repairAction!==n.repairAction&&d(t,["repairAction"],`A repair's action on ${e.itemClass} items is ${n.repairAction}.`);let r=e.itemCount===null;r!==(e.unmeasuredReason!==null)&&d(t,["unmeasuredReason"],"An unmeasured quantity (itemCount null) has a reason, and a measured one has none."),r!==(e.measuredAt===null)&&d(t,["measuredAt"],"Only a measured quantity has a measurement time.");let{repairedCount:o,repairFailedCount:i,repairSkippedCount:s}=e;if(o===null||i===null||s===null){if(st.some(l=>e[l]!==null))for(let l of st)e[l]===null&&d(t,[l],"The repaired, failed and skipped counts are recorded together or not at all.");return}e.repairAction==="NONE"&&d(t,["repairAction"],"Only a class with a repair action carries repair counts."),e.itemCount!==null&&o+i+s>e.itemCount&&d(t,["itemCount"],"The repaired, failed and skipped counts together do not exceed the measured count.")},pa=da.superRefine(ua),ma=p.object({run:dt,phase:aa.nullable(),phaseScope:p.string().min(1).nullable(),phaseDone:K.nullable(),phaseTotal:K.nullable(),heartbeatAt:N,isStale:p.boolean(),staleAfter:N,cancelRequestedAt:N.nullable()}).strict(),fa=(e,t)=>{if(e.run.status!=="RUNNING"&&d(t,["run","status"],"The active run is a RUNNING run."),$(e.heartbeatAt,e.run.startedAt)&&d(t,["heartbeatAt"],"A run's heartbeat is not earlier than its start."),N.safeParse(e.heartbeatAt).success&&N.safeParse(e.staleAfter).success&&!$(e.heartbeatAt,e.staleAfter)&&d(t,["staleAfter"],"A run's heartbeat goes stale only after it beat."),e.phase===null)for(let n of["phaseScope","phaseDone","phaseTotal"])e[n]!==null&&d(t,[n],"A run with no phase has no phase progress.");e.phase==="DOCUMENTS"&&e.phaseScope!==null&&d(t,["phaseScope"],"The DOCUMENTS phase scans no scope.")},ha=ma.superRefine(fa),ya=p.object({run:dt,quantities:p.array(pa),previousStoreFingerprint:On.nullable()}).strict(),ga=(e,t)=>{e.run.status!=="COMPLETED"&&d(t,["run","status"],"The last completed run is a COMPLETED run.");let n=new Set;for(let[r,o]of e.quantities.entries()){let i=JSON.stringify([o.store,o.scopeKey,o.itemClass]);if(n.has(i)&&d(t,["quantities",r],"A run records each (store, scope, class) cell once."),n.add(i),e.run.mode==="SCAN")for(let s of st)o[s]!==null&&d(t,["quantities",r,s],"A SCAN run repairs nothing, so its quantities carry no repair counts.")}},Sa=["FAILED","CANCELLED","ABANDONED"],Ea=p.object({run:dt,repairAppliedItems:K.nullable(),hasNewerRepair:p.boolean()}).strict(),ba=(e,t)=>{Sa.includes(e.run.status)||d(t,["run","status"],"A newer unsuccessful run is FAILED, CANCELLED or ABANDONED."),e.run.mode==="SCAN"&&e.repairAppliedItems!==null&&d(t,["repairAppliedItems"],"A SCAN run applies nothing."),e.run.mode==="REPAIR"&&!e.hasNewerRepair&&d(t,["hasNewerRepair"],"An unsuccessful REPAIR run is itself a repair newer than the last completed run.")},rl=p.object({readAt:N,lastCompleted:ya.superRefine(ga).nullable(),active:ha.nullable(),newerUnsuccessful:Ea.superRefine(ba).nullable()}).strict(),Ca=p.object({sequence:p.number().int().min(1),itemKey:p.string().min(1),metadataId:p.number().int().positive().nullable(),fileUri:p.string().nullable(),revision:p.number().int().nullable(),observed:p.record(p.string(),p.unknown()),repairOutcome:ia.nullable(),repairErrorClass:p.string().min(1).nullable(),repairSkipReason:sa.nullable()}).strict(),_a=(e,t)=>{e.repairOutcome==="FAILED"!=(e.repairErrorClass!==null)&&d(t,["repairErrorClass"],"Only a FAILED finding names an error class."),e.repairOutcome==="SKIPPED"!=(e.repairSkipReason!==null)&&d(t,["repairSkipReason"],"Only a SKIPPED finding names a skip reason.")},Ra=Ca.superRefine(_a),ol=p.object({sotDomain:p.string().nullable()}).passthrough(),Ia=p.object({rows:p.array(Ra),nextAfter:p.number().int().min(1).nullable(),recordedCount:K,totalCount:K.nullable()}).strict(),xa=(e,t)=>{for(let[n,r]of e.rows.entries()){let o=e.rows[n-1];o!==void 0&&r.sequence<=o.sequence&&d(t,["rows",n,"sequence"],"A page lists its rows in ascending sequence.")}e.nextAfter!==null&&e.nextAfter!==e.rows.at(-1)?.sequence&&d(t,["nextAfter"],"The next page starts after the sequence of this page's last row.")},al=Ia.superRefine(xa),il=p.object({runUid:ie,store:ct,scopeKey:p.string().min(1),itemClass:Nn,after:p.number().int().min(1).optional(),limit:p.number().int().min(1).max(Dn)}).strict(),sl=p.object({runUid:ie,store:ct,scopeKey:p.string().min(1),itemClass:Nn.extract(["UNRECORDED"]),after:p.number().int().min(1).optional()}).strict(),Aa=p.object({requeued:K,skipped:p.array(p.object({metadataId:p.number().int().min(1),reason:p.string().min(1)}).strict()),nextAfter:p.number().int().min(1).nullable()}).strict(),ll=Aa.superRefine(xe(Dn)),ut=p.enum(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),An=p.enum(["start","cancel"]),Ta=ut.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","FORBIDDEN","UPSTREAM_FAILED"]),Na=ut.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),lt={start:Ta,cancel:Na},Da=p.object({code:ut.exclude(["UPSTREAM_FAILED"]),status:ke,errorCode:p.number().int().nullable()}).strict(),Pn=Object.freeze(p.array(Da).parse(Cn).map(e=>Object.freeze(e))),Oa=(e,t)=>{e.code==="UPSTREAM_FAILED"||e.code==="FORBIDDEN"&&e.status===null||Pn.some(n=>n.code===e.code&&n.status===e.status)||d(t,["status"],`A ${e.code} failure carries the status of its row in the code table.`)},cl=p.discriminatedUnion("command",[p.object({command:An.extract(["start"]),code:lt.start,status:ke.nullable()}).strict(),p.object({command:An.extract(["cancel"]),code:lt.cancel,status:ke.nullable()}).strict()]).superRefine(Oa),dl=(e,t,n)=>{let r=lt[e],o=Pn.find(i=>i.status===t&&(i.errorCode===null||i.errorCode===n)&&r.safeParse(i.code).success);return o===void 0?"UPSTREAM_FAILED":o.code},ul=p.discriminatedUnion("ok",[p.object({ok:p.literal(!0),runUid:ie}).strict(),p.object({ok:p.literal(!1),status:ke,errorCode:p.number().int().nullable()}).strict()]);function Pa(e){let t=[];for(let r=0;r<e.length;r++){t.push(r);let o=e.charCodeAt(r);o>=55296&&o<=56319&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320&&r++}t.push(e.length);let n=t.length-1;return{length:n,slice(r,o){if(!(Number.isInteger(r)&&Number.isInteger(o))||r<0||r>o)throw new RangeError(`A code-point span is [charStart, charEnd) with 0 <= charStart <= charEnd: [${r}, ${o})`);return o>n?null:e.slice(t[r],t[o])}}}var wa=e=>e.replace(/\s/gu,"");function ee(e,t){let n=new Map,r=i=>{let s=new Int32Array(i.length);return i.forEach((l,c)=>{let h=n.get(l);h===void 0&&(h=n.size,n.set(l,h)),s[c]=h}),s};return{old:r(e),new:r(t),alphabetSize:n.size}}function Fe(e,t,n,r){if(r===0)return;let o=e[e.length-1];if(o!==void 0&&o.oldStart+o.length===t&&o.newStart+o.length===n){o.length+=r;return}e.push({oldStart:t,newStart:n,length:r})}function wn(e,t,n,r,o,i,s){let l=0;for(;n+l<r&&o+l<i&&e[n+l]===t[o+l];)l++;Fe(s,n,o,l);let c=0;for(;r-c>n+l&&i-c>o+l&&e[r-1-c]===t[i-1-c];)c++;return{oldLow:n+l,oldHigh:r-c,newLow:o+l,newHigh:i-c,suffix:c}}function ka(e,t,n){let{oldLow:r,oldHigh:o,newLow:i,newHigh:s}=n,l=o-r,c=s-i,h=Math.ceil((l+c)/2),u=h,y=2*h+2,E=new Int32Array(y).fill(-1),A=new Int32Array(y).fill(-1);E[u+1]=0,A[u+1]=0;let b=l-c,O=b%2!==0,w=0,g=0,D=0,f=0;for(let _=0;_<h;_++){for(let T=-_+w;T<=_-g;T+=2){let I=u+T,x=T===-_||T!==_&&E[I-1]<E[I+1]?E[I+1]:E[I-1]+1,v=x-T;for(;x<l&&v<c&&e[r+x]===t[i+v];)x++,v++;if(E[I]=x,x>l)g+=2;else if(v>c)w+=2;else if(O){let U=u+b-T;if(U>=0&&U<y&&A[U]!==-1&&x>=l-A[U])return{kind:"split",oldSplit:r+x,newSplit:i+v}}}for(let T=-_+D;T<=_-f;T+=2){let I=u+T,x=T===-_||T!==_&&A[I-1]<A[I+1]?A[I+1]:A[I-1]+1,v=x-T;for(;x<l&&v<c&&e[o-1-x]===t[s-1-v];)x++,v++;if(A[I]=x,x>l)f+=2;else if(v>c)D+=2;else if(!O){let U=u+b-T;if(U>=0&&U<y&&E[U]!==-1){let C=E[U];if(C>=l-x)return{kind:"split",oldSplit:r+C,newSplit:i+u+C-U}}}}}return{kind:"disjoint"}}function te(e,t){let n=[],r=[{kind:"region",oldLow:0,oldHigh:e.length,newLow:0,newHigh:t.length}];for(let o=r.pop();o!==void 0;o=r.pop()){if(o.kind==="run"){Fe(n,o.oldStart,o.newStart,o.length);continue}let i=wn(e,t,o.oldLow,o.oldHigh,o.newLow,o.newHigh,n);if(r.push({kind:"run",oldStart:i.oldHigh,newStart:i.newHigh,length:i.suffix}),i.oldLow===i.oldHigh||i.newLow===i.newHigh)continue;let s=ka(e,t,i);s.kind==="split"&&(r.push({kind:"region",oldLow:s.oldSplit,oldHigh:i.oldHigh,newLow:s.newSplit,newHigh:i.newHigh}),r.push({kind:"region",oldLow:i.oldLow,oldHigh:s.oldSplit,newLow:i.newLow,newHigh:s.newSplit}))}return n}function kn(e,t,n){let r=Math.ceil(t.length/32),o=new Array(n);t.forEach((l,c)=>{let h=o[l];h===void 0&&(h=new Uint32Array(r),o[l]=h),h[c>>>5]=(h[c>>>5]|1<<(c&31))>>>0});let i=new Uint32Array(r).fill(4294967295);for(let l of e){let c=o[l];if(c===void 0)continue;let h=0;for(let u=0;u<r;u++){let y=i[u],E=(y&c[u])>>>0,A=y+E+h;h=A>4294967295?1:0,i[u]=(A>>>0|y&~c[u])>>>0}}let s=0;for(let l=0;l<t.length;l++)s+=i[l>>>5]>>>(l&31)&1;return t.length-s}function Fa(e,t,n){if(e.occurrences!==t.occurrences)return e.occurrences<t.occurrences;if(e.length!==t.length)return e.length>t.length;let r=Math.abs(2*e.oldStart+e.length-n),o=Math.abs(2*t.oldStart+t.length-n);return r!==o?r<o:e.newStart<t.newStart||e.newStart===t.newStart&&e.oldStart<t.oldStart}function Fn(e,t){let{old:n,new:r,alphabetSize:o}=e,i=new Int32Array(o),s=new Int32Array(o),l=new Int32Array(o).fill(-1),c=new Int32Array(n.length),h=[],u=[{kind:"region",oldLow:0,oldHigh:n.length,newLow:0,newHigh:r.length}];for(let y=u.pop();y!==void 0;y=u.pop()){if(y.kind==="run"){Fe(h,y.oldStart,y.newStart,y.length);continue}let E=wn(n,r,y.oldLow,y.oldHigh,y.newLow,y.newHigh,h),A={kind:"run",oldStart:E.oldHigh,newStart:E.newHigh,length:E.suffix},{oldLow:b,oldHigh:O,newLow:w,newHigh:g}=E;if(b===O||w===g){u.push(A);continue}for(let I=O-1;I>=b;I--){let x=n[I];i[x]++,c[I]=l[x],l[x]=I}let D={best:null},f=I=>{(D.best===null||Fa(I,D.best,b+O))&&(D.best=I)},_=new Map;for(let I=w;I<g;I++){let x=r[I],v=i[x];if(!(v===0||v>t.maxOccurrences||D.best!==null&&v>D.best.occurrences))for(let U=l[x];U!==-1;U=c[U]){let C=_.get(I-U);if(C!==void 0&&I>=C.newStart&&I<C.newEnd){v<C.occurrences&&(C.occurrences=v,f({occurrences:v,oldStart:C.oldStart,newStart:C.newStart,length:C.newEnd-C.newStart}));continue}let M=U,F=I;for(;M>b&&F>w&&n[M-1]===r[F-1];)M--,F--;let j=U-M+1;for(;M+j<O&&F+j<g&&n[M+j]===r[F+j];)j++;_.set(I-U,{oldStart:M,newStart:F,newEnd:F+j,occurrences:v}),f({occurrences:v,oldStart:M,newStart:F,length:j})}}let T=D.best;T!==null?(u.push(A),u.push({kind:"region",oldLow:T.oldStart+T.length,oldHigh:O,newLow:T.newStart+T.length,newHigh:g}),u.push({kind:"run",oldStart:T.oldStart,newStart:T.newStart,length:T.length}),u.push({kind:"region",oldLow:b,oldHigh:T.oldStart,newLow:w,newHigh:T.newStart})):(La(n,r,E,i,s,t.cellBound,h),u.push(A));for(let I=b;I<O;I++){let x=n[I];i[x]=0,l[x]=-1}}return h}function La(e,t,n,r,o,i,s){let{oldLow:l,oldHigh:c,newLow:h,newHigh:u}=n;if((c-l)*(u-h)>i)return;for(let b=h;b<u;b++)o[t[b]]++;let y=[];for(let b=l;b<c;b++)o[e[b]]>0&&y.push(b);let E=[];for(let b=h;b<u;b++)r[t[b]]>0&&E.push(b),o[t[b]]=0;let A=te(Int32Array.from(y,b=>e[b]),Int32Array.from(E,b=>t[b]));for(let b of A)for(let O=0;O<b.length;O++)Fe(s,y[b.oldStart+O],E[b.newStart+O],1)}function Ln(e,t,n){let r=[],o=0,i=0;for(let s of[...n,{oldStart:e,newStart:t,length:0}])(s.oldStart>o||s.newStart>i)&&r.push({oldStart:o,oldEnd:s.oldStart,newStart:i,newEnd:s.newStart}),o=s.oldStart+s.length,i=s.newStart+s.length;return r}function pt(e,t,n,r){let o=new Map;for(let s of t){let l=r(s);l!==null&&o.set(l,[...o.get(l)??[],s])}let i=[];for(let s of e){let l=n(s),c=l===null?void 0:o.get(l)?.shift();c!==void 0&&i.push([s,c])}return i}function vn(e,t){let n=new Map;for(let r of e){let o=t[r].clause;o!==null&&n.set(o,(n.get(o)??0)+1)}return n}var Y=e=>e.flatMap((t,n)=>t===null?[n]:[]);function mt(e,t){let n=e?.children??[],r=t?.children??[],o=ee(n.map(f=>f.hash),r.map(f=>f.hash)),i=n.map(()=>null),s=r.map(()=>null),l=[],c=n.map(()=>0),h=r.map(()=>0);for(let f of te(o.old,o.new))for(let _=0;_<f.length;_++)i[f.oldStart+_]=f.newStart+_,s[f.newStart+_]=f.oldStart+_;let u=0;n.forEach((f,_)=>{c[_]=u,u+=i[_]===null?0:1}),u=0,r.forEach((f,_)=>{h[_]=u,s[_]!==null&&(l.push(_),u++)});let y=[],E=(f,_,T)=>{for(let[I,x]of f)i[I]=x,s[x]=I,y.push({entry:{kind:_,pairing:T,oldPosition:I,newPosition:x},order:[x,1,x]})},A=f=>n[f],b=f=>r[f];E(pt(Y(i),Y(s),f=>A(f).hash,f=>b(f).hash),"MOVED",null);let O=vn(Y(i),n),w=vn(Y(s),r),g=f=>f.clause!==null&&O.get(f.clause)===1&&w.get(f.clause)===1?f.clause:null;E(pt(Y(i),Y(s),f=>g(A(f)),f=>g(b(f))),"MODIFIED","clause"),E(pt(Y(i),Y(s),f=>JSON.stringify([c[f],A(f).breadcrumbs]),f=>JSON.stringify([h[f],b(f).breadcrumbs])),"MODIFIED","breadcrumbs");for(let f of Y(i)){let _=c[f],T=_===0?0:l[_-1]+1;y.push({entry:{kind:"REMOVED",pairing:null,oldPosition:f,newPosition:null},order:[T,0,f]})}for(let f of Y(s))y.push({entry:{kind:"ADDED",pairing:null,oldPosition:null,newPosition:f},order:[f,1,f]});y.sort((f,_)=>f.order[0]-_.order[0]||f.order[1]-_.order[1]||f.order[2]-_.order[2]);let D=f=>y.filter(({entry:_})=>_.kind===f).length;return{entries:y.map(({entry:f})=>f),stats:{added:D("ADDED"),removed:D("REMOVED"),modified:D("MODIFIED"),moved:D("MOVED"),unchanged:l.length}}}var Le=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ue=(e,t)=>`${e}/${String(t).replace(/~/g,"~0").replace(/\//g,"~1")}`;function ft(e,t,n,r,o){H(t)!==H(n)&&(Le(t)&&Le(n)?va(e,t,n,r,o):Array.isArray(t)&&Array.isArray(n)?Ma(e,t,n,r,o):r.push({op:"replace",path:e,value:n,previous:t}))}function va(e,t,n,r,o){let i=[...new Set([...Object.keys(t),...Object.keys(n)])].sort(q);for(let s of i){let l=ue(e,s);Object.hasOwn(n,s)?Object.hasOwn(t,s)?ft(l,t[s],n[s],r,o):r.push({op:"add",path:l,value:n[s]}):r.push({op:"remove",path:l,previous:t[s]})}}function Ma(e,t,n,r,o){let i=ee(t.map(H),n.map(H)),s=0;for(;s<t.length&&s<n.length&&i.old[s]===i.new[s];)s++;let l=0;for(;l<t.length-s&&l<n.length-s&&i.old[t.length-1-l]===i.new[n.length-1-l];)l++;let c=(t.length-s-l)*(n.length-s-l);if(c>o.remaining){r.push({op:"replace",path:e,value:n,previous:t});return}o.remaining-=c;let h=0,u=0,y=0;for(let E of[...te(i.old,i.new),{oldStart:t.length,newStart:n.length,length:0}]){let A=t.slice(u,E.oldStart),b=n.slice(y,E.newStart),O=Math.min(A.length,b.length);for(let w=0;w<O;w++){let g=A[w],D=b[w];Le(g)&&Le(D)||Array.isArray(g)&&Array.isArray(D)?ft(ue(e,h),g,D,r,o):(r.push({op:"remove",path:ue(e,h),previous:g}),r.push({op:"add",path:ue(e,h),value:D})),h++}for(let w of A.slice(O))r.push({op:"remove",path:ue(e,h),previous:w});for(let w of b.slice(O))r.push({op:"add",path:ue(e,h),value:w}),h++;h+=E.length,u=E.oldStart+E.length,y=E.newStart+E.length}}function ht(e,t){let n=[];return ft("",e,t,n,{remaining:an}),n}function Mn(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="object"||n===null||Array.isArray(n))continue;let{start:r,end:o,page_number:i}=n;Number.isInteger(r)&&Number.isInteger(o)&&Number.isInteger(i)&&t.push({start:r,end:o,pageNumber:i})}return t.sort((n,r)=>n.start-r.start)}function yt(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].start<=t?n=i+1:r=i}let o=e[n-1];return o!==void 0&&t<o.end?o.pageNumber:null}function Un(e){let t=[],n=[],r={LF:0,CRLF:0,CR:0},o=0,i=0,s=0;for(let u=0;u<e.length;){let y=e.charCodeAt(u);if(y===10||y===13){t.push(e.slice(o,u)),n.push(s);let E=y===13&&e.charCodeAt(u+1)===10?2:1;r[E===2?"CRLF":y===13?"CR":"LF"]++,u+=E,i+=E,o=u,s=i;continue}u+=y>=55296&&y<=56319&&(e.charCodeAt(u+1)&64512)===56320?2:1,i++}o<e.length&&(t.push(e.slice(o)),n.push(s));let l=r.LF+r.CRLF+r.CR,c=["LF","CRLF","CR"].filter(u=>r[u]>0),h=l===0?"NONE":c.length===1?c[0]:"MIXED";return{lines:t,starts:n,lineEnding:h,finalNewline:l>0&&o===e.length}}var zn=null;function Hn(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>767)return!1;return!0}function Et(e){return Hn(e)?e.split(""):(zn??=new Intl.Segmenter("und",{granularity:"grapheme"}),Array.from(zn.segment(e),t=>t.segment))}function gt(e){return Hn(e)?e.length:Et(e).length}function Ua(e,t,n){let r=e.length+t.length;if(n.exhausted||e.length>nt||t.length>nt||r===0)return null;let o=ee(e,t),i=kn(o.old,o.new,o.alphabetSize);if(2*i/r<rt||r-2*i>rn)return null;let s=r*(r-2*i);if(s>n.remaining)return n.exhausted=!0,null;n.remaining-=s;let l=te(o.old,o.new),c=[],h=0,u=0;for(let g of[...l,{oldStart:e.length,newStart:t.length,length:0}])(g.oldStart>h||g.newStart>u)&&c.push({equal:!1,oldStart:h,oldEnd:g.oldStart,newStart:u,newEnd:g.newStart}),g.length>0&&c.push({equal:!0,oldStart:g.oldStart,oldEnd:g.oldStart+g.length,newStart:g.newStart,newEnd:g.newStart+g.length}),h=g.oldStart+g.length,u=g.newStart+g.length;let y=[];c.forEach((g,D)=>{let f=y[y.length-1],_=f!==void 0&&!f.equal,T=g.equal&&g.oldEnd-g.oldStart<=1&&_&&D+1<c.length;if(_&&(T||!g.equal)){f.oldEnd=g.oldEnd,f.newEnd=g.newEnd;return}y.push({...g})});let E=0,A=0,b=0,O=[],w=[];for(let g of y){let D=e.slice(g.oldStart,g.oldEnd).join(""),f=t.slice(g.newStart,g.newEnd).join("");if(g.equal){E+=g.oldEnd-g.oldStart,O.push({kind:"equal",text:D}),w.push({kind:"equal",text:f});continue}A+=g.oldEnd-g.oldStart,b+=g.newEnd-g.newStart,D!==""&&O.push({kind:"removed",text:D}),f!==""&&w.push({kind:"added",text:f})}return 2*E/r<rt?null:{oldSegments:O,newSegments:w,removed:A,added:b}}var jn={old:[],new:[]};function Se(e){return e.filter(([,t,n])=>H(t)!==H(n)).map(([t,n,r])=>({field:t,before:n,after:r}))}var St=(e,t)=>t===""?[]:[{kind:e,text:t}];function za(e,t,n){let r=[],o=(l,c)=>({kind:"context",oldNumber:l+1,newNumber:c+1,page:yt(n.pages.new,n.newText.starts[c]),segments:St("equal",n.newText.lines[c])}),i=t.oldStart,s=t.newStart;for(let l of e){for(;i<l.oldStart;i++,s++)r.push(o(i,s));for(let c=l.oldStart;c<l.oldEnd;c++){let h=n.oldText.lines[c];r.push({kind:"removed",oldNumber:c+1,newNumber:null,page:yt(n.pages.old,n.oldText.starts[c]),segments:n.removedSegments.get(c)??St("removed",h)})}for(let c=l.newStart;c<l.newEnd;c++){let h=n.newText.lines[c];r.push({kind:"added",oldNumber:null,newNumber:c+1,page:yt(n.pages.new,n.newText.starts[c]),segments:n.addedSegments.get(c)??St("added",h)})}i=l.oldEnd,s=l.newEnd}for(;i<t.oldEnd;i++,s++)r.push(o(i,s));return r}function bt(e,t,n,r){let o=Un(e??""),i=Un(t??""),s=Se([["present",e!==null,t!==null],["lineEnding",o.lineEnding,i.lineEnding],["finalNewline",o.finalNewline,i.finalNewline]]),l=Fn(ee(o.lines,i.lines),{maxOccurrences:tn,cellBound:nn}),c=Ln(o.lines.length,i.lines.length,l),h=new Map,u=new Map,y={remaining:on,exhausted:!1},E=0,A=0,b=0,O=0,w=0,g=0;for(let C of c){b+=C.oldEnd-C.oldStart,O+=C.newEnd-C.newStart;let M=Math.min(C.oldEnd-C.oldStart,C.newEnd-C.newStart);for(let F=0;C.oldStart+F<C.oldEnd||C.newStart+F<C.newEnd;F++){let j=C.oldStart+F,G=C.newStart+F;if(F>=M){let me=j<C.oldEnd?gt(o.lines[j]):0,re=G<C.newEnd?gt(i.lines[G]):0;w+=me,g+=re,E+=me,A+=re;continue}let J=Et(o.lines[j]),W=Et(i.lines[G]);w+=J.length,g+=W.length;let Z=Ua(J,W,y);if(Z!==null){h.set(j,Z.oldSegments),u.set(G,Z.newSegments),E+=Z.removed,A+=Z.added;continue}E+=J.length,A+=W.length}}let D=0;for(let C of l)for(let M=C.oldStart;M<C.oldStart+C.length;M++)D+=gt(o.lines[M]);let f=D+w,_=D+g,T={linesAdded:O,linesRemoved:b,linesUnchanged:o.lines.length-b,charsAdded:A,charsRemoved:E,similarity:f+_===0?null:2*(f-E)/(f+_)},I=r==="whole"?Math.max(o.lines.length,i.lines.length):r,x=[];for(let C of c){let M=x[x.length-1],F=M?.[M.length-1];M!==void 0&&F!==void 0&&C.oldStart-F.oldEnd<=2*I?M.push(C):x.push([C])}let v={oldText:o,newText:i,pages:n,removedSegments:h,addedSegments:u},U=x.map((C,M)=>{let F=C[0],j=C[C.length-1],G=Math.max(0,F.oldStart-I),J=F.newStart-(F.oldStart-G),W=Math.min(o.lines.length,j.oldEnd+I),Z=j.newEnd+(W-j.oldEnd),me=za(C,{oldStart:G,oldEnd:W,newStart:J},v);return{hunk:M,oldStart:W>G?G+1:G,oldLines:W-G,newStart:Z>J?J+1:J,newLines:Z-J,firstPage:me[0].page,linesAdded:C.reduce((re,fe)=>re+fe.newEnd-fe.newStart,0),linesRemoved:C.reduce((re,fe)=>re+fe.oldEnd-fe.oldStart,0),lines:me}});return{attributes:s,stats:T,hunks:U}}function ve(e,t){let n=bt(e.body,t.body,{old:Mn(e.pageOffsets),new:Mn(t.pageOffsets)},tt),r=Se([["mime",e.mime,t.mime],["source",e.source,t.source],["isTruncated",e.isTruncated,t.isTruncated],["pageOffsets",e.pageOffsets,t.pageOffsets]]);return{...n,attributes:[...r,...n.attributes]}}function Me(e,t){return bt(e,t,jn,tt)}function Ha(e,t){return bt(e,t,jn,"whole")}function Ue(e){return{attributes:[...e.attributes],stats:e.stats,hunks:e.hunks.map(({lines:t,...n})=>n)}}function ja(e,t,n,r){let o=Number.isInteger(t)&&t>=0?e.hunks[t]:void 0;if(o===void 0)throw new RangeError(`The diff has no hunk ${t}.`);if(!Number.isInteger(n)||n<0||n>=o.lines.length)throw new RangeError(`Hunk ${t} has no line at offset ${n}.`);if(!gn.safeParse(r).success)throw new RangeError(`A line page holds 1 to the page maximum lines, not ${r}.`);let i=Math.min(n+r,o.lines.length);return{lines:o.lines.slice(n,i),next:i<o.lines.length?i:null}}function ze(e,t,n){let r=[...e].sort(t);for(let o=1;o<r.length;o++)if(t(r[o-1],r[o])===0)throw new RangeError(`A facet set holds the key ${JSON.stringify(n(r[o]))} more than once.`);return r}function Kn(e,t,n,r){let o=0,i=0;for(;o<e.length||i<t.length;){let s=e[o],l=t[i],c=s===void 0?1:l===void 0?-1:n(s,l);r(c<=0?s:null,c>=0?l:null),o+=c<=0?1:0,i+=c>=0?1:0}}function Ct(e,t){let n=[],r=[],o=0;return Kn(ze(e??[],q,String),ze(t??[],q,String),q,(i,s)=>{i!==null&&s!==null?o++:i!==null?r.push(i):n.push(s)}),{added:n,removed:r,unchangedCount:o}}function Gn(e,t,n){let r=[],o=[],i=[],s=0;return Kn(ze(e,n.compare,n.keyOf),ze(t,n.compare,n.keyOf),n.compare,(l,c)=>{if(l===null){r.push({key:n.keyOf(c),value:{...c}});return}if(c===null){o.push({key:n.keyOf(l),value:{...l}});return}let h=new Map(n.fieldsOf(c)),u=Se(n.fieldsOf(l).map(([y,E])=>[y,E,h.get(y)]));u.length===0?s++:i.push({key:n.keyOf(l),fields:u})}),{added:r,removed:o,modified:i,unchangedCount:s}}var Ka={compare:(e,t)=>q(e.labelKey,t.labelKey),keyOf:e=>e.labelKey,fieldsOf:e=>[["assignedBy",e.assignedBy],["confidenceScore",e.confidenceScore]]},Ga={compare:ot,keyOf:ae,fieldsOf:e=>[["mimeType",e.mimeType],["fileSize",e.fileSize],["textSha256",e.textSha256]]},_t=(e,t)=>Gn(e,t,Ka),Rt=(e,t)=>Gn(e,t,Ga);function Ee(e,t,n){return Se(n.map(r=>[r,e[r],t[r]]))}var Yn=["confidentialityLevel","departmentId","folderPath","createdBy"],Jn=["fileName","filePath","fileId","revision","revisionId","fileSize","mimeType","fileHash","mtime"],ne=(e,t)=>({facet:e,addedCount:null,removedCount:null,modifiedCount:null,movedCount:null,unchangedCount:null,charsAdded:null,charsRemoved:null,...t}),Bn=(e,t)=>ne(e,{addedCount:t.stats.linesAdded,removedCount:t.stats.linesRemoved,unchangedCount:t.stats.linesUnchanged,charsAdded:t.stats.charsAdded,charsRemoved:t.stats.charsRemoved});function Ba(e){switch(e.facet){case"classification":return ne("classification",{modifiedCount:Ee(e.from,e.to,Yn).length});case"metadata":return ne("metadata",{modifiedCount:Ee(e.from,e.to,Jn).length});case"labels":case"assets":{let t=e.facet==="labels"?_t(e.from,e.to):Rt(e.from,e.to);return ne(e.facet,{addedCount:t.added.length,removedCount:t.removed.length,modifiedCount:t.modified.length,unchangedCount:t.unchangedCount})}case"tags":{let t=Ct(e.from,e.to);return ne("tags",{addedCount:t.added.length,removedCount:t.removed.length,unchangedCount:t.unchangedCount})}case"structured_data":{let t=ht(e.from,e.to),n=r=>t.filter(o=>o.op===r).length;return ne("structured_data",{addedCount:n("add"),removedCount:n("remove"),modifiedCount:n("replace")})}case"text":return Bn("text",ve(e.from,e.to));case"summary":return Bn("summary",Me(e.from,e.to));case"chunks":{let{stats:t}=mt(e.from,e.to);return ne("chunks",{addedCount:t.added,removedCount:t.removed,modifiedCount:t.modified,movedCount:t.moved,unchangedCount:t.unchanged})}}}function Va(e){if(e.length===0)throw new RangeError("A change has at least one changed facet.");let t=new Set;for(let n of e){if(t.has(n.facet))throw new RangeError(`The ${n.facet} facet is given twice.`);if(t.add(n.facet),H(n.from)===H(n.to))throw new RangeError(`The ${n.facet} facet has equal values on both sides, so it did not change.`)}return[...e].sort((n,r)=>at(n.facet,r.facet)).map(Ba)}var Ya=(e,t)=>({index:e.index,charStart:e.charStart,charEnd:e.charEnd,page:e.page,sheet:e.sheet,slide:e.slide,startSec:e.startSec,endSec:e.endSec,breadcrumbs:e.breadcrumbs,tokenCount:e.tokenCount,fidelity:t});function Vn(e,t){let n=e.facets.chunks?.children.length??0;if(e.chunkFidelities.length!==n)throw new RangeError(`The ${t} state has ${n} child chunks but ${e.chunkFidelities.length} fidelity checks.`)}function Ja(e,t,n){let r=t.facets,o=n.facets;if(H(r[e])===H(o[e]))return{facet:e,change:"UNCHANGED"};switch(e){case"classification":return{facet:e,change:"CHANGED",fields:Ee(r.classification,o.classification,Yn)};case"metadata":return{facet:e,change:"CHANGED",fields:Ee(r.metadata,o.metadata,Jn)};case"labels":case"assets":{let i=e==="labels"?_t(r.labels,o.labels):Rt(r.assets,o.assets);return{facet:e,change:"CHANGED",added:[...i.added],removed:[...i.removed],modified:[...i.modified],unchangedCount:i.unchangedCount}}case"tags":{let i=Ct(r.tags,o.tags);return{facet:e,change:"CHANGED",added:[...i.added],removed:[...i.removed],unchangedCount:i.unchangedCount}}case"structured_data":return{facet:e,change:"CHANGED",operations:ht(r.structured_data,o.structured_data)};case"text":return{facet:e,change:"CHANGED",...Ue(ve(r.text,o.text))};case"summary":return{facet:e,change:"CHANGED",...Ue(Me(r.summary,o.summary))};case"chunks":{let i=mt(r.chunks,o.chunks),s=r.chunks?.children??[],l=o.chunks?.children??[],c=(h,u,y)=>y===null?null:Ya(h[y],u[y]);return{facet:e,change:"CHANGED",stats:i.stats,entries:i.entries.map((h,u)=>({entry:u,kind:h.kind,pairing:h.pairing,old:c(s,t.chunkFidelities,h.oldPosition),new:c(l,n.chunkFidelities,h.newPosition)})),textUnchangedChunkingChanged:r.text.body===o.text.body}}}}function $a(e,t){return Vn(e,"from"),Vn(t,"to"),{diffEngineVersion:en,facets:de.map(n=>Ja(n,e,t))}}import{z as k}from"zod";var qa=["caller_google_token","caller_identity","deployment"],Xa=["describe","name_children"],It="su",He=k.object({ja:k.string().regex(/\S/),en:k.string().regex(/\S/)}).strict();function $n(e){try{return new RegExp(`^(?:${e})$`,It)}catch{return null}}function qn(e){try{return new RegExp(e,It)}catch{return null}}function Wa(e){let t=new RegExp(`${e}|`,It).exec("");return t===null?0:t.length-1}var Za=k.object({scheme:k.string().regex(/^[a-z][a-z0-9+.-]{0,31}$/),title:He,description:He,uri_prefix:k.string(),input_pattern:k.string(),input_example:k.string(),input_hint:He,guidance:He,paste_patterns:k.array(k.string()),credential:k.enum(qa),capabilities:k.array(k.enum(Xa)),delivered_mime_type:k.string().min(1).nullable()}).strict().superRefine((e,t)=>{e.uri_prefix.startsWith(`${e.scheme}://`)||t.addIssue({code:k.ZodIssueCode.custom,path:["uri_prefix"],message:`The URI prefix does not start with ${e.scheme}://.`});let n=$n(e.input_pattern);n===null?t.addIssue({code:k.ZodIssueCode.custom,path:["input_pattern"],message:"The input pattern does not compile with the s and u flags."}):n.test(e.input_example)||t.addIssue({code:k.ZodIssueCode.custom,path:["input_example"],message:"The input example does not fully match the input pattern."}),e.paste_patterns.forEach((r,o)=>{qn(r)===null?t.addIssue({code:k.ZodIssueCode.custom,path:["paste_patterns",o],message:"The paste pattern does not compile with the s and u flags."}):Wa(r)!==1&&t.addIssue({code:k.ZodIssueCode.custom,path:["paste_patterns",o],message:"A paste pattern has exactly one capturing group, the identifier."})}),new Set(e.capabilities).size!==e.capabilities.length&&t.addIssue({code:k.ZodIssueCode.custom,path:["capabilities"],message:"A capability is declared twice."})}),Kl=k.object({sources:k.array(Za)}).strict().superRefine((e,t)=>{let n=e.sources.map(r=>r.scheme);new Set(n).size!==n.length&&t.addIssue({code:k.ZodIssueCode.custom,path:["sources"],message:"A scheme is registered twice."})});function Gl(e,t){let n=t.trim();return[...e].sort((r,o)=>o.uri_prefix.length-r.uri_prefix.length).find(r=>n.startsWith(r.uri_prefix))}function Bl(e,t){return $n(e.input_pattern)?.test(t)??!1}function Vl(e,t){for(let n of e)for(let r of n.paste_patterns){let o=qn(r)?.exec(t)?.[1];if(o!==void 0)return{source:n,identifier:o}}}var Xn=[{key:"enable_summary_generation",featureFlagKey:null,label:"\u8981\u7D04\u751F\u6210",readByPipeline:!1},{key:"enable_structured_extraction",featureFlagKey:null,label:"\u69CB\u9020\u5316\u62BD\u51FA",readByPipeline:!1},{key:"enable_asset_extraction",featureFlagKey:"ENABLE_ASSET_EXTRACTION",label:"\u30A2\u30BB\u30C3\u30C8\u62BD\u51FA",readByPipeline:!1},{key:"enable_vector_indexing",featureFlagKey:"ENABLE_VECTOR_INDEXING",label:"\u30D9\u30AF\u30C8\u30EB\u7D22\u5F15",readByPipeline:!0},{key:"enable_graph_indexing",featureFlagKey:"ENABLE_GRAPH_INDEXING",label:"\u30B0\u30E9\u30D5\u6295\u5F71",readByPipeline:!0}],Qa=new Set(Xn.map(e=>e.key));function Jl(e){return Qa.has(e)}function $l(e){let t=Xn.find(n=>n.key===e);if(t===void 0)throw new Error(`ENRICHMENT_STAGES does not carry ${e}; the canonical list and the key type have drifted apart.`);return t}var ql={pageSize:{min:1,max:200,default:50},topologyLabels:{min:1,max:24,default:24}};import{z as L}from"zod";var ei=["zip","7z","rar","pdf","ooxml","legacy_office"],Ql=L.enum(ei),Wn=["zipcrypto","aes","7z_aes","rar_encryption","pdf_user_password","pdf_owner_password","office_encryption"],ec=L.enum(Wn),ti=[...Wn,"strong_encryption"],tc=L.enum(ti),nc=Object.freeze({zipcrypto:"ZIP \u306E\u6697\u53F7 (ZipCrypto)",aes:"ZIP \u306E\u6697\u53F7 (AES)","7z_aes":"7z \u306E\u6697\u53F7 (AES-256)",rar_encryption:"RAR \u306E\u6697\u53F7",pdf_user_password:"PDF \u306E\u958B\u304F\u305F\u3081\u306E\u30D1\u30B9\u30EF\u30FC\u30C9",pdf_owner_password:"PDF \u306E\u5236\u9650\u306E\u30D1\u30B9\u30EF\u30FC\u30C9",office_encryption:"Office \u306E\u6697\u53F7",strong_encryption:"ZIP \u306E\u5F37\u3044\u6697\u53F7 (\u5916\u305B\u306A\u3044)"}),ni=["source_overwritten","copy_original","copy_promoted","child_decrypted"],rc=L.enum(ni),oc=Object.freeze({source_overwritten:"\u6E90\u3092\u89E3\u3044\u305F\u30D5\u30A1\u30A4\u30EB\u3067\u4E0A\u66F8\u304D\u3057\u305F",copy_original:"\u89E3\u3044\u305F\u5199\u3057\u3092\u539F\u672C\u306B\u3057\u3066\u3044\u308B",copy_promoted:"\u89E3\u3044\u305F\u5199\u3057\u3067\u6E90\u3092\u4E0A\u66F8\u304D\u3057\u305F (\u6607\u683C)",child_decrypted:"\u5B50\u306E\u7269\u3092\u89E3\u3044\u305F\u4E2D\u8EAB\u306B\u3057\u305F"}),ri=["permission_denied","immutable_source","foreign_application","local_source","format_changed"],ac=L.enum(ri),ic=Object.freeze({permission_denied:"\u6E90\u3078\u66F8\u304F\u6A29\u9650\u304C\u7121\u3044",immutable_source:"\u30E1\u30FC\u30EB\u306F\u5909\u3048\u3089\u308C\u306A\u3044",foreign_application:"\u5225\u306E\u30A2\u30D7\u30EA (\u65E5\u5831) \u306E\u7269",local_source:"\u30DB\u30B9\u30C8\u306E\u30ED\u30FC\u30AB\u30EB\u306E\u30D5\u30A1\u30A4\u30EB",format_changed:"\u66F8\u304D\u76F4\u305B\u306A\u3044\u66F8\u5F0F\u306A\u306E\u3067 ZIP \u306B\u3057\u305F"}),sc=e=>e==="permission_denied",lc=Object.freeze({passwordRequired:4225,protectionUnsupported:4226,sourceChanged:4094}),oi=["gmail","gdrive","gcs","file","daily-report"],cc=Object.freeze({gmail:"Gmail",gdrive:"Google \u30C9\u30E9\u30A4\u30D6",gcs:"Cloud Storage",file:"\u30ED\u30FC\u30AB\u30EB\u306E\u30D5\u30A1\u30A4\u30EB","daily-report":"\u65E5\u5831"}),ai=["glob","regex"],dc=Object.freeze({glob:"\u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9 (* \u3068 ?)",regex:"\u6B63\u898F\u8868\u73FE"}),be=Object.freeze({label:200,sender:320,subject:400,file_name:400,uri_prefix:2048}),uc=995,ii=2147483647,pc=e=>new TextEncoder().encode(e).length,si=e=>e.length,Zn=e=>L.string().min(1).refine(t=>si(t)<=e,{message:`Wider than the ${e} UTF-16 code units its column holds`}),je=e=>Zn(e).nullable(),li=L.object({sender:je(be.sender),subject:je(be.subject),file_name:je(be.file_name),uri_prefix:je(be.uri_prefix),source_kind:L.enum(oi).nullable(),syntax:L.enum(ai)}),mc=e=>e.sender===null&&e.subject===null&&e.file_name===null&&e.uri_prefix===null&&e.source_kind===null,Qn=L.object({password_id:L.number().int().positive(),label:Zn(be.label),conditions:li,priority:L.number().int().nonnegative().max(ii),is_active:L.boolean(),use_count:L.number().int().nonnegative(),last_used_at:N.nullable(),created_by:L.string().min(1),created_at:N,updated_by:L.string().min(1),updated_at:N}),fc=L.object({passwords:L.array(Qn)}),hc=L.object({passwords:L.array(Qn),timed_out:L.array(L.number().int().positive())});var pe=-1,X=0;function ci(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function gc(){let e=typeof globalThis<"u"&&globalThis.crypto?globalThis.crypto:typeof crypto<"u"?crypto:void 0;if(!e||typeof e.getRandomValues!="function")throw new Error("Cryptographically secure random number generator (crypto.getRandomValues) is required but not available.");let t=new Uint8Array(16);e.getRandomValues(t);let n=Date.now();if(n===pe){if(X++,X>4095){for(;Date.now()<=pe;);n=Date.now(),pe=n,X=(t[6]<<4|t[7]&15)&1023}}else n>pe?(pe=n,X=(t[6]<<4|t[7]&15)&1023):(n=pe,X++,X>4095&&(X=0));t[0]=Math.floor(n/1099511627776)&255,t[1]=Math.floor(n/4294967296)&255,t[2]=n>>>24&255,t[3]=n>>>16&255,t[4]=n>>>8&255,t[5]=n&255,t[6]=112|X>>>8&15,t[7]=X&255,t[8]=128|t[8]&63;let r=Array.from(t,i=>i.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function Sc(e){if(!ci(e))throw new Error(`Invalid RFC 9562 UUIDv7 string: "${e}"`);let t=e.slice(0,8)+e.slice(9,13),n=parseInt(t,16);if(Number.isNaN(n))throw new Error(`Invalid hex timestamp in UUIDv7: "${t}"`);return new Date(n)}export{ur as AmountEntrySchema,mn as AssetFacetItemSchema,Ae as BaseEnrichmentClient,Qe as BodySourceSchema,Bi as BoundingBoxSchema,ar as CHILD_TREE_REBUILD_CHUNK,Wr as CHUNK_BODY_FIDELITIES,Jr as CHUNK_CHANGE_KINDS,Gr as CHUNK_MANIFEST_VERSION,qr as CHUNK_PAIRINGS,Mi as CIRCUIT_BREAKER_SERVICES,ri as COPY_REASONS,ic as COPY_REASON_LABELS,fr as CanonicalDomainKeySchema,bn as ChangeFeedCursorSchema,cr as ChapterSegmentSchema,xi as ChildTreeRebuildRequestSchema,Ai as ChildTreeRebuildResultSchema,Zr as ChunkBodyFidelitySchema,$r as ChunkChangeKindSchema,Po as ChunkChangeSchema,uo as ChunkManifestChildSchema,po as ChunkManifestParentSchema,fo as ChunkManifestSchema,Xr as ChunkPairingSchema,Qt as ChunkRefSchema,wo as ChunkStatsSchema,Ji as ChunkingStrategySchema,Yi as CircuitBreakerStatusSchema,oo as ClassificationFacetSchema,le as ConfidentialityLevelSchema,ac as CopyReasonSchema,tt as DIFF_CONTEXT_LINES,en as DIFF_ENGINE_VERSION,to as DIFF_LINE_FACETS,sn as DIFF_LINE_PAGE_MAX,nn as DIFF_REGION_CELL_BOUND,no as DOCUMENT_CAPTURE_OUTCOMES,ln as DOCUMENT_CHANGE_FEED_PAGE_MAX,Ts as DOCUMENT_CHANGE_FEED_PAGE_SIZE,de as DOCUMENT_FACETS,Ye as DOCUMENT_KINDS,Qi as DOCUMENT_KIND_LABELS,Br as DOCUMENT_STATE_CAUSES,Ns as DOCUMENT_STATE_LOCK_TIMEOUT_MS,Vr as DOCUMENT_STATE_RUN_OUTCOMES,Ps as DiffLineFacetSchema,gn as DiffLinePageLimitSchema,Fs as DiffLinePageSchema,Do as DiffLineSchema,Ao as DiffSegmentSchema,Ks as DocumentCaptureAnswerSchema,ro as DocumentCaptureOutcomeSchema,Ko as DocumentChangeFeedEntrySchema,Ls as DocumentChangeFeedLimitSchema,js as DocumentChangeFeedPageSchema,Go as DocumentChangeFeedRowSchema,vs as DocumentComparisonSchema,cn as DocumentFacetSchema,ws as DocumentFacetValuesSchema,Hs as DocumentHistorySchema,Cr as DocumentKindSchema,Ho as DocumentRunEntrySchema,dn as DocumentStateCauseSchema,zo as DocumentStateEntrySchema,Yr as DocumentStateRunOutcomeSchema,Uo as DocumentStateSummarySchema,Vi as DocumentStructuredDataSchema,Xn as ENRICHMENT_STAGES,Lt as EnrichmentClient,se as EnrichmentClientError,wt as EnrichmentSyncStatusSchema,So as FACET_APPLICABLE_COUNTS,go as FACET_COUNT_FIELDS,be as FILE_PASSWORD_FIELD_WIDTHS,uc as FILE_PASSWORD_MAX_BYTES,ai as FILE_PASSWORD_PATTERN_SYNTAXES,dc as FILE_PASSWORD_PATTERN_SYNTAX_LABELS,ii as FILE_PASSWORD_PRIORITY_MAX,oi as FILE_PASSWORD_SOURCE_KINDS,cc as FILE_PASSWORD_SOURCE_KIND_LABELS,ki as FILTERABLE_CONFIDENTIALITY_LEVELS,bo as FacetChangeCountsSchema,Fo as FacetDiffSchema,it as FieldChangeSchema,li as FilePasswordConditionsSchema,fc as FilePasswordListSchema,hc as FilePasswordMatchSchema,Qn as FilePasswordViewSchema,Gi as FileUriSchema,ql as GRAPH_INDEX_LIMITS,yr as GraphSearchHitSchema,tn as HISTOGRAM_MAX_OCCURRENCES,xo as HunkIndexEntrySchema,Bs as INGESTION_EVENT_NAMES,on as INLINE_REFINE_CELL_BUDGET,rn as INLINE_REFINE_MAX_EDIT_DISTANCE,nt as INLINE_REFINE_MAX_GRAPHEMES,rt as INLINE_REFINE_MIN_SIMILARITY,ta as INTEGRITY_CLASS_POLICY,Pn as INTEGRITY_COMMAND_CODES,Dn as INTEGRITY_FINDINGS_PAGE_LIMIT_MAX,ha as IntegrityActiveRunSchema,rl as IntegrityAuditOverviewSchema,Na as IntegrityCancelFailureCodeSchema,sl as IntegrityCellResyncRequestSchema,ll as IntegrityCellResyncResultSchema,ut as IntegrityCommandFailureCodeSchema,cl as IntegrityCommandFailureSchema,ul as IntegrityCommandReplySchema,An as IntegrityCommandSchema,Qo as IntegrityDispositionSchema,Nn as IntegrityFindingItemClassSchema,al as IntegrityFindingPageSchema,Ra as IntegrityFindingSchema,il as IntegrityFindingsQuerySchema,Tn as IntegrityItemClassSchema,aa as IntegrityPhaseSchema,ol as IntegrityPlacementObservedSchema,pa as IntegrityQuantitySchema,ea as IntegrityRepairActionSchema,ia as IntegrityRepairOutcomeSchema,sa as IntegrityRepairSkipReasonSchema,dt as IntegrityRunHeaderSchema,na as IntegrityRunModeSchema,ra as IntegrityRunStatusSchema,Wo as IntegrityScopeRoleSchema,Ta as IntegrityStartFailureCodeSchema,ct as IntegrityStoreSchema,Zo as IntegrityUnitSchema,oa as IntegrityVerdictSchema,_o as JsonPatchOperationSchema,V as JsonValueSchema,Co as KeyedItemChangeSchema,Zt as KeyedItemSchema,$e as LEDGER_STEP_KEYS,eo as LINE_ENDINGS,io as LabelFacetItemSchema,ys as LedgerStepKeySchema,Os as LineEndingSchema,gr as MIME_KIND_RULES,Pt as MODE_TIERS,ao as MetadataFacetSchema,sr as ModelProviderSchema,Pr as NOTHING_TO_READ_TOKENS,wr as NothingToReadTokenSchema,jt as PIPELINE_FAILURE_STATUSES,Er as PIPELINE_FLOWS,ts as PIPELINE_PHASES,Kt as PIPELINE_STEPS,Te as PIPELINE_STEP_KEYS,ei as PROTECTION_FORMATS,ti as PROTECTION_SCHEMES,nc as PROTECTION_SCHEME_LABELS,Vt as PipelineFailureStatusSchema,qt as PipelineRunRecordSchema,Ze as PipelineRunStatusSchema,Xt as PipelineRunSummarySchema,Bt as PipelineStepKeySchema,Ss as PipelineStepMetricSchema,jr as PipelineStepRecordSchema,Nr as PipelineStepStatusSchema,Dr as PipelineTriggerSchema,Ql as ProtectionFormatSchema,tc as ProtectionSchemeSchema,he as QUARANTINED_CONFIDENTIALITY_LEVEL,Wn as REMOVABLE_PROTECTION_SCHEMES,Qr as RESTRICTED_MARK_SUBJECTS,xr as RUN_TERMINAL_STEP_ERROR_CODES,Je as RUN_TERMINAL_STEP_KEY,_r as RUN_TERMINAL_STEP_OUTCOMES,pn as ReadableConfidentialityLevelSchema,zs as RecentPipelineRunEntrySchema,ec as RemovableProtectionSchemeSchema,vo as RestrictedChangeMarkSchema,Us as RestrictedFailureMarkSchema,Ms as RestrictedIngestMarkSchema,Ds as RestrictedMarkSubjectSchema,Sn as RestrictedRunMarkSchema,Lo as RestrictedStateMarkSchema,Ir as RunTerminalStepDetailSchema,Tr as RunTerminalStepErrorCodeSchema,Rr as RunTerminalStepOutcomeSchema,zi as SEARCH_DEGRADATION_REASONS,vi as SEARCH_FUSIONS,Ot as SEARCH_MODES,wi as SEARCH_PARAM_LIMITS,Ui as SEARCH_QUALITY_TIERS,Xa as SOURCE_CAPABILITIES,qa as SOURCE_CREDENTIALS,Ar as STALE_RUN_ERROR_CODE,an as STRUCTURED_DATA_ARRAY_CELL_BOUND,we as SYSTEM_PARAMETER_RANGES,hr as SearchHitSchema,mr as SearchMetadataSchema,pr as SearchModeSchema,kt as SearchRequestSchema,Ft as SearchResponseSchema,Kl as SourceCatalogSchema,Za as SourceSpecSchema,Or as StageProvenanceSchema,Ce as TREE_PATH_PATTERN,lr as TenantIdSchema,ks as TextDiffIndexSchema,co as TextFacetSchema,Ro as TextStatsSchema,dr as TranscriptSegmentSchema,_e as TreePathSchema,ni as UNLOCK_DISPOSITIONS,oc as UNLOCK_DISPOSITION_LABELS,lc as UNLOCK_ERROR_CODES,rc as UnlockDispositionSchema,Xs as assertBoundedSystemParameter,qs as assertSystemParameterInRange,nr as assetTypeName,H as canonicalJson,es as classifyDocumentKind,Pa as codePointSlicer,ot as compareAssetKeys,q as compareCodeUnits,at as compareFacets,as as comparePhases,$a as compareStates,At as compareTreePaths,Jo as decodeChangeFeedCursor,Ha as diffChunkBodies,ja as diffLinePage,Yo as encodeChangeFeedCursor,$l as enrichmentStage,ns as flowFor,rs as flowStepGates,gs as formatSkipReason,gc as generateUuidV7,Bl as identifierMatches,dl as integrityCommandFailureCodeOf,Jl as isEnrichmentStageKey,sc as isPromotable,$ as isStrictlyEarlier,br as isUnknownTerm,ci as isValidUuidV7,or as millisecondsBetween,Li as modeFusesRankings,Fi as modeScoreIsSimilarity,os as orderedSteps,Yt as parseSkipReason,pc as passwordByteLength,Vl as pastedIdentifier,Pe as readableEntrySchema,Gl as sourceOfUri,ls as storedTermOf,Ne as storedTermSchema,cs as storedTermText,si as storedWidth,wa as stripWhitespace,Va as summarizeTransition,Me as summaryFacetDiff,Ue as textDiffIndex,ve as textFacetDiff,hi as treePathDepth,yi as treePathLabel,ae as treePathOf,gi as treePathParent,fi as treePathSegments,mc as triesEveryFile,Sc as uuidv7ToDate};
|
|
1
|
+
var H=e=>{if(e===null||typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new RangeError(`A canonical JSON number is finite: ${e}`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(H).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${H(t[r])}`).join(",")}}`};import{z as tr}from"zod";var Ke={embedded_image:"\u57CB\u3081\u8FBC\u307F\u753B\u50CF",embedded_chart:"\u57CB\u3081\u8FBC\u307F\u306E\u56F3\u8868",embedded_table:"\u57CB\u3081\u8FBC\u307F\u306E\u8868",attachment:"\u6DFB\u4ED8",archive_member:"\u66F8\u5EAB\u306E\u4E2D\u8EAB",keyframe:"\u5834\u9762\u306E\u753B\u50CF",audio_track:"\u97F3\u58F0",transcript_segment:"\u66F8\u304D\u8D77\u3053\u3057"};var Ce=/^[a-z_]+-(0|[1-9][0-9]*)(\/[a-z_]+-(0|[1-9][0-9]*))*$/,_e=tr.string().regex(Ce,"A tree path joins <asset_type>-<asset_index> segments with '/' from the root down."),oe=e=>{if(!Ce.test(e))throw new RangeError(`not a tree path: ${JSON.stringify(e)}`);return e.split("/").map(t=>{let n=t.lastIndexOf("-");return{kind:t.slice(0,n),digits:t.slice(n+1)}})},fi=e=>oe(e).map(({kind:t,digits:n})=>({assetType:t,assetIndex:Number(n)})),hi=e=>oe(e).length,xt=(e,t)=>e<t?-1:e>t?1:0,At=(e,t)=>{let n=oe(e),r=oe(t);for(let o=0;o<Math.min(n.length,r.length);o+=1){let i=n[o],s=r[o],l=xt(i.kind,s.kind)||i.digits.length-s.digits.length||xt(i.digits,s.digits);if(l!==0)return l}return n.length-r.length},nr=e=>{if(!Object.hasOwn(Ke,e))throw new RangeError(`no name for the asset type ${JSON.stringify(e)}`);return Ke[e]},yi=e=>oe(e).map(({kind:t,digits:n})=>`${nr(t)} ${n}`).join(" > "),ae=e=>e.parentPath===void 0?`${e.assetType}-${e.assetIndex}`:`${e.parentPath}/${e.assetType}-${e.assetIndex}`,gi=e=>oe(e).length===1?null:e.slice(0,e.lastIndexOf("/"));import{z as Q}from"zod";import{z as Ge}from"zod";var ie=Ge.string().uuid().transform(e=>e.toLowerCase()),N=Ge.string().datetime({offset:!0}),Ie=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!Object.hasOwn(e,"__proto__"),d=(e,t,n)=>{e.addIssue({code:Ge.ZodIssueCode.custom,path:[...t],message:n})},rr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:Z|([+-])(\d{2}):?(\d{2}))$/,Re=e=>{let t=N.safeParse(e).success?rr.exec(e):null;if(t===null)return null;let[,n,r,o,i,s,l,c,h,u,y]=t,E=new Date(0);E.setUTCFullYear(Number(n),Number(r)-1,Number(o)),E.setUTCHours(Number(i),Number(s),l===void 0?0:Number(l),0);let A=h===void 0?0:(h==="+"?1:-1)*(Number(u)*3600+Number(y)*60);return{epochSeconds:E.getTime()/1e3-A,fraction:c===void 0?"":c}},$=(e,t)=>{let n=Re(e),r=Re(t);if(n===null||r===null)return!1;if(n.epochSeconds!==r.epochSeconds)return n.epochSeconds<r.epochSeconds;let o=Math.max(n.fraction.length,r.fraction.length);return n.fraction.padEnd(o,"0")<r.fraction.padEnd(o,"0")},or=(e,t)=>{let n=Re(e),r=Re(t);if(n===null||r===null)return null;let o=Math.max(3,n.fraction.length,r.fraction.length),i=10n**BigInt(o),s=(BigInt(r.epochSeconds)-BigInt(n.epochSeconds))*i+BigInt(r.fraction.padEnd(o,"0"))-BigInt(n.fraction.padEnd(o,"0")),l=10n**BigInt(o-3);return Number(s>0n?(s+l-1n)/l:s/l)};var xe=e=>{if(!Number.isInteger(e)||e<1)throw new RangeError(`A requeue chunk reads a positive integer of documents: ${e}`);return(t,n)=>{let r=t.requeued+t.skipped.length;r>e&&d(n,["requeued"],`One chunk settles at most ${e} documents.`),t.nextAfter!==null!=(r===e)&&d(n,["nextAfter"],"A chunk continues exactly when it read the limit.");let o=new Set;for(let[i,s]of t.skipped.entries())o.has(s.metadataId)&&d(n,["skipped",i,"metadataId"],"A chunk keeps a document back once."),o.add(s.metadataId)}};var ar=100,Tt=Q.number().int().min(1).max(Number.MAX_SAFE_INTEGER),xi=Q.object({after:Tt.optional()}).strict(),ir=Q.object({requeued:Q.number().int().nonnegative(),skipped:Q.array(Q.object({metadataId:Q.number().int().min(1),reason:Q.string().min(1)}).strict()),nextAfter:Tt.nullable()}).strict(),Ai=ir.superRefine(xe(ar));var se=class extends Error{statusCode;responseBody;parsedBody;constructor(t,n,r,o){super(t),this.name="EnrichmentClientError",this.statusCode=n,this.responseBody=r,this.parsedBody=o}},Ae=class{baseUrl;apiKey;fetchFn;timeoutMs;constructor(t){if(!t||typeof t.baseUrl!="string"||t.baseUrl.trim().length===0)throw new Error("baseUrl is required and must be a non-empty string for EnrichmentClient.");let n=t.baseUrl.trim().replace(/\/$/,"");if(t.apiKey&&n.startsWith("http://")&&!n.includes("localhost")&&!n.includes("127.0.0.1"))throw new Error("Security Violation: Transmitting Bearer tokens over unencrypted HTTP to non-localhost hosts is strictly prohibited.");this.baseUrl=n,this.apiKey=t.apiKey,this.fetchFn=t.fetchFn??fetch,this.timeoutMs=t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:3e4}async request(t,n,r){let o=`${this.baseUrl}${t}`,i={Accept:"application/json","Content-Type":"application/json","X-Tenant-Id":n};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`);let s=new AbortController,l=setTimeout(()=>s.abort(),this.timeoutMs),c;try{c=await this.fetchFn(o,{method:"POST",headers:i,body:JSON.stringify(r),signal:s.signal})}catch(u){let y=u instanceof Error?u.message:String(u);throw new se(`Network request failed for POST ${o}: ${y}`,0,"")}finally{clearTimeout(l)}if(!c.ok){let u=await c.text().catch(()=>""),y;try{y=JSON.parse(u)}catch{}throw new se(`API request failed with status ${c.status}: ${u}`,c.status,u,y)}let h=await c.text().catch(()=>"");if(h.trim().length!==0)try{return JSON.parse(h)}catch(u){let y=u instanceof Error?u.message:String(u);throw new se(`Failed to parse response JSON from ${o}: ${y}`,c.status,h)}}};import{z as m}from"zod";import{z as Nt}from"zod";var sr=Nt.enum(["google_cloud","google_vision","yomitoku_local","faster_whisper_local","google_speech","ollama_local","openai","anthropic","azure_openai","bedrock","custom_openai_compatible"]),le=Nt.enum(["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"]),he="RESTRICTED";var wi={rrfK:{min:1,max:200,default:60},alpha:{min:0,max:1,default:.7},threshold:{min:0,max:1},limit:{min:1,max:50,default:10},queryLength:{min:1,max:500},filterTextLength:{min:1,max:100}},Dt=le.options.filter(e=>e!==he);if(Dt.length===0)throw new Error("The confidentiality vocabulary left nothing filterable after removing the quarantined level; a validator built from this list would reject every request.");var ki=Dt,Ot=["KEYWORD","SPARSE","DENSE","HYBRID","GRAPH_TRAVERSE"],Pt={KEYWORD:{dense:!1,sparse:!1,graph:!1,lexical:!0},SPARSE:{dense:!1,sparse:!0,graph:!1,lexical:!1},DENSE:{dense:!0,sparse:!1,graph:!1,lexical:!1},HYBRID:{dense:!0,sparse:!0,graph:!0,lexical:!0},GRAPH_TRAVERSE:{dense:!1,sparse:!1,graph:!0,lexical:!1}};function Fi(e){let t=Pt[e];return t.dense&&!t.sparse}function Li(e){let t=Pt[e];return[t.dense,t.sparse,t.graph,t.lexical].filter(Boolean).length>1}var vi=["rrf","linear"],Mi=["vector","graph"],Ui=["FULL","DEGRADED_LEXICAL_ONLY","DEGRADED_PARTIAL"],zi=["vector_search_disabled","graph_search_disabled","circuit_breaker_open:vector","circuit_breaker_open:graph","vector_tier_not_configured","graph_tier_not_configured","no_active_vector_collection","vector_collections_missing","row_scope_permits_no_rows","vector_tier_unavailable","graph_tier_unavailable","vector_tier_timed_out","graph_tier_timed_out","tiers_not_executed"];var lr=m.string().trim().min(1,"tenant_id must be a non-empty string"),Gi=m.string().trim().min(1,"file_uri must be a non-empty string"),wt=m.enum(["PENDING","EXTRACTING","ENRICHING","PROJECTING","SYNCED","FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"]),Bi=m.object({page:m.number().int().positive().optional(),x:m.number().nonnegative().optional(),y:m.number().nonnegative().optional(),width:m.number().positive().optional(),height:m.number().positive().optional(),start_sec:m.number().nonnegative().optional(),end_sec:m.number().nonnegative().optional(),frame_index:m.number().int().nonnegative().optional(),timestamp_sec:m.number().nonnegative().optional(),scene_confidence:m.number().min(0).max(1).optional()}),cr=m.object({title:m.string().trim().min(1),start_sec:m.number().nonnegative(),end_sec:m.number().nonnegative(),summary:m.string()}),dr=m.object({start_sec:m.number().nonnegative(),end_sec:m.number().nonnegative(),speaker:m.string().trim().min(1),text:m.string()}),ur=m.object({label:m.string(),value:m.number(),currency:m.string()}),Vi=m.object({document_type:m.string().optional(),title:m.string().optional(),organization:m.string().optional(),key_entities:m.array(m.string()).optional(),dates:m.array(m.string()).optional(),amounts:m.array(ur).optional(),media_type:m.enum(["video","audio"]).optional(),duration_sec:m.number().nonnegative().optional(),chapters:m.array(cr).optional(),transcript_segments:m.array(dr).optional()}),Yi=m.enum(["CLOSED","OPEN","HALF_OPEN"]),pr=m.enum(Ot),mr=m.object({circuit_breaker_status:m.string(),quality_tier:m.string(),latency_ms:m.number().nonnegative(),total_hits:m.number().int().nonnegative(),fallback_applied:m.boolean(),degraded_reason:m.string().nullable()}),fr=m.enum(["CONTRACT_LEGAL","EMAIL_THREAD","DAILY_REPORT","FINANCIAL_REPORT","TECHNICAL_SPEC","MASTER_DATA","MEDIA_ASSET","GENERAL_DOCUMENT"]),Ji=m.enum(["hierarchical","conversation","section","fixed_size","table_aware","semantic","none","multimodal"]),hr=m.object({metadata_id:m.number().int().positive(),chunk_index:m.number().int().nonnegative(),text:m.string(),score:m.number()}),yr=m.object({metadata_id:m.number().int().positive(),relation:m.string(),target_name:m.string()}),kt=m.object({query:m.string().trim().min(1,"query must not be empty"),tenant_id:lr,domain_key:fr.optional(),limit:m.number().int().positive().optional(),department_id:m.number().int().positive().optional(),search_mode:pr.optional(),strategy_id:m.number().int().positive().optional()}).strict(),Ft=m.object({hits:m.array(hr),graph_hits:m.array(yr),tiers:m.record(m.string(),m.boolean()),metadata:mr});var Lt=class extends Ae{async search(t){let n=kt.parse(t),r=await this.request("/ai/search/hybrid",n.tenant_id,n);return Ft.parse(r)}};import{z as a}from"zod";import{z as S}from"zod";var Ye=["email","pdf","office","image","media","archive","markdown","text","google_native","other"],Qi={email:"\u30E1\u30FC\u30EB",pdf:"PDF",office:"Office \u6587\u66F8",image:"\u753B\u50CF",media:"\u97F3\u58F0\u30FB\u52D5\u753B",archive:"\u66F8\u5EAB",markdown:"Markdown",text:"\u30C6\u30AD\u30B9\u30C8",google_native:"Google \u30CD\u30A4\u30C6\u30A3\u30D6",other:"\u305D\u306E\u4ED6"},gr=[["message/rfc822","email"],["application/pdf","pdf"],["application/vnd.openxmlformats-officedocument.*","office"],["application/msword","office"],["application/vnd.ms-excel","office"],["application/vnd.ms-powerpoint","office"],["application/zip","archive"],["application/x-zip-compressed","archive"],["application/x-zip","archive"],["application/x-tar","archive"],["application/x-gtar","archive"],["application/gzip","archive"],["application/x-gzip","archive"],["application/x-bzip2","archive"],["application/x-xz","archive"],["application/vnd.google-apps.*","google_native"],["image/svg+xml","text"],["image/emf","other"],["image/x-emf","other"],["image/wmf","other"],["image/x-wmf","other"],["image/*","image"],["audio/*","media"],["video/*","media"],["text/markdown","markdown"],["text/x-markdown","markdown"],["text/*","text"],["application/json","text"],["application/xml","text"]];function es(e){let t=(e.split(";")[0]??"").trim().toLowerCase();for(let[n,r]of gr)if(n.endsWith("*")?t.startsWith(n.slice(0,-1)):t===n)return r;return"other"}var Te=["delete_child_assets","unlock_document","extract_text","analyze_media","extract_assets","ocr_document","ocr_children","resolve_body","enrich_document","project_to_indexes"],Je="record_document_state",$e=[...Te,Je],ts=["EXTRACTING","ENRICHING","PROJECTING"],jt=["FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"],Be=e=>({featureFlagKey:e,whenClosed:"skip",failureStatus:null}),vt=(e,t)=>({featureFlagKey:e,whenClosed:"fail",failureStatus:t}),Kt={delete_child_assets:{key:"delete_child_assets",label:"\u65E7\u7248\u306E\u5B50\u30A2\u30BB\u30C3\u30C8\u524A\u9664",description:"\u3053\u306E\u7248\u3088\u308A\u524D\u306E\u7248\u304C\u751F\u3093\u3060\u5B50\u30A2\u30BB\u30C3\u30C8\u3092\u4FDD\u7BA1\u5C64\u3068\u7D22\u5F15\u304B\u3089\u5916\u3059\u3002",endpoint:"/ai/assets/delete",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:null,fanOut:null},unlock_document:{key:"unlock_document",label:"\u30D1\u30B9\u30EF\u30FC\u30C9\u306E\u89E3\u9664",description:"\u6587\u66F8\u304C\u6301\u3064\u30D1\u30B9\u30EF\u30FC\u30C9 (ZIP\u30FBPDF\u30FBOffice) \u3092\u3001\u6761\u4EF6\u306E\u5F53\u305F\u308B\u30D5\u30A1\u30A4\u30EB\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3067\u5916\u3057\u3001\u89E3\u3044\u305F\u30D5\u30A1\u30A4\u30EB\u3092\u539F\u672C\u306B\u3059\u308B (\u6E90\u3092\u4E0A\u66F8\u304D\u3059\u308B\u304B\u89E3\u3044\u305F\u5199\u3057\u3092\u539F\u672C\u306B\u3057\u3001\u30D1\u30B9\u30EF\u30FC\u30C9\u306E\u7121\u3044\u6587\u66F8\u306F\u98DB\u3070\u3059)\u3002",endpoint:"/ai/documents/unlock",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:null,fanOut:null},extract_text:{key:"extract_text",label:"\u6587\u5B57\u5C64\u306E\u62BD\u51FA",description:"\u6587\u66F8\u304C\u6301\u3064\u6587\u5B57\u5C64 (PDF \u306E\u6587\u5B57\u30FBOffice \u306E\u672C\u6587\u30FB\u30E1\u30FC\u30EB\u306E\u672C\u6587\u3068\u898B\u51FA\u3057) \u3092\u8AAD\u307F\u3001\u4F4D\u7F6E\u60C5\u5831\u3068\u5171\u306B\u4FDD\u5B58\u3059\u308B\u3002",endpoint:"/ai/enrichment/extract",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:null,fanOut:null},analyze_media:{key:"analyze_media",label:"\u30E1\u30C7\u30A3\u30A2\u89E3\u6790",description:"\u97F3\u58F0\u30FB\u52D5\u753B\u3092\u8EE2\u5199\u3057\u3001\u767A\u8A71\u533A\u9593\u4ED8\u304D\u306E\u30C1\u30E3\u30F3\u30AF\u3068\u30AD\u30FC\u30D5\u30EC\u30FC\u30E0\u6570\u3092\u8A18\u9332\u3059\u308B\u3002",endpoint:"/ai/media/analyze",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[Be("ENABLE_MEDIA_ANALYSIS")],capability:"transcription",fanOut:null},extract_assets:{key:"extract_assets",label:"\u5B50\u30A2\u30BB\u30C3\u30C8\u306E\u62BD\u51FA",description:"\u57CB\u3081\u8FBC\u307F\u753B\u50CF\u30FB\u30E1\u30FC\u30EB\u306E\u6DFB\u4ED8\u30FBMarkdown \u304C\u53C2\u7167\u3059\u308B\u753B\u50CF\u30FB\u66F8\u5EAB (ZIP\u30FBtar\u30FBgzip\u30FBbzip2\u30FBxz) \u306E\u4E2D\u8EAB\u3092\u5B50\u30A2\u30BB\u30C3\u30C8\u3068\u3057\u3066\u53D6\u308A\u51FA\u3057 (\u6DFB\u4ED8\u306E\u66F8\u5EAB\u3082\u4E2D\u8EAB\u3078\u5C55\u958B\u3059\u308B)\u3001\u914D\u5099\u306E\u7F6E\u304D\u5834\u3078\u5199\u3057\u3066\u767B\u9332\u3059\u308B\u3002",endpoint:"/ai/assets/extract",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[Be("ENABLE_ASSET_EXTRACTION")],capability:"asset_extraction",fanOut:null},ocr_children:{key:"ocr_children",label:"\u5B50\u30A2\u30BB\u30C3\u30C8\u306E\u8AAD\u307F\u53D6\u308A",description:"\u5207\u308A\u51FA\u3057\u305F\u5B50\u30A2\u30BB\u30C3\u30C8\u3092\u62BD\u51FA\u9806\u306B 1 \u4EF6\u305A\u3064\u8AAD\u307F\u3001\u6587\u5B57\u5C64\u3092\u8AAD\u3081\u308B\u5B50 (\u30C6\u30AD\u30B9\u30C8\u30FB\u30E1\u30FC\u30EB\u30FBOffice\u30FBPDF) \u306F\u305D\u306E\u6587\u5B57\u5C64\u3092\u3001\u8AAD\u3081\u306A\u3044\u5B50\u306F\u7248\u9762\u3092\u5149\u5B66\u8A8D\u8B58\u3067\u8AAD\u3093\u3067 (\u89AA\u306E\u672C\u6587\u3067\u3042\u308B\u7248\u9762\u306E\u8A8D\u8B58\u304C\u65E2\u306B\u8AAD\u3093\u3060\u30DA\u30FC\u30B8\u306B\u8F09\u308B PDF \u306E\u753B\u50CF\u306F\u8AAD\u307F\u76F4\u3055\u306A\u3044)\u3001\u5B50\u3054\u3068\u306B\u672C\u6587\u3068\u51FA\u6240\u3092\u4FDD\u5B58\u3059\u308B\u3002",endpoint:"/ai/ocr/run",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:"ocr",fanOut:"children"},ocr_document:{key:"ocr_document",label:"\u6587\u66F8\u306E OCR",description:"\u6587\u66F8\u81EA\u8EAB\u306E\u7248\u9762 (\u753B\u50CF\u30FBPDF \u306E\u5404\u30DA\u30FC\u30B8) \u3092\u5149\u5B66\u8A8D\u8B58\u306B\u304B\u3051\u308B\u3002",endpoint:"/ai/ocr/run",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[Be("ENABLE_OCR")],capability:"ocr",fanOut:null},resolve_body:{key:"resolve_body",label:"\u672C\u6587\u306E\u78BA\u5B9A",description:"\u6587\u5B57\u5C64\u30FBOCR\u30FB\u8EE2\u5199\u306E\u3069\u308C\u3092\u672C\u6587\u3068\u3059\u308B\u304B\u3092\u6C7A\u3081\u3001\u51FA\u6240\u3092\u8A18\u9332\u3059\u308B\u3002",endpoint:"/ai/enrichment/body",phase:"ENRICHING",failureStatus:"FAILED_ENRICH",gates:[],capability:null,fanOut:null},enrich_document:{key:"enrich_document",label:"\u8981\u7D04\u3068\u69CB\u9020\u5316\u62BD\u51FA",description:"\u672C\u6587\u3092\u30E2\u30C7\u30EB\u3078\u6E21\u3057\u3001\u8981\u7D04\u30FB\u30BF\u30B0\u30FB\u69CB\u9020\u5316\u30C7\u30FC\u30BF\u30FB\u30C9\u30E1\u30A4\u30F3\u5206\u985E\u3092\u5F97\u308B\u3002",endpoint:"/ai/enrichment/document",phase:"ENRICHING",failureStatus:"FAILED_ENRICH",gates:[],capability:"enrichment",fanOut:null},project_to_indexes:{key:"project_to_indexes",label:"\u30D9\u30AF\u30C8\u30EB\u3068\u30B0\u30E9\u30D5\u3078\u306E\u6295\u5F71",description:"\u672C\u6587\u3092\u30C1\u30E3\u30F3\u30AF\u306B\u3057\u3066\u57CB\u3081\u8FBC\u307F\u3001\u30D9\u30AF\u30C8\u30EB\u7D22\u5F15\u3068\u30CA\u30EC\u30C3\u30B8\u30B0\u30E9\u30D5\u3078\u66F8\u304F\u3002",endpoint:"/ai/enrichment/project",phase:"PROJECTING",failureStatus:"FAILED_VECTOR",gates:[vt("ENABLE_VECTOR_INDEXING","FAILED_VECTOR"),vt("ENABLE_GRAPH_INDEXING","FAILED_GRAPH")],capability:null,fanOut:null}},Ve={whenClosed:"fail",failureStatus:"FAILED_EXTRACT"},Mt=[{step:"delete_child_assets",dependsOn:[]},{step:"extract_text",dependsOn:["delete_child_assets"]},{step:"extract_assets",dependsOn:["extract_text"]},{step:"ocr_document",dependsOn:["extract_text"]},{step:"ocr_children",dependsOn:["extract_assets","ocr_document"]},{step:"resolve_body",dependsOn:["ocr_children","ocr_document"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],Ut=[{step:"delete_child_assets",dependsOn:[]},{step:"unlock_document",dependsOn:["delete_child_assets"]},{step:"extract_text",dependsOn:["unlock_document"]},{step:"extract_assets",dependsOn:["extract_text"]},{step:"ocr_document",dependsOn:["extract_text"]},{step:"ocr_children",dependsOn:["extract_assets","ocr_document"]},{step:"resolve_body",dependsOn:["ocr_children","ocr_document"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],Sr=[{step:"delete_child_assets",dependsOn:[]},{step:"extract_text",dependsOn:["delete_child_assets"]},{step:"extract_assets",dependsOn:["extract_text"]},{step:"ocr_children",dependsOn:["extract_assets"]},{step:"resolve_body",dependsOn:["ocr_children"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],zt=[{step:"delete_child_assets",dependsOn:[]},{step:"extract_text",dependsOn:["delete_child_assets"]},{step:"resolve_body",dependsOn:["extract_text"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],Er={email:{kind:"email",steps:Mt},pdf:{kind:"pdf",steps:Ut},office:{kind:"office",steps:Ut},google_native:{kind:"google_native",steps:Mt},image:{kind:"image",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"ocr_document",dependsOn:["delete_child_assets"],gatePolicy:Ve},{step:"resolve_body",dependsOn:["ocr_document"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}]},media:{kind:"media",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"analyze_media",dependsOn:["delete_child_assets"],gatePolicy:Ve},{step:"resolve_body",dependsOn:["analyze_media"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"existing"}]},archive:{kind:"archive",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"unlock_document",dependsOn:["delete_child_assets"]},{step:"extract_assets",dependsOn:["unlock_document"],gatePolicy:Ve},{step:"ocr_children",dependsOn:["extract_assets"]},{step:"resolve_body",dependsOn:["ocr_children"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}]},markdown:{kind:"markdown",steps:Sr},text:{kind:"text",steps:zt},other:{kind:"other",steps:zt}};function ns(e){return Er[e]}function rs(e){let{gates:t}=Kt[e.step],{gatePolicy:n}=e;return n===void 0?t:t.map(r=>({featureFlagKey:r.featureFlagKey,whenClosed:n.whenClosed,failureStatus:n.failureStatus}))}function os(e){let t=new Map(e.steps.map(i=>[i.step,i]));for(let i of e.steps){if(i.gatePolicy!==void 0&&Kt[i.step].gates.length===0)throw new Error(`Flow ${e.kind}: step ${i.step} overrides its gate policy, but the step has no gate to close.`);for(let s of i.dependsOn)if(!t.has(s))throw new Error(`Flow ${e.kind}: step ${i.step} depends on ${s}, which the flow does not contain.`)}let n=[...e.steps],r=new Set,o=[];for(;n.length>0;){let i=n.findIndex(l=>l.dependsOn.every(c=>r.has(c)));if(i===-1)throw new Error(`Flow ${e.kind}: the steps ${n.map(l=>l.step).join(", ")} depend on each other in a cycle.`);let[s]=n.splice(i,1);r.add(s.step),o.push(s)}return o}var Ht={EXTRACTING:0,ENRICHING:1,PROJECTING:2};function as(e,t){return Ht[e]-Ht[t]}import{z as ye}from"zod";function ls(e,t){return Gt(e,t)?t:{known:!1,raw:t}}function Gt(e,t){return e.includes(t)}function br(e){return typeof e!="string"}function cs(e){return br(e)?e.raw:e}function Ne(e){let t=ye.object({known:ye.literal(!1),raw:ye.string()}).strict().refine(n=>!Gt(e,n.raw),{message:"A value the vocabulary knows is carried as itself, never as an unknown term.",path:["raw"]});return ye.union([ye.enum(e),t])}var Cr=S.enum(Ye),Bt=S.enum(Te),ys=S.enum($e),Vt=S.enum(jt),_r=["RECORDED","UNCHANGED","ALREADY_RECORDED"],Rr=S.enum(_r),Ir=S.object({outcome:Rr}).strict(),xr=["history_no_current_row","history_lock_timeout","history_write_failed"],Ar="stale_run",Tr=S.enum(xr),Ze=S.enum(["RUNNING","SUCCEEDED","FAILED"]),Nr=S.enum(["RUNNING","SUCCEEDED","SKIPPED","FAILED"]),Dr=S.enum(["ingest","retry","resync"]),Qe=S.enum(["text_layer","ocr","transcript"]),B=S.number().int().nonnegative().nullable(),Or=S.object({provider:S.string().nullable(),model:S.string().nullable(),engine:S.string().nullable(),prompt_key:S.string().nullable(),prompt_version:S.number().int().nullable(),duration_ms:B,input_chars:B,output_chars:B,pages_read:B,pages_total:B,chunk_count:B,points_upserted:B,collection:S.string().nullable(),embedding_model:S.string().nullable(),strategy_id:S.number().int().positive().nullable(),graph_nodes:B,body_source:Qe.nullable(),detail:S.custom(Ie,"A report's detail holds no own __proto__ member.").pipe(S.record(S.string(),S.unknown()))}).strict(),Pr=["no_pages","no_pages_rendered","covered_by_page_recognition"],wr=S.enum(Pr),qe="gate_closed:",Xe="source_skipped:",We="nothing_to_read:",kr=["no_children","not_protected","superseded","recording_disabled","recording_misconfigured"],Fr=e=>kr.includes(e),Lr=/^[A-Z][A-Z0-9_]*$/;function Yt(e){if(Fr(e))return{kind:e};if(e.startsWith(qe)){let t=e.slice(qe.length);return Lr.test(t)?{kind:"gate_closed",featureFlagKey:t}:null}if(e.startsWith(Xe)){let t=Bt.safeParse(e.slice(Xe.length));return t.success?{kind:"source_skipped",stepKey:t.data}:null}if(e.startsWith(We)){let t=wr.safeParse(e.slice(We.length));return t.success?{kind:"nothing_to_read",token:t.data}:null}return null}function gs(e){let t=vr(e);if(Yt(t)===null)throw new RangeError(`Skip reason ${JSON.stringify(e)} has no text form: ${JSON.stringify(t)} is outside the skip-reason grammar.`);return t}function vr(e){switch(e.kind){case"gate_closed":return`${qe}${e.featureFlagKey}`;case"no_children":case"not_protected":case"superseded":case"recording_disabled":case"recording_misconfigured":return e.kind;case"source_skipped":return`${Xe}${e.stepKey}`;case"nothing_to_read":return`${We}${e.token}`;default:{let t=e;throw new RangeError(`Unknown skip reason kind: ${JSON.stringify(t)}`)}}}var Mr=S.object({id:S.number().int().positive(),runId:S.number().int().positive(),sequence:S.number().int().nonnegative(),stepKey:Ne($e),targetMetadataId:S.number().int().positive(),targetTreePath:_e.nullable(),status:Nr,skipReason:S.string().nullable(),provenance:Or.nullable(),strategyId:S.number().int().positive().nullable(),httpStatus:S.number().int().nullable(),errorCode:S.string().nullable(),errorMessage:S.string().nullable(),startedAt:N,finishedAt:N.nullable(),durationMs:B}).strict();function Ur(e,t){switch(e.stepKey===Je&&Hr(e,t),e.status){case"SKIPPED":e.skipReason===null&&d(t,["skipReason"],"A SKIPPED step must record why it was skipped."),e.provenance!==null&&d(t,["provenance"],"A SKIPPED step read nothing, so it has no report.");return;case"SUCCEEDED":e.provenance===null&&d(t,["provenance"],"A SUCCEEDED step must carry its report."),e.skipReason!==null&&d(t,["skipReason"],"A SUCCEEDED step was not skipped.");return;case"RUNNING":e.finishedAt!==null&&d(t,["finishedAt"],"A RUNNING step has not finished.");return;case"FAILED":e.skipReason!==null&&d(t,["skipReason"],"A FAILED step was not skipped.");return}}var zr=["superseded","recording_disabled","recording_misconfigured"];function Hr(e,t){if(e.strategyId!==null&&d(t,["strategyId"],"The terminal step applies no strategy."),e.httpStatus!==null&&d(t,["httpStatus"],"The terminal step calls no API, so it has no HTTP status."),e.status==="SUCCEEDED"&&e.provenance!==null){Ir.safeParse(e.provenance.detail).success||d(t,["provenance","detail"],"A succeeded terminal step's detail is exactly { outcome }.");for(let[n,r]of Object.entries(e.provenance))n!=="detail"&&r!==null&&d(t,["provenance",n],"A succeeded terminal step reports nothing but its outcome.")}if(e.status==="FAILED"&&(e.provenance!==null&&d(t,["provenance"],"Neither the failure close nor the recovery sweeper writes a terminal step's report."),e.errorCode!==Ar&&!Tr.safeParse(e.errorCode).success&&d(t,["errorCode"],"A failed terminal step names a history error code, or the stale-run code the sweeper writes.")),e.status==="SKIPPED"&&e.skipReason!==null){let n=Yt(e.skipReason);(n===null||!zr.includes(n.kind))&&d(t,["skipReason"],"A skipped terminal step names one of the terminal skip reasons.")}}var jr=Mr.superRefine(Ur),Jt=S.object({id:S.number().int().positive(),tenantId:S.string().min(1),metadataId:S.number().int().positive(),revision:S.number().int().positive(),runUid:S.string().uuid(),jobId:S.string().min(1),attempt:S.number().int().positive(),trigger:Dr,documentKind:Ne(Ye),flowKey:S.string().min(1),status:Ze,retryScheduled:S.boolean(),failedStepKey:Ne(Te).nullable(),errorMessage:S.string().nullable(),requestedBy:S.string().min(1),startedAt:N,finishedAt:N.nullable(),steps:S.array(jr)}).strict();function $t(e,t){e.retryScheduled&&e.status!=="FAILED"&&d(t,["retryScheduled"],"Only a FAILED run can have a retry scheduled.")}var qt=Jt.superRefine($t),Xt=Jt.omit({steps:!0}).superRefine($t);function Kr(e,t){e.sampleCount>0||(e.durationP50Ms!==null&&d(t,["durationP50Ms"],"A step with no sample has no median latency."),e.durationP95Ms!==null&&d(t,["durationP95Ms"],"A step with no sample has no 95th-percentile latency."))}var Ss=S.object({documentKind:Cr,stepKey:Bt,sampleCount:S.number().int().nonnegative(),succeeded:S.number().int().nonnegative(),failed:S.number().int().nonnegative(),skipped:S.number().int().nonnegative(),durationP50Ms:B,durationP95Ms:B,lastStartedAt:N.nullable()}).strict().superRefine(Kr);var en=2,tt=3,tn=64,nn=1e6,nt=4096,rt=.3,rn=1024,on=67108864,an=16777216,sn=500,ln=50,Ts=50,Ns=1e4,Gr=1,de=["classification","metadata","labels","tags","structured_data","text","summary","chunks","assets"],cn=a.enum(de),Br=["RUN","PRE_WRITE","MANUAL","BACKFILL"],dn=a.enum(Br),Vr=["SUCCEEDED","FAILED"],Yr=a.enum(Vr),Jr=["ADDED","REMOVED","MODIFIED","MOVED"],$r=a.enum(Jr),qr=["clause","breadcrumbs"],Xr=a.enum(qr),Wr=["EXACT","WHITESPACE_NORMALIZED","UNVERIFIED"],Zr=a.enum(Wr),Qr=["run","ingest","failure","state","change"],Ds=a.enum(Qr),eo=["LF","CRLF","CR","MIXED","NONE"],Os=a.enum(eo),to=["text","summary","chunks"],Ps=a.enum(to),no=["RECORDED","UNCHANGED"],ro=a.enum(no),un=a.lazy(()=>a.custom(Ie,"A JSON object here holds no own __proto__ member.").pipe(a.record(a.string(),V))),V=a.lazy(()=>a.union([a.string(),a.number().finite(),a.boolean(),a.null(),a.array(V),un])),pn=le.exclude([he]),z=a.number().int().positive(),R=a.number().int().nonnegative(),Oe=a.string().regex(/^[0-9a-f]{64}$/,"A SHA-256 is 64 lowercase hexadecimal digits."),q=(e,t)=>e<t?-1:e>t?1:0,ot=(e,t)=>At(ae(e),ae(t)),ce=(e,t,n,r,o)=>{for(let i=1;i<e.length;i++)t(e[i-1],e[i])>=0&&d(n,[...r,i],o)},oo=a.object({confidentialityLevel:le,departmentId:a.number().int().nullable(),folderPath:a.string().nullable(),createdBy:a.string()}).strict(),ao=a.object({fileName:a.string(),filePath:a.string(),fileId:a.string().nullable(),revision:z,revisionId:a.string().nullable(),fileSize:R,mimeType:a.string(),fileHash:a.string().nullable(),mtime:N}).strict(),io=a.object({labelKey:a.string().min(1),assignedBy:a.string(),confidenceScore:a.number().finite()}).strict(),so=a.string().refine(e=>!e.includes("/")&&Ce.test(`${e}-0`),"An asset type is the kind of a tree path segment: lowercase letters and underscores."),mn=a.object({assetType:so,assetIndex:R.max(Number.MAX_SAFE_INTEGER),mimeType:a.string(),fileSize:R,textSha256:Oe.nullable(),parentPath:_e.optional()}).strict(),lo=mn.pick({assetType:!0,assetIndex:!0,parentPath:!0}).strip(),co=a.object({body:a.string().nullable(),mime:a.string().nullable(),source:Qe.nullable(),isTruncated:a.boolean(),pageOffsets:V}).strict(),uo=a.object({index:R,hash:Oe,whitespaceFreeHash:Oe,charStart:R,charEnd:R,breadcrumbs:a.string(),clause:a.string().nullable(),page:a.number().int().nullable(),sheet:a.string().nullable(),slide:a.number().int().nullable(),startSec:a.number().finite().nullable(),endSec:a.number().finite().nullable(),tokenCount:R,parentOrdinal:R}).strict(),po=a.object({ordinal:R,contentHash:Oe,charLength:R}).strict();function mo(e,t){ce(e.children,(r,o)=>r.index-o.index,t,["children"],"Children are listed in strictly ascending index.");let n=0;e.children.forEach((r,o)=>{r.charStart>r.charEnd&&d(t,["children",o,"charEnd"],"A span ends at or after its start."),r.parentOrdinal===n?n++:r.parentOrdinal>n&&d(t,["children",o,"parentOrdinal"],"Parents are numbered in the order they first appear.")}),(e.parents.length!==n||e.parents.some((r,o)=>r.ordinal!==o))&&d(t,["parents"],"Each parent the children reach is listed exactly once, in ordinal order.")}var fo=a.object({version:a.literal(Gr),children:a.array(uo).min(1),parents:a.array(po)}).strict().superRefine(mo);function ho(e,t){ce(e.labels,(n,r)=>q(n.labelKey,r.labelKey),t,["labels"],"Labels are ordered by labelKey with no key repeated."),ce(e.tags??[],q,t,["tags"],"Tags are ordered with no tag repeated."),e.assets.every(n=>lo.safeParse(n).success)&&(ce(e.assets,ot,t,["assets"],"Assets are ordered by their tree paths in tree order with no path repeated."),yo(e.assets,t))}function yo(e,t){let n=new Set;e.forEach((r,o)=>{Object.hasOwn(r,"parentPath")&&r.parentPath===void 0&&d(t,["assets",o,"parentPath"],"parentPath is absent at depth 1, never undefined."),r.parentPath!==void 0&&!n.has(r.parentPath)&&d(t,["assets",o,"parentPath"],"Each parentPath names an earlier item's tree path."),n.add(ae(r))})}var ws=a.object({classification:oo,metadata:ao,labels:a.array(io),tags:a.array(a.string()).nullable(),structured_data:V,text:co,summary:a.string().nullable(),chunks:fo.nullable(),assets:a.array(mn)}).strict().superRefine(ho),go=["addedCount","removedCount","modifiedCount","movedCount","unchangedCount","charsAdded","charsRemoved"],So={classification:["modifiedCount"],metadata:["modifiedCount"],labels:["addedCount","removedCount","modifiedCount","unchangedCount"],tags:["addedCount","removedCount","unchangedCount"],structured_data:["addedCount","removedCount","modifiedCount"],text:["addedCount","removedCount","unchangedCount","charsAdded","charsRemoved"],summary:["addedCount","removedCount","unchangedCount","charsAdded","charsRemoved"],chunks:["addedCount","removedCount","modifiedCount","movedCount","unchangedCount"],assets:["addedCount","removedCount","modifiedCount","unchangedCount"]};function Eo(e,t){let n=So[e.facet];for(let r of go)n.includes(r)&&e[r]===null&&d(t,[r],`The ${e.facet} facet always counts ${r}.`),!n.includes(r)&&e[r]!==null&&d(t,[r],`${r} does not apply to the ${e.facet} facet.`)}var bo=a.object({facet:cn,addedCount:R.nullable(),removedCount:R.nullable(),modifiedCount:R.nullable(),movedCount:R.nullable(),unchangedCount:R.nullable(),charsAdded:R.nullable(),charsRemoved:R.nullable()}).strict().superRefine(Eo),Wt=new Map(de.map((e,t)=>[e,t])),at=(e,t)=>Wt.get(e)-Wt.get(t),fn=a.array(bo).min(1).superRefine((e,t)=>ce(e,(n,r)=>at(n.facet,r.facet),t,[],"A change lists each changed facet once, in display order.")),it=a.object({field:a.string().min(1),before:V,after:V}).strict(),Zt=a.object({key:a.string().min(1),value:un}).strict(),Co=a.object({key:a.string().min(1),fields:a.array(it).min(1)}).strict(),et=a.string().refine(e=>e===""||e.startsWith("/"),"A JSON Pointer is empty or starts with '/'."),_o=a.discriminatedUnion("op",[a.object({op:a.literal("add"),path:et,value:V}).strict(),a.object({op:a.literal("remove"),path:et,previous:V}).strict(),a.object({op:a.literal("replace"),path:et,value:V,previous:V}).strict()]),Ro=a.object({linesAdded:R,linesRemoved:R,linesUnchanged:R,charsAdded:R,charsRemoved:R,similarity:a.number().min(0).max(1).nullable()}).strict();function Io(e,t){e.linesAdded>e.newLines&&d(t,["linesAdded"],"A hunk adds no more lines than it spans on the new side."),e.linesRemoved>e.oldLines&&d(t,["linesRemoved"],"A hunk removes no more lines than it spans on the old side."),e.linesAdded+e.linesRemoved===0&&d(t,["linesAdded"],"A hunk changes at least one line.")}var xo=a.object({hunk:R,oldStart:R,oldLines:R,newStart:R,newLines:R,firstPage:a.number().int().nullable(),linesAdded:R,linesRemoved:R}).strict().superRefine(Io),hn=(e,t)=>{e.forEach((n,r)=>{n.hunk!==r&&d(t,["hunks",r,"hunk"],"Hunks are numbered from 0 in order.")})},yn={attributes:a.array(it),stats:Ro,hunks:a.array(xo)},ks=a.object(yn).strict().superRefine((e,t)=>hn(e.hunks,t)),Ao=a.object({kind:a.enum(["equal","removed","added"]),text:a.string().min(1)}).strict(),To={context:["equal"],removed:["equal","removed"],added:["equal","added"]};function No(e,t){e.oldNumber===null!=(e.kind==="added")&&d(t,["oldNumber"],"Context and removed lines carry their old number; added lines carry none."),e.newNumber===null!=(e.kind==="removed")&&d(t,["newNumber"],"Context and added lines carry their new number; removed lines carry none."),e.segments.forEach((n,r)=>{To[e.kind].includes(n.kind)||d(t,["segments",r,"kind"],`A ${e.kind} line has no ${n.kind} segment.`)})}var Do=a.object({kind:a.enum(["context","removed","added"]),oldNumber:z.nullable(),newNumber:z.nullable(),page:a.number().int().nullable(),segments:a.array(Ao)}).strict().superRefine(No),Fs=a.object({lines:a.array(Do).max(sn),next:R.nullable()}).strict().superRefine((e,t)=>{e.next!==null&&e.lines.length===0&&d(t,["next"],"An empty page has no next page.")}),gn=a.number().int().min(1).max(sn),Ls=a.number().int().min(1).max(ln),Qt=a.object({index:R,charStart:R,charEnd:R,page:a.number().int().nullable(),sheet:a.string().nullable(),slide:a.number().int().nullable(),startSec:a.number().finite().nullable(),endSec:a.number().finite().nullable(),breadcrumbs:a.string(),tokenCount:R,fidelity:Zr}).strict();function Oo(e,t){e.old===null!=(e.kind==="ADDED")&&d(t,["old"],"Every chunk change but ADDED has an old chunk."),e.new===null!=(e.kind==="REMOVED")&&d(t,["new"],"Every chunk change but REMOVED has a new chunk."),e.pairing===null==(e.kind==="MODIFIED")&&d(t,["pairing"],"A MODIFIED pair names the rule that paired it; no other change has one.")}var Po=a.object({entry:R,kind:$r,pairing:Xr.nullable(),old:Qt.nullable(),new:Qt.nullable()}).strict().superRefine(Oo),wo=a.object({added:R,removed:R,modified:R,moved:R,unchanged:R}).strict();function ko(e,t){e.entries.forEach((o,i)=>{o.entry!==i&&d(t,["entries",i,"entry"],"Chunk entries are numbered from 0 in order.")});let n={ADDED:0,REMOVED:0,MODIFIED:0,MOVED:0};for(let o of e.entries)n[o.kind]++;let r=[["added",n.ADDED],["removed",n.REMOVED],["modified",n.MODIFIED],["moved",n.MOVED]];for(let[o,i]of r)e.stats[o]!==i&&d(t,["stats",o],`The ${o} count equals the number of entries of that kind.`)}var Fo=a.union([a.object({facet:cn,change:a.literal("UNCHANGED")}).strict(),a.object({facet:a.enum(["classification","metadata"]),change:a.literal("CHANGED"),fields:a.array(it).min(1)}).strict(),a.object({facet:a.enum(["labels","assets"]),change:a.literal("CHANGED"),added:a.array(Zt),removed:a.array(Zt),modified:a.array(Co),unchangedCount:R}).strict(),a.object({facet:a.literal("tags"),change:a.literal("CHANGED"),added:a.array(a.string()),removed:a.array(a.string()),unchangedCount:R}).strict(),a.object({facet:a.literal("structured_data"),change:a.literal("CHANGED"),operations:a.array(_o).min(1)}).strict(),a.object({facet:a.enum(["text","summary"]),change:a.literal("CHANGED"),...yn}).strict().superRefine((e,t)=>hn(e.hunks,t)),a.object({facet:a.literal("chunks"),change:a.literal("CHANGED"),stats:wo,entries:a.array(Po),textUnchangedChunkingChanged:a.boolean()}).strict().superRefine(ko)]),vs=a.object({diffEngineVersion:z,facets:a.array(Fo)}).strict().superRefine((e,t)=>{(e.facets.length!==de.length||e.facets.some((n,r)=>n.facet!==de[r]))&&d(t,["facets"],"A comparison carries every facet once, in display order.")}),Pe=e=>a.object({kind:a.literal("readable"),item:e}).strict(),Sn=a.object({kind:a.literal("restricted"),subject:a.literal("run"),startedAt:N,finishedAt:N.nullable(),status:Ze}).strict(),Ms=a.object({kind:a.literal("restricted"),subject:a.literal("ingest"),createdAt:N,updatedAt:N,syncStatus:wt.nullable()}).strict(),Us=a.object({kind:a.literal("restricted"),subject:a.literal("failure"),failedAt:N.nullable(),syncStatus:Vt}).strict(),Lo=a.object({kind:a.literal("restricted"),subject:a.literal("state"),settledAt:N}).strict(),vo=a.object({kind:a.literal("restricted"),subject:a.literal("change"),settledAt:N}).strict();function Mo(e,t){let n=e.cause==="RUN";e.runId!==null!==n&&d(t,["runId"],"A RUN state names its run; no other state does."),e.runOutcome!==null!==n&&d(t,["runOutcome"],"A RUN state carries the worker's outcome; no other state does."),e.changes!==null!=(e.previousStateId!==null)&&d(t,["changes"],"A state carries its counts exactly when its predecessor is readable."),e.diffEngineVersion!==null!=(e.changes!==null)&&d(t,["diffEngineVersion"],"The engine version comes with the counts it produced."),e.modelOnlyChange&&e.changes===null&&d(t,["modelOnlyChange"],"Only a change with counts can be a model-only change."),e.previousStateId===e.stateId&&d(t,["previousStateId"],"A state does not precede itself.")}var Uo=a.object({stateId:z,revision:z,cause:dn,runId:z.nullable(),runOutcome:Yr.nullable(),settledAt:N,actor:a.string().min(1),classification:a.object({confidentialityLevel:pn,departmentId:a.number().int().nullable(),folderPath:a.string().nullable()}).strict(),modelOnlyChange:a.boolean(),previousStateId:z.nullable(),changes:fn.nullable(),diffEngineVersion:z.nullable()}).strict().superRefine(Mo),zo=a.discriminatedUnion("kind",[Pe(Uo),Lo]),Ho=a.discriminatedUnion("kind",[Pe(qt),Sn]),zs=a.discriminatedUnion("kind",[Pe(Xt),Sn]),En=(e,t,n)=>{for(let r=1;r<e.length;r++)$(e[r-1],e[r])&&d(t,[...n,r],"Entries are listed newest first.")},De=e=>e.kind==="readable"?e.item.settledAt:e.settledAt;function jo(e,t){ce(e.revisions,(r,o)=>o.revision-r.revision,t,["revisions"],"Revisions are listed newest first, each once.");let n=e.revisions.filter(r=>r.isCurrent);(n.length!==1||n[0]?.metadataId!==e.document.metadataId||n[0].revision!==e.document.revision)&&d(t,["revisions"],"Exactly one revision is current: the row the history names."),En(e.states.map(De),t,["states"])}var Hs=a.object({document:a.object({metadataId:z,fileName:a.string().min(1),fileUri:a.string().min(1),revision:z,confidentialityLevel:pn}).strict(),revisions:a.array(a.object({metadataId:z,revision:z,revisionId:a.string().nullable(),isCurrent:a.boolean()}).strict()),states:a.array(zo),runs:a.array(Ho)}).strict().superRefine(jo),Ko=a.object({stateId:z,previousStateId:z,metadataId:z,fileName:a.string().min(1),fileUri:a.string().min(1),revision:z,previousRevision:z,cause:dn,actor:a.string().min(1),settledAt:N,changes:fn}).strict().superRefine((e,t)=>{e.previousStateId===e.stateId&&d(t,["previousStateId"],"A state does not precede itself.")}),Go=a.discriminatedUnion("kind",[Pe(Ko),vo]),bn=a.object({settledAt:N,id:z.max(Number.MAX_SAFE_INTEGER)}).strict(),ge="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function Bo(e){let t="";for(let n=0;n<e.length;n+=3){let r=e.length-n,o=e[n]<<16|(r>1?e[n+1]:0)<<8|(r>2?e[n+2]:0);t+=ge[o>>18&63]+ge[o>>12&63],r>1&&(t+=ge[o>>6&63]),r>2&&(t+=ge[o&63])}return t}function Vo(e){if(e.length%4===1)return null;let t=[],n=0,r=0;for(let o of e){let i=ge.indexOf(o);if(i===-1)return null;n=n<<6|i,r+=6,r>=8&&(r-=8,t.push(n>>r&255),n&=(1<<r)-1)}return Uint8Array.from(t)}function Yo(e){let{settledAt:t,id:n}=bn.parse(e);return Bo(new TextEncoder().encode(H({id:n,settledAt:t})))}function Jo(e){let t=Vo(e);if(t===null)return null;let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{return null}let r=bn.safeParse(n);return r.success&&Yo(r.data)===e?r.data:null}var js=a.object({rows:a.array(Go).max(ln),next:a.string().nullable()}).strict().superRefine((e,t)=>{En(e.rows.map(De),t,["rows"]),e.next!==null&&e.rows.length===0&&d(t,["next"],"An empty page has no next page.");let n=e.next===null?null:Jo(e.next);e.next!==null&&n===null&&d(t,["next"],"The next position is a cursor encodeChangeFeedCursor wrote.");let r=e.rows[e.rows.length-1];n!==null&&r!==void 0&&($(n.settledAt,De(r))||$(De(r),n.settledAt))&&d(t,["next"],"The next position is the arriving state of the page's last row."),n!==null&&r?.kind==="readable"&&n.id!==r.item.stateId&&d(t,["next"],"The next position names the arriving state of the page's last readable row.")}),Ks=a.object({outcome:ro}).strict();var Bs=Object.freeze({integrityRun:"integrity_run",resyncRequired:"resync-required"});import{z as p}from"zod";var Cn=[{code:"DEPLOYMENT_DISABLED",status:503,errorCode:5035},{code:"RUN_ALREADY_ACTIVE",status:409,errorCode:4091},{code:"BASIS_INVALID",status:409,errorCode:4092},{code:"RUN_ALREADY_FINISHED",status:409,errorCode:4093},{code:"FORBIDDEN",status:403,errorCode:null}];var _n={INTEGRITY_TOMBSTONE_RETENTION_DAYS:{min:1,max:3650},INTEGRITY_FINDING_SAMPLE_LIMIT:{min:1,max:5e3},INTEGRITY_RUN_HEARTBEAT_TIMEOUT_SECONDS:{min:30,max:3600},INTEGRITY_RUN_RETENTION_COUNT:{min:2,max:100},POLICY_CONFLICT_MAX_TIE_GROUP_SIZE:{min:2,max:60},CHILD_TREE_MAX_NODES:{min:1,max:1e5},CHILD_TREE_MAX_TOTAL_BYTES:{min:1048576,max:4294967296},CHILD_TREE_MAX_SECONDS:{min:60,max:3600},ARCHIVE_MAX_MEMBER_BYTES:{min:65536,max:1073741824},ARCHIVE_MAX_COMPRESSION_RATIO:{min:10,max:1e4},ARCHIVE_READER_MAX_MEMORY_BYTES:{min:268435456,max:17179869184}};var Xo=e=>{for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)},we=Xo(_n),Rn=e=>Object.hasOwn(we,e),In=(e,t)=>{let{min:n,max:r}=we[e];if(!Number.isInteger(t)||t<n||t>r)throw new RangeError(`${e} \u306F ${n}\u301C${r} \u306E\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)},qs=(e,t)=>{Rn(e)&&In(e,t)},Xs=(e,t)=>{if(!Rn(e))throw new TypeError(`The range table bounds no parameter named ${JSON.stringify(e)}.`);In(e,t)};var ct=p.enum(["QDRANT","NEO4J"]),Wo=p.enum(["PRODUCTION","VARIANT","LABEL"]),Tn=p.enum(["EXPECTED","LIVE","HISTORY","TOMBSTONE","AWAITING_SUCCESSOR","IN_FLIGHT","UNPLACED","UNRECORDED","UNREFERENCED","CHANGED_AFTER_START","PIPELINE_FAILED","PROJECTION_REFUSED","ORPHAN","TOMBSTONE_EXPIRED","UNPROPAGATED_DELETE","STALE_REVISION","MISPLACED","OUT_OF_TIER","UNMARKED_SUPERSEDED","FLAG_DRIFT","VARIANT_FLAG_DRIFT","DETACHED","UNKEYED","MISSING","COUNT_MISMATCH","UNPROJECTED","UNKEYED_ENTITY"]),Nn=Tn.exclude(["EXPECTED","LIVE","HISTORY"]),Zo=p.enum(["POINT","NODE","CHUNK","DOCUMENT"]),Qo=p.enum(["EXPECTED","HEALTHY","RETAINED","INFORMATIONAL","DISCREPANCY"]),ea=p.enum(["NONE","PURGE","FLAG","REPROJECT"]),P=(e,t)=>Object.freeze({disposition:e,repairAction:t}),ta=Object.freeze({EXPECTED:P("EXPECTED","NONE"),LIVE:P("HEALTHY","NONE"),HISTORY:P("RETAINED","NONE"),TOMBSTONE:P("RETAINED","NONE"),AWAITING_SUCCESSOR:P("RETAINED","NONE"),IN_FLIGHT:P("INFORMATIONAL","NONE"),UNPLACED:P("INFORMATIONAL","NONE"),UNRECORDED:P("INFORMATIONAL","NONE"),UNREFERENCED:P("INFORMATIONAL","NONE"),CHANGED_AFTER_START:P("INFORMATIONAL","NONE"),PIPELINE_FAILED:P("INFORMATIONAL","NONE"),PROJECTION_REFUSED:P("INFORMATIONAL","NONE"),ORPHAN:P("DISCREPANCY","PURGE"),TOMBSTONE_EXPIRED:P("DISCREPANCY","PURGE"),UNPROPAGATED_DELETE:P("DISCREPANCY","FLAG"),STALE_REVISION:P("DISCREPANCY","PURGE"),MISPLACED:P("DISCREPANCY","PURGE"),OUT_OF_TIER:P("DISCREPANCY","PURGE"),UNMARKED_SUPERSEDED:P("DISCREPANCY","FLAG"),FLAG_DRIFT:P("DISCREPANCY","REPROJECT"),VARIANT_FLAG_DRIFT:P("DISCREPANCY","NONE"),DETACHED:P("DISCREPANCY","PURGE"),UNKEYED:P("DISCREPANCY","PURGE"),MISSING:P("DISCREPANCY","REPROJECT"),COUNT_MISMATCH:P("DISCREPANCY","REPROJECT"),UNPROJECTED:P("DISCREPANCY","REPROJECT"),UNKEYED_ENTITY:P("DISCREPANCY","NONE")}),na=p.enum(["SCAN","REPAIR"]),ra=p.enum(["RUNNING","COMPLETED","FAILED","CANCELLED","ABANDONED"]),oa=p.enum(["CONSISTENT","INCONSISTENT","UNDETERMINED"]),aa=p.enum(["QDRANT","NEO4J","DOCUMENTS"]),ia=p.enum(["APPLIED","SKIPPED","FAILED"]),sa=p.enum(["RECLASSIFIED","IN_FLIGHT","DESTINATION_PENDING","BASIS_EXHAUSTED","PROJECTION_REFUSED","PIPELINE_FAILED","UNRECORDED","OUTSIDE"]),Dn=100,K=p.number().int().nonnegative(),ke=p.number().int().min(300).max(599),st=["repairedCount","repairFailedCount","repairSkippedCount"],On=p.string().regex(/^[0-9a-f]{64}$/,"A store fingerprint is 64 lowercase hexadecimal digits."),xn=we.INTEGRITY_TOMBSTONE_RETENTION_DAYS,la=p.object({runUid:ie,mode:na,status:ra,requestedBy:p.string().min(1),executor:p.string().min(1),basisRunUid:ie.nullable(),storeFingerprint:On,tombstoneRetentionDays:p.number().int().min(xn.min).max(xn.max),startedAt:N,finishedAt:N.nullable(),verdict:oa.nullable(),errorClass:p.string().min(1).nullable(),reprojectDocuments:K.nullable(),reprojectRebuildDocuments:K.nullable()}).strict(),ca=(e,t)=>{let n=e.status==="COMPLETED";e.mode==="REPAIR"!=(e.basisRunUid!==null)&&d(t,["basisRunUid"],"A REPAIR run names its basis SCAN run, and a SCAN run names none."),n!==(e.verdict!==null)&&d(t,["verdict"],"Only a COMPLETED run has a verdict."),n!==(e.reprojectDocuments!==null)&&d(t,["reprojectDocuments"],"Only a COMPLETED run has the count of documents to re-project.");let{reprojectDocuments:r,reprojectRebuildDocuments:o}=e;r===null||o===null?r!==o&&d(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are counted together with the documents it re-projects."):o>r&&d(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are no more than the documents it re-projects."),e.status==="RUNNING"!=(e.finishedAt===null)&&d(t,["finishedAt"],"Only a RUNNING run has not finished."),e.finishedAt!==null&&$(e.finishedAt,e.startedAt)&&d(t,["finishedAt"],"A run does not finish before it starts."),(e.status==="FAILED"||e.status==="ABANDONED")!=(e.errorClass!==null)&&d(t,["errorClass"],"Only a FAILED or ABANDONED run names an error class.")},dt=la.superRefine(ca),da=p.object({store:ct,scopeKey:p.string().min(1),scopeRole:Wo,itemClass:Tn,unit:Zo,disposition:Qo,repairAction:ea,itemCount:K.nullable(),unmeasuredReason:p.string().min(1).nullable(),measuredAt:N.nullable(),repairedCount:K.nullable(),repairFailedCount:K.nullable(),repairSkippedCount:K.nullable()}).strict(),ua=(e,t)=>{let n=ta[e.itemClass];e.disposition!==n.disposition&&d(t,["disposition"],`A ${e.itemClass} quantity is ${n.disposition}.`),e.repairAction!==n.repairAction&&d(t,["repairAction"],`A repair's action on ${e.itemClass} items is ${n.repairAction}.`);let r=e.itemCount===null;r!==(e.unmeasuredReason!==null)&&d(t,["unmeasuredReason"],"An unmeasured quantity (itemCount null) has a reason, and a measured one has none."),r!==(e.measuredAt===null)&&d(t,["measuredAt"],"Only a measured quantity has a measurement time.");let{repairedCount:o,repairFailedCount:i,repairSkippedCount:s}=e;if(o===null||i===null||s===null){if(st.some(l=>e[l]!==null))for(let l of st)e[l]===null&&d(t,[l],"The repaired, failed and skipped counts are recorded together or not at all.");return}e.repairAction==="NONE"&&d(t,["repairAction"],"Only a class with a repair action carries repair counts."),e.itemCount!==null&&o+i+s>e.itemCount&&d(t,["itemCount"],"The repaired, failed and skipped counts together do not exceed the measured count.")},pa=da.superRefine(ua),ma=p.object({run:dt,phase:aa.nullable(),phaseScope:p.string().min(1).nullable(),phaseDone:K.nullable(),phaseTotal:K.nullable(),heartbeatAt:N,isStale:p.boolean(),staleAfter:N,cancelRequestedAt:N.nullable()}).strict(),fa=(e,t)=>{if(e.run.status!=="RUNNING"&&d(t,["run","status"],"The active run is a RUNNING run."),$(e.heartbeatAt,e.run.startedAt)&&d(t,["heartbeatAt"],"A run's heartbeat is not earlier than its start."),N.safeParse(e.heartbeatAt).success&&N.safeParse(e.staleAfter).success&&!$(e.heartbeatAt,e.staleAfter)&&d(t,["staleAfter"],"A run's heartbeat goes stale only after it beat."),e.phase===null)for(let n of["phaseScope","phaseDone","phaseTotal"])e[n]!==null&&d(t,[n],"A run with no phase has no phase progress.");e.phase==="DOCUMENTS"&&e.phaseScope!==null&&d(t,["phaseScope"],"The DOCUMENTS phase scans no scope.")},ha=ma.superRefine(fa),ya=p.object({run:dt,quantities:p.array(pa),previousStoreFingerprint:On.nullable()}).strict(),ga=(e,t)=>{e.run.status!=="COMPLETED"&&d(t,["run","status"],"The last completed run is a COMPLETED run.");let n=new Set;for(let[r,o]of e.quantities.entries()){let i=JSON.stringify([o.store,o.scopeKey,o.itemClass]);if(n.has(i)&&d(t,["quantities",r],"A run records each (store, scope, class) cell once."),n.add(i),e.run.mode==="SCAN")for(let s of st)o[s]!==null&&d(t,["quantities",r,s],"A SCAN run repairs nothing, so its quantities carry no repair counts.")}},Sa=["FAILED","CANCELLED","ABANDONED"],Ea=p.object({run:dt,repairAppliedItems:K.nullable(),hasNewerRepair:p.boolean()}).strict(),ba=(e,t)=>{Sa.includes(e.run.status)||d(t,["run","status"],"A newer unsuccessful run is FAILED, CANCELLED or ABANDONED."),e.run.mode==="SCAN"&&e.repairAppliedItems!==null&&d(t,["repairAppliedItems"],"A SCAN run applies nothing."),e.run.mode==="REPAIR"&&!e.hasNewerRepair&&d(t,["hasNewerRepair"],"An unsuccessful REPAIR run is itself a repair newer than the last completed run.")},rl=p.object({readAt:N,lastCompleted:ya.superRefine(ga).nullable(),active:ha.nullable(),newerUnsuccessful:Ea.superRefine(ba).nullable()}).strict(),Ca=p.object({sequence:p.number().int().min(1),itemKey:p.string().min(1),metadataId:p.number().int().positive().nullable(),fileUri:p.string().nullable(),revision:p.number().int().nullable(),observed:p.record(p.string(),p.unknown()),repairOutcome:ia.nullable(),repairErrorClass:p.string().min(1).nullable(),repairSkipReason:sa.nullable()}).strict(),_a=(e,t)=>{e.repairOutcome==="FAILED"!=(e.repairErrorClass!==null)&&d(t,["repairErrorClass"],"Only a FAILED finding names an error class."),e.repairOutcome==="SKIPPED"!=(e.repairSkipReason!==null)&&d(t,["repairSkipReason"],"Only a SKIPPED finding names a skip reason.")},Ra=Ca.superRefine(_a),ol=p.object({sotDomain:p.string().nullable()}).passthrough(),Ia=p.object({rows:p.array(Ra),nextAfter:p.number().int().min(1).nullable(),recordedCount:K,totalCount:K.nullable()}).strict(),xa=(e,t)=>{for(let[n,r]of e.rows.entries()){let o=e.rows[n-1];o!==void 0&&r.sequence<=o.sequence&&d(t,["rows",n,"sequence"],"A page lists its rows in ascending sequence.")}e.nextAfter!==null&&e.nextAfter!==e.rows.at(-1)?.sequence&&d(t,["nextAfter"],"The next page starts after the sequence of this page's last row.")},al=Ia.superRefine(xa),il=p.object({runUid:ie,store:ct,scopeKey:p.string().min(1),itemClass:Nn,after:p.number().int().min(1).optional(),limit:p.number().int().min(1).max(Dn)}).strict(),sl=p.object({runUid:ie,store:ct,scopeKey:p.string().min(1),itemClass:Nn.extract(["UNRECORDED"]),after:p.number().int().min(1).optional()}).strict(),Aa=p.object({requeued:K,skipped:p.array(p.object({metadataId:p.number().int().min(1),reason:p.string().min(1)}).strict()),nextAfter:p.number().int().min(1).nullable()}).strict(),ll=Aa.superRefine(xe(Dn)),ut=p.enum(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),An=p.enum(["start","cancel"]),Ta=ut.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","FORBIDDEN","UPSTREAM_FAILED"]),Na=ut.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),lt={start:Ta,cancel:Na},Da=p.object({code:ut.exclude(["UPSTREAM_FAILED"]),status:ke,errorCode:p.number().int().nullable()}).strict(),Pn=Object.freeze(p.array(Da).parse(Cn).map(e=>Object.freeze(e))),Oa=(e,t)=>{e.code==="UPSTREAM_FAILED"||e.code==="FORBIDDEN"&&e.status===null||Pn.some(n=>n.code===e.code&&n.status===e.status)||d(t,["status"],`A ${e.code} failure carries the status of its row in the code table.`)},cl=p.discriminatedUnion("command",[p.object({command:An.extract(["start"]),code:lt.start,status:ke.nullable()}).strict(),p.object({command:An.extract(["cancel"]),code:lt.cancel,status:ke.nullable()}).strict()]).superRefine(Oa),dl=(e,t,n)=>{let r=lt[e],o=Pn.find(i=>i.status===t&&(i.errorCode===null||i.errorCode===n)&&r.safeParse(i.code).success);return o===void 0?"UPSTREAM_FAILED":o.code},ul=p.discriminatedUnion("ok",[p.object({ok:p.literal(!0),runUid:ie}).strict(),p.object({ok:p.literal(!1),status:ke,errorCode:p.number().int().nullable()}).strict()]);function Pa(e){let t=[];for(let r=0;r<e.length;r++){t.push(r);let o=e.charCodeAt(r);o>=55296&&o<=56319&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320&&r++}t.push(e.length);let n=t.length-1;return{length:n,slice(r,o){if(!(Number.isInteger(r)&&Number.isInteger(o))||r<0||r>o)throw new RangeError(`A code-point span is [charStart, charEnd) with 0 <= charStart <= charEnd: [${r}, ${o})`);return o>n?null:e.slice(t[r],t[o])}}}var wa=e=>e.replace(/\s/gu,"");function ee(e,t){let n=new Map,r=i=>{let s=new Int32Array(i.length);return i.forEach((l,c)=>{let h=n.get(l);h===void 0&&(h=n.size,n.set(l,h)),s[c]=h}),s};return{old:r(e),new:r(t),alphabetSize:n.size}}function Fe(e,t,n,r){if(r===0)return;let o=e[e.length-1];if(o!==void 0&&o.oldStart+o.length===t&&o.newStart+o.length===n){o.length+=r;return}e.push({oldStart:t,newStart:n,length:r})}function wn(e,t,n,r,o,i,s){let l=0;for(;n+l<r&&o+l<i&&e[n+l]===t[o+l];)l++;Fe(s,n,o,l);let c=0;for(;r-c>n+l&&i-c>o+l&&e[r-1-c]===t[i-1-c];)c++;return{oldLow:n+l,oldHigh:r-c,newLow:o+l,newHigh:i-c,suffix:c}}function ka(e,t,n){let{oldLow:r,oldHigh:o,newLow:i,newHigh:s}=n,l=o-r,c=s-i,h=Math.ceil((l+c)/2),u=h,y=2*h+2,E=new Int32Array(y).fill(-1),A=new Int32Array(y).fill(-1);E[u+1]=0,A[u+1]=0;let b=l-c,O=b%2!==0,w=0,g=0,D=0,f=0;for(let _=0;_<h;_++){for(let T=-_+w;T<=_-g;T+=2){let I=u+T,x=T===-_||T!==_&&E[I-1]<E[I+1]?E[I+1]:E[I-1]+1,v=x-T;for(;x<l&&v<c&&e[r+x]===t[i+v];)x++,v++;if(E[I]=x,x>l)g+=2;else if(v>c)w+=2;else if(O){let U=u+b-T;if(U>=0&&U<y&&A[U]!==-1&&x>=l-A[U])return{kind:"split",oldSplit:r+x,newSplit:i+v}}}for(let T=-_+D;T<=_-f;T+=2){let I=u+T,x=T===-_||T!==_&&A[I-1]<A[I+1]?A[I+1]:A[I-1]+1,v=x-T;for(;x<l&&v<c&&e[o-1-x]===t[s-1-v];)x++,v++;if(A[I]=x,x>l)f+=2;else if(v>c)D+=2;else if(!O){let U=u+b-T;if(U>=0&&U<y&&E[U]!==-1){let C=E[U];if(C>=l-x)return{kind:"split",oldSplit:r+C,newSplit:i+u+C-U}}}}}return{kind:"disjoint"}}function te(e,t){let n=[],r=[{kind:"region",oldLow:0,oldHigh:e.length,newLow:0,newHigh:t.length}];for(let o=r.pop();o!==void 0;o=r.pop()){if(o.kind==="run"){Fe(n,o.oldStart,o.newStart,o.length);continue}let i=wn(e,t,o.oldLow,o.oldHigh,o.newLow,o.newHigh,n);if(r.push({kind:"run",oldStart:i.oldHigh,newStart:i.newHigh,length:i.suffix}),i.oldLow===i.oldHigh||i.newLow===i.newHigh)continue;let s=ka(e,t,i);s.kind==="split"&&(r.push({kind:"region",oldLow:s.oldSplit,oldHigh:i.oldHigh,newLow:s.newSplit,newHigh:i.newHigh}),r.push({kind:"region",oldLow:i.oldLow,oldHigh:s.oldSplit,newLow:i.newLow,newHigh:s.newSplit}))}return n}function kn(e,t,n){let r=Math.ceil(t.length/32),o=new Array(n);t.forEach((l,c)=>{let h=o[l];h===void 0&&(h=new Uint32Array(r),o[l]=h),h[c>>>5]=(h[c>>>5]|1<<(c&31))>>>0});let i=new Uint32Array(r).fill(4294967295);for(let l of e){let c=o[l];if(c===void 0)continue;let h=0;for(let u=0;u<r;u++){let y=i[u],E=(y&c[u])>>>0,A=y+E+h;h=A>4294967295?1:0,i[u]=(A>>>0|y&~c[u])>>>0}}let s=0;for(let l=0;l<t.length;l++)s+=i[l>>>5]>>>(l&31)&1;return t.length-s}function Fa(e,t,n){if(e.occurrences!==t.occurrences)return e.occurrences<t.occurrences;if(e.length!==t.length)return e.length>t.length;let r=Math.abs(2*e.oldStart+e.length-n),o=Math.abs(2*t.oldStart+t.length-n);return r!==o?r<o:e.newStart<t.newStart||e.newStart===t.newStart&&e.oldStart<t.oldStart}function Fn(e,t){let{old:n,new:r,alphabetSize:o}=e,i=new Int32Array(o),s=new Int32Array(o),l=new Int32Array(o).fill(-1),c=new Int32Array(n.length),h=[],u=[{kind:"region",oldLow:0,oldHigh:n.length,newLow:0,newHigh:r.length}];for(let y=u.pop();y!==void 0;y=u.pop()){if(y.kind==="run"){Fe(h,y.oldStart,y.newStart,y.length);continue}let E=wn(n,r,y.oldLow,y.oldHigh,y.newLow,y.newHigh,h),A={kind:"run",oldStart:E.oldHigh,newStart:E.newHigh,length:E.suffix},{oldLow:b,oldHigh:O,newLow:w,newHigh:g}=E;if(b===O||w===g){u.push(A);continue}for(let I=O-1;I>=b;I--){let x=n[I];i[x]++,c[I]=l[x],l[x]=I}let D={best:null},f=I=>{(D.best===null||Fa(I,D.best,b+O))&&(D.best=I)},_=new Map;for(let I=w;I<g;I++){let x=r[I],v=i[x];if(!(v===0||v>t.maxOccurrences||D.best!==null&&v>D.best.occurrences))for(let U=l[x];U!==-1;U=c[U]){let C=_.get(I-U);if(C!==void 0&&I>=C.newStart&&I<C.newEnd){v<C.occurrences&&(C.occurrences=v,f({occurrences:v,oldStart:C.oldStart,newStart:C.newStart,length:C.newEnd-C.newStart}));continue}let M=U,F=I;for(;M>b&&F>w&&n[M-1]===r[F-1];)M--,F--;let j=U-M+1;for(;M+j<O&&F+j<g&&n[M+j]===r[F+j];)j++;_.set(I-U,{oldStart:M,newStart:F,newEnd:F+j,occurrences:v}),f({occurrences:v,oldStart:M,newStart:F,length:j})}}let T=D.best;T!==null?(u.push(A),u.push({kind:"region",oldLow:T.oldStart+T.length,oldHigh:O,newLow:T.newStart+T.length,newHigh:g}),u.push({kind:"run",oldStart:T.oldStart,newStart:T.newStart,length:T.length}),u.push({kind:"region",oldLow:b,oldHigh:T.oldStart,newLow:w,newHigh:T.newStart})):(La(n,r,E,i,s,t.cellBound,h),u.push(A));for(let I=b;I<O;I++){let x=n[I];i[x]=0,l[x]=-1}}return h}function La(e,t,n,r,o,i,s){let{oldLow:l,oldHigh:c,newLow:h,newHigh:u}=n;if((c-l)*(u-h)>i)return;for(let b=h;b<u;b++)o[t[b]]++;let y=[];for(let b=l;b<c;b++)o[e[b]]>0&&y.push(b);let E=[];for(let b=h;b<u;b++)r[t[b]]>0&&E.push(b),o[t[b]]=0;let A=te(Int32Array.from(y,b=>e[b]),Int32Array.from(E,b=>t[b]));for(let b of A)for(let O=0;O<b.length;O++)Fe(s,y[b.oldStart+O],E[b.newStart+O],1)}function Ln(e,t,n){let r=[],o=0,i=0;for(let s of[...n,{oldStart:e,newStart:t,length:0}])(s.oldStart>o||s.newStart>i)&&r.push({oldStart:o,oldEnd:s.oldStart,newStart:i,newEnd:s.newStart}),o=s.oldStart+s.length,i=s.newStart+s.length;return r}function pt(e,t,n,r){let o=new Map;for(let s of t){let l=r(s);l!==null&&o.set(l,[...o.get(l)??[],s])}let i=[];for(let s of e){let l=n(s),c=l===null?void 0:o.get(l)?.shift();c!==void 0&&i.push([s,c])}return i}function vn(e,t){let n=new Map;for(let r of e){let o=t[r].clause;o!==null&&n.set(o,(n.get(o)??0)+1)}return n}var Y=e=>e.flatMap((t,n)=>t===null?[n]:[]);function mt(e,t){let n=e?.children??[],r=t?.children??[],o=ee(n.map(f=>f.hash),r.map(f=>f.hash)),i=n.map(()=>null),s=r.map(()=>null),l=[],c=n.map(()=>0),h=r.map(()=>0);for(let f of te(o.old,o.new))for(let _=0;_<f.length;_++)i[f.oldStart+_]=f.newStart+_,s[f.newStart+_]=f.oldStart+_;let u=0;n.forEach((f,_)=>{c[_]=u,u+=i[_]===null?0:1}),u=0,r.forEach((f,_)=>{h[_]=u,s[_]!==null&&(l.push(_),u++)});let y=[],E=(f,_,T)=>{for(let[I,x]of f)i[I]=x,s[x]=I,y.push({entry:{kind:_,pairing:T,oldPosition:I,newPosition:x},order:[x,1,x]})},A=f=>n[f],b=f=>r[f];E(pt(Y(i),Y(s),f=>A(f).hash,f=>b(f).hash),"MOVED",null);let O=vn(Y(i),n),w=vn(Y(s),r),g=f=>f.clause!==null&&O.get(f.clause)===1&&w.get(f.clause)===1?f.clause:null;E(pt(Y(i),Y(s),f=>g(A(f)),f=>g(b(f))),"MODIFIED","clause"),E(pt(Y(i),Y(s),f=>JSON.stringify([c[f],A(f).breadcrumbs]),f=>JSON.stringify([h[f],b(f).breadcrumbs])),"MODIFIED","breadcrumbs");for(let f of Y(i)){let _=c[f],T=_===0?0:l[_-1]+1;y.push({entry:{kind:"REMOVED",pairing:null,oldPosition:f,newPosition:null},order:[T,0,f]})}for(let f of Y(s))y.push({entry:{kind:"ADDED",pairing:null,oldPosition:null,newPosition:f},order:[f,1,f]});y.sort((f,_)=>f.order[0]-_.order[0]||f.order[1]-_.order[1]||f.order[2]-_.order[2]);let D=f=>y.filter(({entry:_})=>_.kind===f).length;return{entries:y.map(({entry:f})=>f),stats:{added:D("ADDED"),removed:D("REMOVED"),modified:D("MODIFIED"),moved:D("MOVED"),unchanged:l.length}}}var Le=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ue=(e,t)=>`${e}/${String(t).replace(/~/g,"~0").replace(/\//g,"~1")}`;function ft(e,t,n,r,o){H(t)!==H(n)&&(Le(t)&&Le(n)?va(e,t,n,r,o):Array.isArray(t)&&Array.isArray(n)?Ma(e,t,n,r,o):r.push({op:"replace",path:e,value:n,previous:t}))}function va(e,t,n,r,o){let i=[...new Set([...Object.keys(t),...Object.keys(n)])].sort(q);for(let s of i){let l=ue(e,s);Object.hasOwn(n,s)?Object.hasOwn(t,s)?ft(l,t[s],n[s],r,o):r.push({op:"add",path:l,value:n[s]}):r.push({op:"remove",path:l,previous:t[s]})}}function Ma(e,t,n,r,o){let i=ee(t.map(H),n.map(H)),s=0;for(;s<t.length&&s<n.length&&i.old[s]===i.new[s];)s++;let l=0;for(;l<t.length-s&&l<n.length-s&&i.old[t.length-1-l]===i.new[n.length-1-l];)l++;let c=(t.length-s-l)*(n.length-s-l);if(c>o.remaining){r.push({op:"replace",path:e,value:n,previous:t});return}o.remaining-=c;let h=0,u=0,y=0;for(let E of[...te(i.old,i.new),{oldStart:t.length,newStart:n.length,length:0}]){let A=t.slice(u,E.oldStart),b=n.slice(y,E.newStart),O=Math.min(A.length,b.length);for(let w=0;w<O;w++){let g=A[w],D=b[w];Le(g)&&Le(D)||Array.isArray(g)&&Array.isArray(D)?ft(ue(e,h),g,D,r,o):(r.push({op:"remove",path:ue(e,h),previous:g}),r.push({op:"add",path:ue(e,h),value:D})),h++}for(let w of A.slice(O))r.push({op:"remove",path:ue(e,h),previous:w});for(let w of b.slice(O))r.push({op:"add",path:ue(e,h),value:w}),h++;h+=E.length,u=E.oldStart+E.length,y=E.newStart+E.length}}function ht(e,t){let n=[];return ft("",e,t,n,{remaining:an}),n}function Mn(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="object"||n===null||Array.isArray(n))continue;let{start:r,end:o,page_number:i}=n;Number.isInteger(r)&&Number.isInteger(o)&&Number.isInteger(i)&&t.push({start:r,end:o,pageNumber:i})}return t.sort((n,r)=>n.start-r.start)}function yt(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].start<=t?n=i+1:r=i}let o=e[n-1];return o!==void 0&&t<o.end?o.pageNumber:null}function Un(e){let t=[],n=[],r={LF:0,CRLF:0,CR:0},o=0,i=0,s=0;for(let u=0;u<e.length;){let y=e.charCodeAt(u);if(y===10||y===13){t.push(e.slice(o,u)),n.push(s);let E=y===13&&e.charCodeAt(u+1)===10?2:1;r[E===2?"CRLF":y===13?"CR":"LF"]++,u+=E,i+=E,o=u,s=i;continue}u+=y>=55296&&y<=56319&&(e.charCodeAt(u+1)&64512)===56320?2:1,i++}o<e.length&&(t.push(e.slice(o)),n.push(s));let l=r.LF+r.CRLF+r.CR,c=["LF","CRLF","CR"].filter(u=>r[u]>0),h=l===0?"NONE":c.length===1?c[0]:"MIXED";return{lines:t,starts:n,lineEnding:h,finalNewline:l>0&&o===e.length}}var zn=null;function Hn(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>767)return!1;return!0}function Et(e){return Hn(e)?e.split(""):(zn??=new Intl.Segmenter("und",{granularity:"grapheme"}),Array.from(zn.segment(e),t=>t.segment))}function gt(e){return Hn(e)?e.length:Et(e).length}function Ua(e,t,n){let r=e.length+t.length;if(n.exhausted||e.length>nt||t.length>nt||r===0)return null;let o=ee(e,t),i=kn(o.old,o.new,o.alphabetSize);if(2*i/r<rt||r-2*i>rn)return null;let s=r*(r-2*i);if(s>n.remaining)return n.exhausted=!0,null;n.remaining-=s;let l=te(o.old,o.new),c=[],h=0,u=0;for(let g of[...l,{oldStart:e.length,newStart:t.length,length:0}])(g.oldStart>h||g.newStart>u)&&c.push({equal:!1,oldStart:h,oldEnd:g.oldStart,newStart:u,newEnd:g.newStart}),g.length>0&&c.push({equal:!0,oldStart:g.oldStart,oldEnd:g.oldStart+g.length,newStart:g.newStart,newEnd:g.newStart+g.length}),h=g.oldStart+g.length,u=g.newStart+g.length;let y=[];c.forEach((g,D)=>{let f=y[y.length-1],_=f!==void 0&&!f.equal,T=g.equal&&g.oldEnd-g.oldStart<=1&&_&&D+1<c.length;if(_&&(T||!g.equal)){f.oldEnd=g.oldEnd,f.newEnd=g.newEnd;return}y.push({...g})});let E=0,A=0,b=0,O=[],w=[];for(let g of y){let D=e.slice(g.oldStart,g.oldEnd).join(""),f=t.slice(g.newStart,g.newEnd).join("");if(g.equal){E+=g.oldEnd-g.oldStart,O.push({kind:"equal",text:D}),w.push({kind:"equal",text:f});continue}A+=g.oldEnd-g.oldStart,b+=g.newEnd-g.newStart,D!==""&&O.push({kind:"removed",text:D}),f!==""&&w.push({kind:"added",text:f})}return 2*E/r<rt?null:{oldSegments:O,newSegments:w,removed:A,added:b}}var jn={old:[],new:[]};function Se(e){return e.filter(([,t,n])=>H(t)!==H(n)).map(([t,n,r])=>({field:t,before:n,after:r}))}var St=(e,t)=>t===""?[]:[{kind:e,text:t}];function za(e,t,n){let r=[],o=(l,c)=>({kind:"context",oldNumber:l+1,newNumber:c+1,page:yt(n.pages.new,n.newText.starts[c]),segments:St("equal",n.newText.lines[c])}),i=t.oldStart,s=t.newStart;for(let l of e){for(;i<l.oldStart;i++,s++)r.push(o(i,s));for(let c=l.oldStart;c<l.oldEnd;c++){let h=n.oldText.lines[c];r.push({kind:"removed",oldNumber:c+1,newNumber:null,page:yt(n.pages.old,n.oldText.starts[c]),segments:n.removedSegments.get(c)??St("removed",h)})}for(let c=l.newStart;c<l.newEnd;c++){let h=n.newText.lines[c];r.push({kind:"added",oldNumber:null,newNumber:c+1,page:yt(n.pages.new,n.newText.starts[c]),segments:n.addedSegments.get(c)??St("added",h)})}i=l.oldEnd,s=l.newEnd}for(;i<t.oldEnd;i++,s++)r.push(o(i,s));return r}function bt(e,t,n,r){let o=Un(e??""),i=Un(t??""),s=Se([["present",e!==null,t!==null],["lineEnding",o.lineEnding,i.lineEnding],["finalNewline",o.finalNewline,i.finalNewline]]),l=Fn(ee(o.lines,i.lines),{maxOccurrences:tn,cellBound:nn}),c=Ln(o.lines.length,i.lines.length,l),h=new Map,u=new Map,y={remaining:on,exhausted:!1},E=0,A=0,b=0,O=0,w=0,g=0;for(let C of c){b+=C.oldEnd-C.oldStart,O+=C.newEnd-C.newStart;let M=Math.min(C.oldEnd-C.oldStart,C.newEnd-C.newStart);for(let F=0;C.oldStart+F<C.oldEnd||C.newStart+F<C.newEnd;F++){let j=C.oldStart+F,G=C.newStart+F;if(F>=M){let me=j<C.oldEnd?gt(o.lines[j]):0,re=G<C.newEnd?gt(i.lines[G]):0;w+=me,g+=re,E+=me,A+=re;continue}let J=Et(o.lines[j]),W=Et(i.lines[G]);w+=J.length,g+=W.length;let Z=Ua(J,W,y);if(Z!==null){h.set(j,Z.oldSegments),u.set(G,Z.newSegments),E+=Z.removed,A+=Z.added;continue}E+=J.length,A+=W.length}}let D=0;for(let C of l)for(let M=C.oldStart;M<C.oldStart+C.length;M++)D+=gt(o.lines[M]);let f=D+w,_=D+g,T={linesAdded:O,linesRemoved:b,linesUnchanged:o.lines.length-b,charsAdded:A,charsRemoved:E,similarity:f+_===0?null:2*(f-E)/(f+_)},I=r==="whole"?Math.max(o.lines.length,i.lines.length):r,x=[];for(let C of c){let M=x[x.length-1],F=M?.[M.length-1];M!==void 0&&F!==void 0&&C.oldStart-F.oldEnd<=2*I?M.push(C):x.push([C])}let v={oldText:o,newText:i,pages:n,removedSegments:h,addedSegments:u},U=x.map((C,M)=>{let F=C[0],j=C[C.length-1],G=Math.max(0,F.oldStart-I),J=F.newStart-(F.oldStart-G),W=Math.min(o.lines.length,j.oldEnd+I),Z=j.newEnd+(W-j.oldEnd),me=za(C,{oldStart:G,oldEnd:W,newStart:J},v);return{hunk:M,oldStart:W>G?G+1:G,oldLines:W-G,newStart:Z>J?J+1:J,newLines:Z-J,firstPage:me[0].page,linesAdded:C.reduce((re,fe)=>re+fe.newEnd-fe.newStart,0),linesRemoved:C.reduce((re,fe)=>re+fe.oldEnd-fe.oldStart,0),lines:me}});return{attributes:s,stats:T,hunks:U}}function ve(e,t){let n=bt(e.body,t.body,{old:Mn(e.pageOffsets),new:Mn(t.pageOffsets)},tt),r=Se([["mime",e.mime,t.mime],["source",e.source,t.source],["isTruncated",e.isTruncated,t.isTruncated],["pageOffsets",e.pageOffsets,t.pageOffsets]]);return{...n,attributes:[...r,...n.attributes]}}function Me(e,t){return bt(e,t,jn,tt)}function Ha(e,t){return bt(e,t,jn,"whole")}function Ue(e){return{attributes:[...e.attributes],stats:e.stats,hunks:e.hunks.map(({lines:t,...n})=>n)}}function ja(e,t,n,r){let o=Number.isInteger(t)&&t>=0?e.hunks[t]:void 0;if(o===void 0)throw new RangeError(`The diff has no hunk ${t}.`);if(!Number.isInteger(n)||n<0||n>=o.lines.length)throw new RangeError(`Hunk ${t} has no line at offset ${n}.`);if(!gn.safeParse(r).success)throw new RangeError(`A line page holds 1 to the page maximum lines, not ${r}.`);let i=Math.min(n+r,o.lines.length);return{lines:o.lines.slice(n,i),next:i<o.lines.length?i:null}}function ze(e,t,n){let r=[...e].sort(t);for(let o=1;o<r.length;o++)if(t(r[o-1],r[o])===0)throw new RangeError(`A facet set holds the key ${JSON.stringify(n(r[o]))} more than once.`);return r}function Kn(e,t,n,r){let o=0,i=0;for(;o<e.length||i<t.length;){let s=e[o],l=t[i],c=s===void 0?1:l===void 0?-1:n(s,l);r(c<=0?s:null,c>=0?l:null),o+=c<=0?1:0,i+=c>=0?1:0}}function Ct(e,t){let n=[],r=[],o=0;return Kn(ze(e??[],q,String),ze(t??[],q,String),q,(i,s)=>{i!==null&&s!==null?o++:i!==null?r.push(i):n.push(s)}),{added:n,removed:r,unchangedCount:o}}function Gn(e,t,n){let r=[],o=[],i=[],s=0;return Kn(ze(e,n.compare,n.keyOf),ze(t,n.compare,n.keyOf),n.compare,(l,c)=>{if(l===null){r.push({key:n.keyOf(c),value:{...c}});return}if(c===null){o.push({key:n.keyOf(l),value:{...l}});return}let h=new Map(n.fieldsOf(c)),u=Se(n.fieldsOf(l).map(([y,E])=>[y,E,h.get(y)]));u.length===0?s++:i.push({key:n.keyOf(l),fields:u})}),{added:r,removed:o,modified:i,unchangedCount:s}}var Ka={compare:(e,t)=>q(e.labelKey,t.labelKey),keyOf:e=>e.labelKey,fieldsOf:e=>[["assignedBy",e.assignedBy],["confidenceScore",e.confidenceScore]]},Ga={compare:ot,keyOf:ae,fieldsOf:e=>[["mimeType",e.mimeType],["fileSize",e.fileSize],["textSha256",e.textSha256]]},_t=(e,t)=>Gn(e,t,Ka),Rt=(e,t)=>Gn(e,t,Ga);function Ee(e,t,n){return Se(n.map(r=>[r,e[r],t[r]]))}var Yn=["confidentialityLevel","departmentId","folderPath","createdBy"],Jn=["fileName","filePath","fileId","revision","revisionId","fileSize","mimeType","fileHash","mtime"],ne=(e,t)=>({facet:e,addedCount:null,removedCount:null,modifiedCount:null,movedCount:null,unchangedCount:null,charsAdded:null,charsRemoved:null,...t}),Bn=(e,t)=>ne(e,{addedCount:t.stats.linesAdded,removedCount:t.stats.linesRemoved,unchangedCount:t.stats.linesUnchanged,charsAdded:t.stats.charsAdded,charsRemoved:t.stats.charsRemoved});function Ba(e){switch(e.facet){case"classification":return ne("classification",{modifiedCount:Ee(e.from,e.to,Yn).length});case"metadata":return ne("metadata",{modifiedCount:Ee(e.from,e.to,Jn).length});case"labels":case"assets":{let t=e.facet==="labels"?_t(e.from,e.to):Rt(e.from,e.to);return ne(e.facet,{addedCount:t.added.length,removedCount:t.removed.length,modifiedCount:t.modified.length,unchangedCount:t.unchangedCount})}case"tags":{let t=Ct(e.from,e.to);return ne("tags",{addedCount:t.added.length,removedCount:t.removed.length,unchangedCount:t.unchangedCount})}case"structured_data":{let t=ht(e.from,e.to),n=r=>t.filter(o=>o.op===r).length;return ne("structured_data",{addedCount:n("add"),removedCount:n("remove"),modifiedCount:n("replace")})}case"text":return Bn("text",ve(e.from,e.to));case"summary":return Bn("summary",Me(e.from,e.to));case"chunks":{let{stats:t}=mt(e.from,e.to);return ne("chunks",{addedCount:t.added,removedCount:t.removed,modifiedCount:t.modified,movedCount:t.moved,unchangedCount:t.unchanged})}}}function Va(e){if(e.length===0)throw new RangeError("A change has at least one changed facet.");let t=new Set;for(let n of e){if(t.has(n.facet))throw new RangeError(`The ${n.facet} facet is given twice.`);if(t.add(n.facet),H(n.from)===H(n.to))throw new RangeError(`The ${n.facet} facet has equal values on both sides, so it did not change.`)}return[...e].sort((n,r)=>at(n.facet,r.facet)).map(Ba)}var Ya=(e,t)=>({index:e.index,charStart:e.charStart,charEnd:e.charEnd,page:e.page,sheet:e.sheet,slide:e.slide,startSec:e.startSec,endSec:e.endSec,breadcrumbs:e.breadcrumbs,tokenCount:e.tokenCount,fidelity:t});function Vn(e,t){let n=e.facets.chunks?.children.length??0;if(e.chunkFidelities.length!==n)throw new RangeError(`The ${t} state has ${n} child chunks but ${e.chunkFidelities.length} fidelity checks.`)}function Ja(e,t,n){let r=t.facets,o=n.facets;if(H(r[e])===H(o[e]))return{facet:e,change:"UNCHANGED"};switch(e){case"classification":return{facet:e,change:"CHANGED",fields:Ee(r.classification,o.classification,Yn)};case"metadata":return{facet:e,change:"CHANGED",fields:Ee(r.metadata,o.metadata,Jn)};case"labels":case"assets":{let i=e==="labels"?_t(r.labels,o.labels):Rt(r.assets,o.assets);return{facet:e,change:"CHANGED",added:[...i.added],removed:[...i.removed],modified:[...i.modified],unchangedCount:i.unchangedCount}}case"tags":{let i=Ct(r.tags,o.tags);return{facet:e,change:"CHANGED",added:[...i.added],removed:[...i.removed],unchangedCount:i.unchangedCount}}case"structured_data":return{facet:e,change:"CHANGED",operations:ht(r.structured_data,o.structured_data)};case"text":return{facet:e,change:"CHANGED",...Ue(ve(r.text,o.text))};case"summary":return{facet:e,change:"CHANGED",...Ue(Me(r.summary,o.summary))};case"chunks":{let i=mt(r.chunks,o.chunks),s=r.chunks?.children??[],l=o.chunks?.children??[],c=(h,u,y)=>y===null?null:Ya(h[y],u[y]);return{facet:e,change:"CHANGED",stats:i.stats,entries:i.entries.map((h,u)=>({entry:u,kind:h.kind,pairing:h.pairing,old:c(s,t.chunkFidelities,h.oldPosition),new:c(l,n.chunkFidelities,h.newPosition)})),textUnchangedChunkingChanged:r.text.body===o.text.body}}}}function $a(e,t){return Vn(e,"from"),Vn(t,"to"),{diffEngineVersion:en,facets:de.map(n=>Ja(n,e,t))}}import{z as k}from"zod";var qa=["caller_google_token","caller_identity","deployment"],Xa=["describe","name_children"],It="su",He=k.object({ja:k.string().regex(/\S/),en:k.string().regex(/\S/)}).strict();function $n(e){try{return new RegExp(`^(?:${e})$`,It)}catch{return null}}function qn(e){try{return new RegExp(e,It)}catch{return null}}function Wa(e){let t=new RegExp(`${e}|`,It).exec("");return t===null?0:t.length-1}var Za=k.object({scheme:k.string().regex(/^[a-z][a-z0-9+.-]{0,31}$/),title:He,description:He,uri_prefix:k.string(),input_pattern:k.string(),input_example:k.string(),input_hint:He,guidance:He,paste_patterns:k.array(k.string()),credential:k.enum(qa),capabilities:k.array(k.enum(Xa)),delivered_mime_type:k.string().min(1).nullable()}).strict().superRefine((e,t)=>{e.uri_prefix.startsWith(`${e.scheme}://`)||t.addIssue({code:k.ZodIssueCode.custom,path:["uri_prefix"],message:`The URI prefix does not start with ${e.scheme}://.`});let n=$n(e.input_pattern);n===null?t.addIssue({code:k.ZodIssueCode.custom,path:["input_pattern"],message:"The input pattern does not compile with the s and u flags."}):n.test(e.input_example)||t.addIssue({code:k.ZodIssueCode.custom,path:["input_example"],message:"The input example does not fully match the input pattern."}),e.paste_patterns.forEach((r,o)=>{qn(r)===null?t.addIssue({code:k.ZodIssueCode.custom,path:["paste_patterns",o],message:"The paste pattern does not compile with the s and u flags."}):Wa(r)!==1&&t.addIssue({code:k.ZodIssueCode.custom,path:["paste_patterns",o],message:"A paste pattern has exactly one capturing group, the identifier."})}),new Set(e.capabilities).size!==e.capabilities.length&&t.addIssue({code:k.ZodIssueCode.custom,path:["capabilities"],message:"A capability is declared twice."})}),Kl=k.object({sources:k.array(Za)}).strict().superRefine((e,t)=>{let n=e.sources.map(r=>r.scheme);new Set(n).size!==n.length&&t.addIssue({code:k.ZodIssueCode.custom,path:["sources"],message:"A scheme is registered twice."})});function Gl(e,t){let n=t.trim();return[...e].sort((r,o)=>o.uri_prefix.length-r.uri_prefix.length).find(r=>n.startsWith(r.uri_prefix))}function Bl(e,t){return $n(e.input_pattern)?.test(t)??!1}function Vl(e,t){for(let n of e)for(let r of n.paste_patterns){let o=qn(r)?.exec(t)?.[1];if(o!==void 0)return{source:n,identifier:o}}}var Xn=[{key:"enable_summary_generation",featureFlagKey:null,label:"\u8981\u7D04\u751F\u6210",readByPipeline:!1},{key:"enable_structured_extraction",featureFlagKey:null,label:"\u69CB\u9020\u5316\u62BD\u51FA",readByPipeline:!1},{key:"enable_asset_extraction",featureFlagKey:"ENABLE_ASSET_EXTRACTION",label:"\u30A2\u30BB\u30C3\u30C8\u62BD\u51FA",readByPipeline:!1},{key:"enable_vector_indexing",featureFlagKey:"ENABLE_VECTOR_INDEXING",label:"\u30D9\u30AF\u30C8\u30EB\u7D22\u5F15",readByPipeline:!0},{key:"enable_graph_indexing",featureFlagKey:"ENABLE_GRAPH_INDEXING",label:"\u30B0\u30E9\u30D5\u6295\u5F71",readByPipeline:!0}],Qa=new Set(Xn.map(e=>e.key));function Jl(e){return Qa.has(e)}function $l(e){let t=Xn.find(n=>n.key===e);if(t===void 0)throw new Error(`ENRICHMENT_STAGES does not carry ${e}; the canonical list and the key type have drifted apart.`);return t}var ql={pageSize:{min:1,max:200,default:50},topologyLabels:{min:1,max:24,default:24}};import{z as L}from"zod";var ei=["zip","pdf","ooxml","legacy_office"],Ql=L.enum(ei),Wn=["zipcrypto","aes","pdf_user_password","pdf_owner_password","office_encryption"],ec=L.enum(Wn),ti=[...Wn,"strong_encryption"],tc=L.enum(ti),nc=Object.freeze({zipcrypto:"ZIP \u306E\u6697\u53F7 (ZipCrypto)",aes:"ZIP \u306E\u6697\u53F7 (AES)",pdf_user_password:"PDF \u306E\u958B\u304F\u305F\u3081\u306E\u30D1\u30B9\u30EF\u30FC\u30C9",pdf_owner_password:"PDF \u306E\u5236\u9650\u306E\u30D1\u30B9\u30EF\u30FC\u30C9",office_encryption:"Office \u306E\u6697\u53F7",strong_encryption:"ZIP \u306E\u5F37\u3044\u6697\u53F7 (\u5916\u305B\u306A\u3044)"}),ni=["source_overwritten","copy_original","copy_promoted","child_decrypted"],rc=L.enum(ni),oc=Object.freeze({source_overwritten:"\u6E90\u3092\u89E3\u3044\u305F\u30D5\u30A1\u30A4\u30EB\u3067\u4E0A\u66F8\u304D\u3057\u305F",copy_original:"\u89E3\u3044\u305F\u5199\u3057\u3092\u539F\u672C\u306B\u3057\u3066\u3044\u308B",copy_promoted:"\u89E3\u3044\u305F\u5199\u3057\u3067\u6E90\u3092\u4E0A\u66F8\u304D\u3057\u305F (\u6607\u683C)",child_decrypted:"\u5B50\u306E\u7269\u3092\u89E3\u3044\u305F\u4E2D\u8EAB\u306B\u3057\u305F"}),ri=["permission_denied","immutable_source","foreign_application","local_source"],ac=L.enum(ri),ic=Object.freeze({permission_denied:"\u6E90\u3078\u66F8\u304F\u6A29\u9650\u304C\u7121\u3044",immutable_source:"\u30E1\u30FC\u30EB\u306F\u5909\u3048\u3089\u308C\u306A\u3044",foreign_application:"\u5225\u306E\u30A2\u30D7\u30EA (\u65E5\u5831) \u306E\u7269",local_source:"\u30DB\u30B9\u30C8\u306E\u30ED\u30FC\u30AB\u30EB\u306E\u30D5\u30A1\u30A4\u30EB"}),sc=e=>e==="permission_denied",lc=Object.freeze({passwordRequired:4225,protectionUnsupported:4226,sourceChanged:4094}),oi=["gmail","gdrive","gcs","file","daily-report"],cc=Object.freeze({gmail:"Gmail",gdrive:"Google \u30C9\u30E9\u30A4\u30D6",gcs:"Cloud Storage",file:"\u30ED\u30FC\u30AB\u30EB\u306E\u30D5\u30A1\u30A4\u30EB","daily-report":"\u65E5\u5831"}),ai=["glob","regex"],dc=Object.freeze({glob:"\u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9 (* \u3068 ?)",regex:"\u6B63\u898F\u8868\u73FE"}),be=Object.freeze({label:200,sender:320,subject:400,file_name:400,uri_prefix:2048}),uc=995,ii=2147483647,pc=e=>new TextEncoder().encode(e).length,si=e=>e.length,Zn=e=>L.string().min(1).refine(t=>si(t)<=e,{message:`Wider than the ${e} UTF-16 code units its column holds`}),je=e=>Zn(e).nullable(),li=L.object({sender:je(be.sender),subject:je(be.subject),file_name:je(be.file_name),uri_prefix:je(be.uri_prefix),source_kind:L.enum(oi).nullable(),syntax:L.enum(ai)}),mc=e=>e.sender===null&&e.subject===null&&e.file_name===null&&e.uri_prefix===null&&e.source_kind===null,Qn=L.object({password_id:L.number().int().positive(),label:Zn(be.label),conditions:li,priority:L.number().int().nonnegative().max(ii),is_active:L.boolean(),use_count:L.number().int().nonnegative(),last_used_at:N.nullable(),created_by:L.string().min(1),created_at:N,updated_by:L.string().min(1),updated_at:N}),fc=L.object({passwords:L.array(Qn)}),hc=L.object({passwords:L.array(Qn),timed_out:L.array(L.number().int().positive())});var pe=-1,X=0;function ci(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function gc(){let e=typeof globalThis<"u"&&globalThis.crypto?globalThis.crypto:typeof crypto<"u"?crypto:void 0;if(!e||typeof e.getRandomValues!="function")throw new Error("Cryptographically secure random number generator (crypto.getRandomValues) is required but not available.");let t=new Uint8Array(16);e.getRandomValues(t);let n=Date.now();if(n===pe){if(X++,X>4095){for(;Date.now()<=pe;);n=Date.now(),pe=n,X=(t[6]<<4|t[7]&15)&1023}}else n>pe?(pe=n,X=(t[6]<<4|t[7]&15)&1023):(n=pe,X++,X>4095&&(X=0));t[0]=Math.floor(n/1099511627776)&255,t[1]=Math.floor(n/4294967296)&255,t[2]=n>>>24&255,t[3]=n>>>16&255,t[4]=n>>>8&255,t[5]=n&255,t[6]=112|X>>>8&15,t[7]=X&255,t[8]=128|t[8]&63;let r=Array.from(t,i=>i.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function Sc(e){if(!ci(e))throw new Error(`Invalid RFC 9562 UUIDv7 string: "${e}"`);let t=e.slice(0,8)+e.slice(9,13),n=parseInt(t,16);if(Number.isNaN(n))throw new Error(`Invalid hex timestamp in UUIDv7: "${t}"`);return new Date(n)}export{ur as AmountEntrySchema,mn as AssetFacetItemSchema,Ae as BaseEnrichmentClient,Qe as BodySourceSchema,Bi as BoundingBoxSchema,ar as CHILD_TREE_REBUILD_CHUNK,Wr as CHUNK_BODY_FIDELITIES,Jr as CHUNK_CHANGE_KINDS,Gr as CHUNK_MANIFEST_VERSION,qr as CHUNK_PAIRINGS,Mi as CIRCUIT_BREAKER_SERVICES,ri as COPY_REASONS,ic as COPY_REASON_LABELS,fr as CanonicalDomainKeySchema,bn as ChangeFeedCursorSchema,cr as ChapterSegmentSchema,xi as ChildTreeRebuildRequestSchema,Ai as ChildTreeRebuildResultSchema,Zr as ChunkBodyFidelitySchema,$r as ChunkChangeKindSchema,Po as ChunkChangeSchema,uo as ChunkManifestChildSchema,po as ChunkManifestParentSchema,fo as ChunkManifestSchema,Xr as ChunkPairingSchema,Qt as ChunkRefSchema,wo as ChunkStatsSchema,Ji as ChunkingStrategySchema,Yi as CircuitBreakerStatusSchema,oo as ClassificationFacetSchema,le as ConfidentialityLevelSchema,ac as CopyReasonSchema,tt as DIFF_CONTEXT_LINES,en as DIFF_ENGINE_VERSION,to as DIFF_LINE_FACETS,sn as DIFF_LINE_PAGE_MAX,nn as DIFF_REGION_CELL_BOUND,no as DOCUMENT_CAPTURE_OUTCOMES,ln as DOCUMENT_CHANGE_FEED_PAGE_MAX,Ts as DOCUMENT_CHANGE_FEED_PAGE_SIZE,de as DOCUMENT_FACETS,Ye as DOCUMENT_KINDS,Qi as DOCUMENT_KIND_LABELS,Br as DOCUMENT_STATE_CAUSES,Ns as DOCUMENT_STATE_LOCK_TIMEOUT_MS,Vr as DOCUMENT_STATE_RUN_OUTCOMES,Ps as DiffLineFacetSchema,gn as DiffLinePageLimitSchema,Fs as DiffLinePageSchema,Do as DiffLineSchema,Ao as DiffSegmentSchema,Ks as DocumentCaptureAnswerSchema,ro as DocumentCaptureOutcomeSchema,Ko as DocumentChangeFeedEntrySchema,Ls as DocumentChangeFeedLimitSchema,js as DocumentChangeFeedPageSchema,Go as DocumentChangeFeedRowSchema,vs as DocumentComparisonSchema,cn as DocumentFacetSchema,ws as DocumentFacetValuesSchema,Hs as DocumentHistorySchema,Cr as DocumentKindSchema,Ho as DocumentRunEntrySchema,dn as DocumentStateCauseSchema,zo as DocumentStateEntrySchema,Yr as DocumentStateRunOutcomeSchema,Uo as DocumentStateSummarySchema,Vi as DocumentStructuredDataSchema,Xn as ENRICHMENT_STAGES,Lt as EnrichmentClient,se as EnrichmentClientError,wt as EnrichmentSyncStatusSchema,So as FACET_APPLICABLE_COUNTS,go as FACET_COUNT_FIELDS,be as FILE_PASSWORD_FIELD_WIDTHS,uc as FILE_PASSWORD_MAX_BYTES,ai as FILE_PASSWORD_PATTERN_SYNTAXES,dc as FILE_PASSWORD_PATTERN_SYNTAX_LABELS,ii as FILE_PASSWORD_PRIORITY_MAX,oi as FILE_PASSWORD_SOURCE_KINDS,cc as FILE_PASSWORD_SOURCE_KIND_LABELS,ki as FILTERABLE_CONFIDENTIALITY_LEVELS,bo as FacetChangeCountsSchema,Fo as FacetDiffSchema,it as FieldChangeSchema,li as FilePasswordConditionsSchema,fc as FilePasswordListSchema,hc as FilePasswordMatchSchema,Qn as FilePasswordViewSchema,Gi as FileUriSchema,ql as GRAPH_INDEX_LIMITS,yr as GraphSearchHitSchema,tn as HISTOGRAM_MAX_OCCURRENCES,xo as HunkIndexEntrySchema,Bs as INGESTION_EVENT_NAMES,on as INLINE_REFINE_CELL_BUDGET,rn as INLINE_REFINE_MAX_EDIT_DISTANCE,nt as INLINE_REFINE_MAX_GRAPHEMES,rt as INLINE_REFINE_MIN_SIMILARITY,ta as INTEGRITY_CLASS_POLICY,Pn as INTEGRITY_COMMAND_CODES,Dn as INTEGRITY_FINDINGS_PAGE_LIMIT_MAX,ha as IntegrityActiveRunSchema,rl as IntegrityAuditOverviewSchema,Na as IntegrityCancelFailureCodeSchema,sl as IntegrityCellResyncRequestSchema,ll as IntegrityCellResyncResultSchema,ut as IntegrityCommandFailureCodeSchema,cl as IntegrityCommandFailureSchema,ul as IntegrityCommandReplySchema,An as IntegrityCommandSchema,Qo as IntegrityDispositionSchema,Nn as IntegrityFindingItemClassSchema,al as IntegrityFindingPageSchema,Ra as IntegrityFindingSchema,il as IntegrityFindingsQuerySchema,Tn as IntegrityItemClassSchema,aa as IntegrityPhaseSchema,ol as IntegrityPlacementObservedSchema,pa as IntegrityQuantitySchema,ea as IntegrityRepairActionSchema,ia as IntegrityRepairOutcomeSchema,sa as IntegrityRepairSkipReasonSchema,dt as IntegrityRunHeaderSchema,na as IntegrityRunModeSchema,ra as IntegrityRunStatusSchema,Wo as IntegrityScopeRoleSchema,Ta as IntegrityStartFailureCodeSchema,ct as IntegrityStoreSchema,Zo as IntegrityUnitSchema,oa as IntegrityVerdictSchema,_o as JsonPatchOperationSchema,V as JsonValueSchema,Co as KeyedItemChangeSchema,Zt as KeyedItemSchema,$e as LEDGER_STEP_KEYS,eo as LINE_ENDINGS,io as LabelFacetItemSchema,ys as LedgerStepKeySchema,Os as LineEndingSchema,gr as MIME_KIND_RULES,Pt as MODE_TIERS,ao as MetadataFacetSchema,sr as ModelProviderSchema,Pr as NOTHING_TO_READ_TOKENS,wr as NothingToReadTokenSchema,jt as PIPELINE_FAILURE_STATUSES,Er as PIPELINE_FLOWS,ts as PIPELINE_PHASES,Kt as PIPELINE_STEPS,Te as PIPELINE_STEP_KEYS,ei as PROTECTION_FORMATS,ti as PROTECTION_SCHEMES,nc as PROTECTION_SCHEME_LABELS,Vt as PipelineFailureStatusSchema,qt as PipelineRunRecordSchema,Ze as PipelineRunStatusSchema,Xt as PipelineRunSummarySchema,Bt as PipelineStepKeySchema,Ss as PipelineStepMetricSchema,jr as PipelineStepRecordSchema,Nr as PipelineStepStatusSchema,Dr as PipelineTriggerSchema,Ql as ProtectionFormatSchema,tc as ProtectionSchemeSchema,he as QUARANTINED_CONFIDENTIALITY_LEVEL,Wn as REMOVABLE_PROTECTION_SCHEMES,Qr as RESTRICTED_MARK_SUBJECTS,xr as RUN_TERMINAL_STEP_ERROR_CODES,Je as RUN_TERMINAL_STEP_KEY,_r as RUN_TERMINAL_STEP_OUTCOMES,pn as ReadableConfidentialityLevelSchema,zs as RecentPipelineRunEntrySchema,ec as RemovableProtectionSchemeSchema,vo as RestrictedChangeMarkSchema,Us as RestrictedFailureMarkSchema,Ms as RestrictedIngestMarkSchema,Ds as RestrictedMarkSubjectSchema,Sn as RestrictedRunMarkSchema,Lo as RestrictedStateMarkSchema,Ir as RunTerminalStepDetailSchema,Tr as RunTerminalStepErrorCodeSchema,Rr as RunTerminalStepOutcomeSchema,zi as SEARCH_DEGRADATION_REASONS,vi as SEARCH_FUSIONS,Ot as SEARCH_MODES,wi as SEARCH_PARAM_LIMITS,Ui as SEARCH_QUALITY_TIERS,Xa as SOURCE_CAPABILITIES,qa as SOURCE_CREDENTIALS,Ar as STALE_RUN_ERROR_CODE,an as STRUCTURED_DATA_ARRAY_CELL_BOUND,we as SYSTEM_PARAMETER_RANGES,hr as SearchHitSchema,mr as SearchMetadataSchema,pr as SearchModeSchema,kt as SearchRequestSchema,Ft as SearchResponseSchema,Kl as SourceCatalogSchema,Za as SourceSpecSchema,Or as StageProvenanceSchema,Ce as TREE_PATH_PATTERN,lr as TenantIdSchema,ks as TextDiffIndexSchema,co as TextFacetSchema,Ro as TextStatsSchema,dr as TranscriptSegmentSchema,_e as TreePathSchema,ni as UNLOCK_DISPOSITIONS,oc as UNLOCK_DISPOSITION_LABELS,lc as UNLOCK_ERROR_CODES,rc as UnlockDispositionSchema,Xs as assertBoundedSystemParameter,qs as assertSystemParameterInRange,nr as assetTypeName,H as canonicalJson,es as classifyDocumentKind,Pa as codePointSlicer,ot as compareAssetKeys,q as compareCodeUnits,at as compareFacets,as as comparePhases,$a as compareStates,At as compareTreePaths,Jo as decodeChangeFeedCursor,Ha as diffChunkBodies,ja as diffLinePage,Yo as encodeChangeFeedCursor,$l as enrichmentStage,ns as flowFor,rs as flowStepGates,gs as formatSkipReason,gc as generateUuidV7,Bl as identifierMatches,dl as integrityCommandFailureCodeOf,Jl as isEnrichmentStageKey,sc as isPromotable,$ as isStrictlyEarlier,br as isUnknownTerm,ci as isValidUuidV7,or as millisecondsBetween,Li as modeFusesRankings,Fi as modeScoreIsSimilarity,os as orderedSteps,Yt as parseSkipReason,pc as passwordByteLength,Vl as pastedIdentifier,Pe as readableEntrySchema,Gl as sourceOfUri,ls as storedTermOf,Ne as storedTermSchema,cs as storedTermText,si as storedWidth,wa as stripWhitespace,Va as summarizeTransition,Me as summaryFacetDiff,Ue as textDiffIndex,ve as textFacetDiff,hi as treePathDepth,yi as treePathLabel,ae as treePathOf,gi as treePathParent,fi as treePathSegments,mc as triesEveryFile,Sc as uuidv7ToDate};
|