@inkeep/open-knowledge 0.11.0-beta.6 → 0.11.0-beta.8
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/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/{chunk-TLSUDHID-BeulIM_X.mjs → chunk-TLSUDHID-B2VV2ufQ.mjs} +2 -2
- package/dist/cli.mjs +12 -12
- package/dist/constants-HI8vQPCb.mjs +2 -0
- package/dist/{diff-HJF2MPDN-Ci7M3Pfx.mjs → diff-HJF2MPDN-DTuHZGVW.mjs} +1 -1
- package/dist/{dist-DFDll_q5.mjs → dist-9gkYdouR.mjs} +16 -17
- package/dist/{dist-CHRfgQ3D.mjs → dist-PzyBKLCf.mjs} +1 -1
- package/dist/{flag-coverage-QT4N2Z44-C38ybzz7.mjs → flag-coverage-QT4N2Z44-DmAL_7h5.mjs} +2 -2
- package/dist/{gh-detect-C3kYac-p.mjs → gh-detect-BiKqq3fe.mjs} +2 -2
- package/dist/git-handle-CTJE6H8P-aY9Efmma.mjs +1 -0
- package/dist/{git-handle-BSAUg1L_-B0dX3OSo.mjs → git-handle-Cd7K54Co-D4vPl00M.mjs} +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{init-DOOSSLEH.mjs → init-DHt4ChZM.mjs} +5 -5
- package/dist/init-XQMfwD-g.mjs +1 -0
- package/dist/{libesm-BXjuRhd9.mjs → libesm-D3nlnq5U.mjs} +2 -2
- package/dist/loader-BC6KKXuj.mjs +1 -0
- package/dist/{loader-BrdaUVEQ.mjs → loader-Ds6qHxYz.mjs} +3 -3
- package/dist/{preview-BHPfi0n1.mjs → preview-72lOqALs.mjs} +2 -2
- package/dist/preview-QKPxmqR_.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-A9JVnd1C.js → ActivityModeContent-BsurnqDs.js} +1 -1
- package/dist/public/assets/{DocumentContext-CmBtR_Ex.js → DocumentContext-ywaSbgZy.js} +1 -1
- package/dist/public/assets/{GraphPanel-BvMeDFSM.js → GraphPanel-DACQCEp9.js} +1 -1
- package/dist/public/assets/{SettingsDialogBody-Dhgc3_Ok.js → SettingsDialogBody-m4zzZa4Q.js} +1 -1
- package/dist/public/assets/{SourceEditor-D0EQlBRn.js → SourceEditor-CPUnHIDu.js} +1 -1
- package/dist/public/assets/{config-validation-events-BnNnGv50.js → config-validation-events-Dtuvx7eU.js} +2 -2
- package/dist/public/assets/{index-BXJoxA8K.js → index-D3rLIkvo.js} +5 -5
- package/dist/public/assets/{keyboard-shortcuts-DGQUJa57.js → keyboard-shortcuts-BtfhTJ-K.js} +1 -1
- package/dist/public/assets/{prop-types-z8aPJgr3.js → prop-types-BLvAnH2n.js} +1 -1
- package/dist/public/assets/{target-navigation-intent-BAXnlSRH.js → target-navigation-intent-BUfApF6Q.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-DihrFfB5.js → typing-burst-detector-BjfA2X2R.js} +1 -1
- package/dist/public/index.html +7 -7
- package/dist/{repair-launch-json-C6PTJ9xk.mjs → repair-launch-json-CyMyIXft.mjs} +2 -2
- package/dist/{repair-mcp-configs-1DLQ_aI_.mjs → repair-mcp-configs-87f1qZAU.mjs} +2 -2
- package/dist/{repair-skills-CjT8z59t.mjs → repair-skills--P4hyOt3.mjs} +2 -2
- package/dist/repair-skills-BQA-lmTE.mjs +1 -0
- package/dist/{server-lock-BpjJj3OD-vTp6kF0e.mjs → server-lock-BpjJj3OD-CGDmzK2V.mjs} +2 -2
- package/dist/server-lock-CyhBidkz-CrazWnBM.mjs +1 -0
- package/dist/{src-DPAvJMN5.mjs → src-BiwF6r4U.mjs} +2 -2
- package/dist/start-CXQ-QCFm.mjs +1 -0
- package/dist/{start-CQvloGGb.mjs → start-V6qeRUN7.mjs} +2 -2
- package/dist/{write-project-skill-B4WKDHbQ.mjs → write-project-skill-DozAMZpM.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-DSCKzAUk.mjs +0 -2
- package/dist/git-handle-CvT4CaVU-BqccGnFS.mjs +0 -1
- package/dist/init-s_zGdaxm.mjs +0 -1
- package/dist/loader-DePwbagD.mjs +0 -1
- package/dist/preview-CQODygq-.mjs +0 -1
- package/dist/repair-skills-DIfWiu1E.mjs +0 -1
- package/dist/server-lock-CyhBidkz-C2yQNfyA.mjs +0 -1
- package/dist/start-DMPvMQIA.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as __toCommonJS,i as __require$2,n as __esmMin,o as __toESM$2,r as __exportAll,t as __commonJSMin$2}from"./chunk-FK9Q3tQk.mjs";import{$ as CONFIG_DOC_NAME_USER,$i as preprocess,$n as TagsListSuccessSchema,$r as parseFrontmatterYaml,$t as MarkdownManager,A as ApiConfigSuccessSchema,Ai as detectRemovedKeys,An as SeedListPacksSuccessSchema,Ar as defaultScheduler,At as FrontmatterPatchSuccessSchema,B as CC1DiskAckPayloadSchema,Bi as _enum,Bn as SkillInstallStateSuccessSchema,Br as getAgentCanonicalDescriptors,Bt as LINKABLE_ASSET_EXTENSIONS,C as AgentPatchSuccessSchema,Ci as DEFAULT_SPANS_MAX_BYTES,Cn as SYSTEM_DOC_NAME,Ct as EmbedDetectSuccessSchema,D as AgentWriteMdSuccessSchema,Dn as SearchSuccessSchema,Dr as createTagInTextRegex,Dt as FolderConfigPutSuccessSchema,E as AgentWriteMdRequestSchema,Ei as OK_PROJECT_MARKER,En as SearchRequestSchema,Er as createCodeFenceTracker,Et as FolderConfigPutRequestSchema,F as BridgeMergeContentLossError,Fi as validatePatchScopes,Fn as ShareConstructUrlResponseSchema,Fr as encodeShareUrl,Ft as INLINE_RENDERABLE_EXTENSIONS,G as CC1_CHANNEL_DISK_ACK,Gi as custom,Gn as SyncConflictContentSuccessSchema,Gr as isBranchNotFoundGitError,Gt as LocalOpAuthStatusSuccessSchema,H as CC1_CHANNEL_BRANCH_SWITCHED,Hn as SpawnCursorSuccessSchema,Hr as getParseHealth,Ht as LocalOpAuthEmptySuccessSchema,I as CC1BranchSwitchedPayloadSchema,Ii as withConfigSpan,In as SharePublishNameCheckResponseSchema,Ir as expandTagToHierarchy,It as InstallSkillRequestSchema,J as CLIENT_VERSION_HEADER,Ji as literal,Jn as SyncResolveConflictSuccessSchema,Jr as isOrphanMode,Jt as LocalOpEmbeddingsSetKeyRequestSchema,K as CC1_CHANNEL_SERVER_INFO,Ki as discriminatedUnion,Kn as SyncConflictsSuccessSchema,Kr as isFrontmatterValueEmpty,Kt as LocalOpCloneRequestSchema,L as CC1ConfigIgnoreNestedErrorPayloadSchema,Li as withConfigSpanSync,Ln as SharePublishOwnersResponseSchema,Lr as extractFrontmatterTags,Lt as InstallSkillSuccessSchema,M as BacklinksSuccessSchema,Mi as isKnownConfigError,Mn as SemanticIndexStatusSchema,Mr as detectFmRegion,Mt as HistorySuccessSchema,N as BranchInfoResponseSchema,Ni as locateIssue,Nn as ServerInfoSuccessSchema,Nr as displayNameFromClientName,Nt as HistoryVersionSuccessSchema,O as AgentWriteRequestSchema,Oi as addConfigSpanEvent,On as SeedApplyRequestSchema,Or as createWorkspaceSearchCorpus,Ot as ForwardLinksSuccessSchema,P as BridgeInvariantViolationError,Pi as toConfigIssue,Pn as ShareConstructUrlRequestSchema,Pr as emptySkillState,Pt as HubsSuccessSchema,Q as CONFIG_DOC_NAME_PROJECT_LOCAL,Qi as optional,Qn as TagsForNameSuccessSchema,Qr as normalizeBridge,Qt as LocalOpOpenSuccessSchema,R as CC1ConfigValidationRejectedPayloadSchema,Rn as SharePublishRequestSchema,Rr as fnv1aDigest,Rt as InstalledAgentsSuccessSchema,S as AgentPatchRequestSchema,Sa as require_dist$1,Si as DEFAULT_LOGS_MAX_BYTES,Sr as classifyWikiLinkTarget,St as EXECUTABLE_BLOCKLIST_EXTENSIONS,T as AgentUndoSuccessSchema,Ti as LOCAL_DIR,Tn as SaveVersionSuccessSchema,Tr as createBasenameIndex,Tt as FolderConfigGetSuccessSchema,U as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ui as array,Un as StreamingProblemEventSchema,Ur as getWikiLinkText,Ut as LocalOpAuthHostRequestSchema,V as CC1ServerInfoPayloadSchema,Vi as _null,Vn as SkillStateSchema,Vr as getHeadingSlug,Vt as LinkGraphSuccessSchema,W as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Wi as boolean,Wn as SuggestLinksSuccessSchema,Wr as iconFromClientName,Wt as LocalOpAuthSetIdentityRequestSchema,X as CONFIG_DOC_NAME_OKIGNORE,Xi as number,Xn as SyncTriggerRequestSchema,Xr as mediaKindForSidebarAssetExtension,Xt as LocalOpOkInitResponseSchema,Y as CONFIG_DOC_NAMES,Yi as looseObject,Yn as SyncStatusSchema,Yr as isValidBranchName,Yt as LocalOpOkInitRequestSchema,Z as CONFIG_DOC_NAME_PROJECT,Zi as object$1,Zn as SyncTriggerSuccessSchema,Zr as mergeThreeWay,Zt as LocalOpOpenRequestSchema,_ as AGENT_ICON_COLORS,_a as clone,_i as Fragment,_n as SANDBOXED_HTML_CSP,_r as applyFastDiff,_t as DocumentListSuccessSchema,a as acquireProcessLock,aa as datetime,ai as resolveAssetProjectPath,an as PREVIEW_EMBED_STARTERS,ar as TemplatePutSuccessSchema,at as CreateFolderSuccessSchema,b as AgentActivitySuccessSchema,ba as $constructor,bi as DEFAULT_EMBEDDINGS_BASE_URL,bn as SKILL_STATE_TARGETS,br as assertNeverProblemType,bt as DuplicatePathSuccessSchema,c as isValidLockPid,ca as describe$1,ci as sharedExtensions,cn as PageHeadingsSuccessSchema,cr as TestRescanFilesSuccessSchema,ct as DEFAULT_DEDUP_MODE,da as $ZodType,di as toBridgeInvariantLog,dn as ProblemDetailsSchema,dr as TrashCleanupSuccessSchema,ea as record,ei as prependFrontmatter,en as MetricsAgentPresenceSuccessSchema,er as TemplateDeleteSuccessSchema,et as CheckoutRequestSchema,f as readServerLock,fa as parse$1,fi as toWikiLinkSlug,fn as RenamePathRequestSchema,fr as UA_PATTERNS,ft as DOCUMENT_OPEN_BYTE_LIMIT,ga as prettifyError,gi as PluginKey,gn as RollbackSuccessSchema,gr as WriteWarningSchema,gt as DiffSuccessSchema,h as updateProcessLockPort,ha as safeParseAsync$1,hi as getSchema,hn as RollbackRequestSchema,hr as WorkspaceSuccessSchema,ht as DeletePathSuccessSchema,ii as renderInventoryFooter,in as OrphansSuccessSchema,ir as TemplatePutRequestSchema,it as CreateFolderRequestSchema,j as BacklinkCountsSuccessSchema,ji as humanFormat,jn as SeedPlanSuccessSchema,jr as detectAppliedToleranceClasses,jt as FrontmatterValueSchema,k as AgentWriteSuccessSchema,ki as applyPatchToDocument,kn as SeedApplySuccessSchema,kr as createWorkspaceSearchDocument,kt as FrontmatterPatchRequestSchema,la as meta$1,li as stripFrontmatter,ln as PagesSuccessSchema,lr as TestResetSuccessSchema,m as releaseServerLock,ma as safeParse$1,mi as validateDocName,mn as RescueListSuccessSchema,mr as UploadRequestSchema,mt as DeletePathRequestSchema,n as RUNTIME_VERSION,na as union,ni as projectFull,nn as MetricsReconciliationSuccessSchema,nr as TemplateMoveRequestSchema,nt as ClientLogsRequestSchema,o as acquireServerLock,oa as toJSONSchema,oi as resolveInternalHref,on as PREVIEW_THEME_TOKENS,or as TemplatesListSuccessSchema,ot as CreatePageRequestSchema,p as releaseProcessLock,pa as parseAsync,pi as unwrapFrontmatterFences,pn as RenamePathSuccessSchema,pr as UploadAssetSuccessSchema,pt as DeadLinksSuccessSchema,q as CC1_CONTRACT_VERSION,qi as intersection,qn as SyncResolveConflictRequestSchema,qr as isHiddenDocName,qt as LocalOpEmbeddingsMutationSuccessSchema,ra as unknown,ri as readFmMap,rn as ORPHAN_MODES,rr as TemplateMoveSuccessSchema,rt as ClientLogsSuccessSchema,s as isProcessAlive,si as searchWorkspaceCorpus,sn as PROTOCOL_VERSION,sr as TestRescanBacklinksSuccessSchema,st as CreatePageSuccessSchema,t as ProcessLockCollisionError,ta as string,ti as previewEmbedFence,tn as MetricsParseHealthSuccessSchema,tr as TemplateGetSuccessSchema,tt as CheckoutResponseSchema,u as readProcessLock,ua as $ZodObject,ui as tagsMatchingPrefix,un as PrincipalSuccessSchema,ur as TrashCleanupRequestSchema,va as defineLazy,vi as CONFIG_SCHEMA_MAJOR_PATH,vn as SANDBOXED_HTML_EXTENSIONS,vr as applyIncrementalDiff,vt as DocumentReadSuccessSchema,w as AgentUndoRequestSchema,wi as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,wn as SaveVersionRequestSchema,wr as colorFromSeed,wt as EmptyRequestSchema,x as AgentBurstDiffSuccessSchema,xi as DEFAULT_EMBEDDINGS_MODEL,xn as SKILL_STATE_VERSION_RE,xr as classifyMarkdownHref,y as ASSET_EXTENSIONS,ya as normalizeParams,yi as ConfigSchema$1,yn as SKILL_STATE_REL,yr as applyPatchToFm,yt as DuplicatePathRequestSchema,z as CC1DerivedViewPayloadSchema,zi as ZodOptional$1,zn as SharePublishResponseSchema,zr as formatFileSize,zt as LINEAGE_EPOCH_KEY}from"./server-lock-BpjJj3OD-vTp6kF0e.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-k1YlZnpm.mjs";import{a as require_src$15,i as simpleGit,n as withParentLock,r as esm_default,t as createGitInstance}from"./git-handle-BSAUg1L_-B0dX3OSo.mjs";import{r as diffLines,t as createPatch}from"./libesm-BXjuRhd9.mjs";import{n as mimes,t as build_default}from"./build-CJEQ0nGy.mjs";import{t as require_yazl}from"./yazl-CB0sfSbo.mjs";import{t as b1}from"./chunk-YNYSPYQ5-iQGTFdx0.mjs";import{a as c,c as h,d as m,f as p,h as x,i as b,l as i,m as v,n as C,o as d,p as u,r as a,s as f,t as $$1,u as l}from"./chunk-GFQRA5P5-ePq2jelx.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-DmvuPNqm.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-BWGDFyz_.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-D1Ufj9fh.mjs";import{r as o$1}from"./chunk-CWQS3NFK-BP3kiNgH.mjs";import"./chunk-DXB73IDG-C2RuFAAY.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-BfIuRNkK.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-C6ngIqYR.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-DWhg7YHU.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-C-Zyd2K_.mjs";import{n as n$1}from"./chunk-3THT3N7L-Ce6LrnIA.mjs";import{t as n$2}from"./chunk-44UOCSGV-uErOrz7G.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import*as U from"node:path";import{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import crypto$1 from"crypto";import crypto$1$1,{createHash,randomUUID,webcrypto}from"node:crypto";import*as zlib$1 from"zlib";import{Readable as Readable$1}from"stream";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{promisify}from"node:util";import{Http2ServerRequest,constants as constants$2}from"http2";import{AsyncLocalStorage}from"node:async_hooks";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
|
|
1
|
+
import{a as __toCommonJS,i as __require$2,n as __esmMin,o as __toESM$2,r as __exportAll,t as __commonJSMin$2}from"./chunk-FK9Q3tQk.mjs";import{$ as CONFIG_DOC_NAME_USER,$i as union,$n as TemplateMoveRequestSchema,$r as projectFull,$t as MetricsReconciliationSuccessSchema,A as ApiConfigSuccessSchema,Ai as locateIssue,An as ServerInfoSuccessSchema,Ar as displayNameFromClientName,At as FrontmatterValueSchema,B as CC1DiskAckPayloadSchema,Bi as array,Bn as StreamingProblemEventSchema,Br as getWikiLinkText,Bt as LinkGraphSuccessSchema,C as AgentPatchSuccessSchema,Ci as OK_PROJECT_MARKER,Cn as SearchRequestSchema,Cr as createCodeFenceTracker,Ct as EmptyRequestSchema,D as AgentWriteMdSuccessSchema,Di as detectRemovedKeys,Dn as SeedListPacksSuccessSchema,Dr as defaultScheduler,Dt as ForwardLinksSuccessSchema,E as AgentWriteMdRequestSchema,Ei as applyPatchToDocument,En as SeedApplySuccessSchema,Er as createWorkspaceSearchDocument,Et as FolderConfigPutSuccessSchema,F as BridgeMergeContentLossError,Fn as SharePublishRequestSchema,Fr as fnv1aDigest,Ft as InstallSkillRequestSchema,G as CC1_CHANNEL_DISK_ACK,Gi as literal,Gn as SyncResolveConflictSuccessSchema,Gr as isOrphanMode,Gt as LocalOpCloneRequestSchema,H as CC1_CHANNEL_BRANCH_SWITCHED,Hi as custom,Hn as SyncConflictContentSuccessSchema,Hr as isBranchNotFoundGitError,Ht as LocalOpAuthHostRequestSchema,I as CC1BranchSwitchedPayloadSchema,Ii as ZodOptional$1,In as SharePublishResponseSchema,Ir as formatFileSize,It as InstallSkillSuccessSchema,J as CLIENT_VERSION_HEADER,Ji as object$1,Jn as SyncTriggerSuccessSchema,Jr as mergeThreeWay,Jt as LocalOpOkInitRequestSchema,K as CC1_CHANNEL_SERVER_INFO,Ki as looseObject,Kn as SyncStatusSchema,Kr as isValidBranchName,Kt as LocalOpEmbeddingsMutationSuccessSchema,L as CC1ConfigIgnoreNestedErrorPayloadSchema,Li as _enum,Ln as SkillInstallStateSuccessSchema,Lr as getAgentCanonicalDescriptors,Lt as InstalledAgentsSuccessSchema,M as BacklinksSuccessSchema,Mi as validatePatchScopes,Mn as ShareConstructUrlResponseSchema,Mr as encodeShareUrl,Mt as HistoryVersionSuccessSchema,N as BranchInfoResponseSchema,Ni as withConfigSpan,Nn as SharePublishNameCheckResponseSchema,Nr as expandTagToHierarchy,Nt as HubsSuccessSchema,O as AgentWriteRequestSchema,Oi as humanFormat,On as SeedPlanSuccessSchema,Or as detectAppliedToleranceClasses,Ot as FrontmatterPatchRequestSchema,P as BridgeInvariantViolationError,Pi as withConfigSpanSync,Pn as SharePublishOwnersResponseSchema,Pr as extractFrontmatterTags,Pt as INLINE_RENDERABLE_EXTENSIONS,Q as CONFIG_DOC_NAME_PROJECT_LOCAL,Qi as string,Qn as TemplateGetSuccessSchema,Qr as previewEmbedFence,Qt as MetricsParseHealthSuccessSchema,R as CC1ConfigValidationRejectedPayloadSchema,Ri as _null,Rn as SkillStateSchema,Rr as getHeadingSlug,Rt as LINEAGE_EPOCH_KEY,S as AgentPatchRequestSchema,Si as LOCAL_DIR,Sn as SaveVersionSuccessSchema,Sr as createBasenameIndex,St as EmbedDetectSuccessSchema,T as AgentUndoSuccessSchema,Ti as addConfigSpanEvent,Tn as SeedApplyRequestSchema,Tr as createWorkspaceSearchCorpus,Tt as FolderConfigPutRequestSchema,U as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ui as discriminatedUnion,Un as SyncConflictsSuccessSchema,Ur as isFrontmatterValueEmpty,Ut as LocalOpAuthSetIdentityRequestSchema,V as CC1ServerInfoPayloadSchema,Vi as boolean,Vn as SuggestLinksSuccessSchema,Vr as iconFromClientName,Vt as LocalOpAuthEmptySuccessSchema,W as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Wi as intersection,Wn as SyncResolveConflictRequestSchema,Wr as isHiddenDocName,Wt as LocalOpAuthStatusSuccessSchema,X as CONFIG_DOC_NAME_OKIGNORE,Xi as preprocess,Xn as TagsListSuccessSchema,Xr as parseFrontmatterYaml,Xt as MarkdownManager,Y as CONFIG_DOC_NAMES,Yi as optional,Yn as TagsForNameSuccessSchema,Yr as normalizeBridge,Yt as LocalOpOkInitResponseSchema,Z as CONFIG_DOC_NAME_PROJECT,Zi as record,Zn as TemplateDeleteSuccessSchema,Zr as prependFrontmatter,Zt as MetricsAgentPresenceSuccessSchema,_ as AGENT_ICON_COLORS,_a as $constructor,_i as DEFAULT_EMBEDDINGS_BASE_URL,_n as SKILL_STATE_TARGETS,_r as assertNeverProblemType,_t as DocumentReadSuccessSchema,a as acquireProcessLock,aa as describe$1,ai as sharedExtensions,an as PageHeadingsSuccessSchema,ar as TestRescanFilesSuccessSchema,at as CreateFolderSuccessSchema,b as AgentActivitySuccessSchema,bi as DEFAULT_SPANS_MAX_BYTES,bn as SYSTEM_DOC_NAME,c as isValidLockPid,ca as $ZodType,ci as toBridgeInvariantLog,cn as ProblemDetailsSchema,cr as TrashCleanupSuccessSchema,ct as DEFAULT_DEDUP_MODE,da as safeParse$1,di as validateDocName,dn as RescueListSuccessSchema,dr as UploadRequestSchema,ea as unknown,ei as readFmMap,en as ORPHAN_MODES,er as TemplateMoveSuccessSchema,et as CheckoutRequestSchema,f as readServerLock,fa as safeParseAsync$1,fi as getSchema,fn as RollbackRequestSchema,fr as WorkspaceSuccessSchema,ft as DOCUMENT_OPEN_BYTE_LIMIT,ga as normalizeParams,gi as ConfigSchema$1,gn as SKILL_STATE_REL,gr as applyPatchToFm,gt as DocumentListSuccessSchema,h as updateProcessLockPort,ha as defineLazy,hi as CONFIG_SCHEMA_MAJOR_PATH,hn as SANDBOXED_HTML_EXTENSIONS,hr as applyIncrementalDiff,ht as DeletePathSuccessSchema,ii as searchWorkspaceCorpus,in as PROTOCOL_VERSION,ir as TestRescanBacklinksSuccessSchema,it as CreateFolderRequestSchema,j as BacklinkCountsSuccessSchema,ji as toConfigIssue,jn as ShareConstructUrlRequestSchema,jr as emptySkillState,jt as HistorySuccessSchema,k as AgentWriteSuccessSchema,ki as isKnownConfigError,kn as SemanticIndexStatusSchema,kr as detectFmRegion,kt as FrontmatterPatchSuccessSchema,la as parse$1,li as toWikiLinkSlug,ln as RenamePathRequestSchema,lr as UA_PATTERNS,m as releaseServerLock,ma as clone,mi as Fragment,mn as SANDBOXED_HTML_CSP,mr as applyFastDiff,mt as DeletePathRequestSchema,n as RUNTIME_VERSION,na as datetime,ni as resolveAssetProjectPath,nn as PREVIEW_EMBED_STARTERS,nr as TemplatePutSuccessSchema,nt as ClientLogsRequestSchema,o as acquireServerLock,oa as meta$1,oi as stripFrontmatter,on as PagesSuccessSchema,or as TestResetSuccessSchema,ot as CreatePageRequestSchema,p as releaseProcessLock,pa as prettifyError,pi as PluginKey,pn as RollbackSuccessSchema,pr as WriteWarningSchema,pt as DeadLinksSuccessSchema,q as CC1_CONTRACT_VERSION,qi as number,qn as SyncTriggerRequestSchema,qr as mediaKindForSidebarAssetExtension,qt as LocalOpEmbeddingsSetKeyRequestSchema,ra as toJSONSchema,ri as resolveInternalHref,rn as PREVIEW_THEME_TOKENS,rr as TemplatesListSuccessSchema,rt as ClientLogsSuccessSchema,s as isProcessAlive,sa as $ZodObject,si as tagsMatchingPrefix,sn as PrincipalSuccessSchema,sr as TrashCleanupRequestSchema,st as CreatePageSuccessSchema,t as ProcessLockCollisionError,ti as renderInventoryFooter,tn as OrphansSuccessSchema,tr as TemplatePutRequestSchema,tt as CheckoutResponseSchema,u as readProcessLock,ua as parseAsync,ui as unwrapFrontmatterFences,un as RenamePathSuccessSchema,ur as UploadAssetSuccessSchema,vi as DEFAULT_EMBEDDINGS_MODEL,vn as SKILL_STATE_VERSION_RE,vr as classifyMarkdownHref,vt as DuplicatePathRequestSchema,w as AgentUndoRequestSchema,wn as SearchSuccessSchema,wr as createTagInTextRegex,wt as FolderConfigGetSuccessSchema,x as AgentBurstDiffSuccessSchema,xi as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,xn as SaveVersionRequestSchema,xr as colorFromSeed,xt as EXECUTABLE_BLOCKLIST_EXTENSIONS,y as ASSET_EXTENSIONS,ya as require_dist$1,yi as DEFAULT_LOGS_MAX_BYTES,yr as classifyWikiLinkTarget,yt as DuplicatePathSuccessSchema,z as CC1DerivedViewPayloadSchema,zn as SpawnCursorSuccessSchema,zr as getParseHealth,zt as LINKABLE_ASSET_EXTENSIONS}from"./server-lock-BpjJj3OD-CGDmzK2V.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-k1YlZnpm.mjs";import{a as require_src$15,i as simpleGit,n as withParentLock,r as esm_default,t as createGitInstance}from"./git-handle-Cd7K54Co-D4vPl00M.mjs";import{t as createPatch}from"./libesm-D3nlnq5U.mjs";import{n as mimes,t as build_default}from"./build-CJEQ0nGy.mjs";import{t as require_yazl}from"./yazl-CB0sfSbo.mjs";import{t as b1}from"./chunk-YNYSPYQ5-iQGTFdx0.mjs";import{a as c,c as h,d as m,f as p,h as x,i as b,l as i,m as v,n as C,o as d,p as u,r as a,s as f,t as $$1,u as l}from"./chunk-GFQRA5P5-ePq2jelx.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-DmvuPNqm.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-BWGDFyz_.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-D1Ufj9fh.mjs";import{r as o$1}from"./chunk-CWQS3NFK-BP3kiNgH.mjs";import"./chunk-DXB73IDG-C2RuFAAY.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-BfIuRNkK.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-C6ngIqYR.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-DWhg7YHU.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-C-Zyd2K_.mjs";import{n as n$1}from"./chunk-3THT3N7L-Ce6LrnIA.mjs";import{t as n$2}from"./chunk-44UOCSGV-uErOrz7G.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import*as U from"node:path";import{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,lstat,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import crypto$1 from"crypto";import crypto$1$1,{createHash,randomUUID,webcrypto}from"node:crypto";import*as zlib$1 from"zlib";import{Readable as Readable$1}from"stream";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{promisify}from"node:util";import{Http2ServerRequest,constants as constants$2}from"http2";import{AsyncLocalStorage}from"node:async_hooks";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
|
|
2
2
|
`)){let e=s.trim();if(e.startsWith(OK_CONTRIBUTORS_PREFIX))try{let s=JSON.parse(e.slice(17));if(typeof s==`object`&&s&&`id`in s&&typeof s.id==`string`&&`name`in s&&typeof s.name==`string`&&`docs`in s&&Array.isArray(s.docs)&&s.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in s)||typeof s.colorSeed==`string`)){let e=s;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(s)}}catch{}}return t}const OK_CHECKPOINT_PREFIX=`ok-checkpoint-v1: `;function parseCheckpoint(e){if(!e)return null;for(let t of e.split(`
|
|
3
3
|
`)){let e=t.trim();if(!e.startsWith(OK_CHECKPOINT_PREFIX))continue;let s;try{s=JSON.parse(e.slice(18))}catch{return null}if(typeof s!=`object`||!s)return null;let g=s,S=g.kind,w=g.metadata;if(typeof w!=`object`||!w)return null;let E=typeof g.docName==`string`?g.docName:null,D=typeof g.size==`number`&&Number.isFinite(g.size)?g.size:null;if(S===`bridge-merge-loss`){let e=w;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:E,size:D,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(S===`external-change-rescue`){let e=w;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:E,size:D,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}return null}return null}function formatCheckpointBodyLine(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${OK_CHECKPOINT_PREFIX}${JSON.stringify(t)}`}const OK_ACTOR_PREFIX=`ok-actor: `;function formatOkActor(e){let{summaries:t,previous_paths:s,...g}=e,S={...g};return t&&t.length>0&&(S.summaries=t),s&&s.length>0&&(S.previous_paths=s),`${OK_ACTOR_PREFIX}${JSON.stringify(S)}`}function parseOkActorObject(e){if(e.v!==1||!(`display_name`in e)||typeof e.display_name!=`string`||!(`docs`in e)||!Array.isArray(e.docs))return null;let t=typeof e.principal==`string`?e.principal:null,s=typeof e.agent_session==`string`?e.agent_session:null,g;if(typeof e.writer_id==`string`&&e.writer_id.length>0)g=e.writer_id;else if(s)g=`agent-${s}`;else if(t)g=t;else switch(e.display_name){case`File System`:g=`file-system`;break;case`Git (upstream)`:g=`git-upstream`;break;default:g=`openknowledge-service`}let S=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0,w=parsePreviousPaths(e);return{v:1,writer_id:g,principal:t,agent_session:s,agent_type:typeof e.agent_type==`string`?e.agent_type:null,client_name:typeof e.client_name==`string`?e.client_name:null,client_version:typeof e.client_version==`string`?e.client_version:null,label:typeof e.label==`string`?e.label:null,display_name:e.display_name,color_seed:typeof e.color_seed==`string`?e.color_seed:`unknown`,docs:e.docs.filter(e=>typeof e==`string`),...S&&S.length>0?{summaries:S}:{},...w&&w.length>0?{previous_paths:w}:{}}}function parsePreviousPaths(e){if(!(`previous_paths`in e)||!Array.isArray(e.previous_paths))return;let t=[];for(let s of e.previous_paths){if(typeof s!=`object`||!s)continue;let e=s;typeof e.from!=`string`||typeof e.to!=`string`||t.push({from:e.from,to:e.to})}return t}function parseOkActors(e){if(!e)return[];let t=[];for(let s of e.split(`
|
|
4
4
|
`)){let e=s.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let g;try{g=JSON.parse(e.slice(10))}catch{continue}if(typeof g!=`object`||!g)continue;let S=parseOkActorObject(g);S&&t.push(S)}return t}function okActorToShadowContributor(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function readContributors(e){let t=parseOkActors(e);return t.length>0?t.map(okActorToShadowContributor):parseContributors(e)}function formatWipSubject(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function formatReconcileSubject(e){return`reconcile: ${e}`}function formatRollbackSubject(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function formatParkSubject(e,t){return`park: ${e} -> ${t}`}function formatRenameSubject(e,t){return`rename: ${e} -> ${t}`}function formatCheckpointSubject(e){return`checkpoint: ${e}`}function formatImportSubject(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const SUBJECT_LINE_BREAK_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function stripLineBreaks(e){return e.replace(SUBJECT_LINE_BREAK_RE,` `)}function composeCommitSubject(e,t){let s=stripLineBreaks(e);if(t.length===0)return s;if(t.length>=2)return`${s} (${t.length} edits)`;let[g]=t;if(g===void 0)return s;let S=stripLineBreaks(g),w=`${s} — ${S}`;if(w.length<=72)return w;let E=`${s} — `,D=72-E.length-1;return D<=0?w.slice(0,72):`${E}${S.slice(0,D)}…`}function parseWriterId(e){return WRITER_ID_RE.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}var require_suppress_tracing$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isTracingSuppressed=e.unsuppressTracing=e.suppressTracing=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key SUPPRESS_TRACING`);function s(e){return e.setValue(t,!0)}e.suppressTracing=s;function g(e){return e.deleteValue(t)}e.unsuppressTracing=g;function S(e){return e.getValue(t)===!0}e.isTracingSuppressed=S})),require_constants$7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BAGGAGE_MAX_TOTAL_LENGTH=e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=e.BAGGAGE_MAX_NAME_VALUE_PAIRS=e.BAGGAGE_HEADER=e.BAGGAGE_ITEMS_SEPARATOR=e.BAGGAGE_PROPERTIES_SEPARATOR=e.BAGGAGE_KEY_PAIR_SEPARATOR=void 0,e.BAGGAGE_KEY_PAIR_SEPARATOR=`=`,e.BAGGAGE_PROPERTIES_SEPARATOR=`;`,e.BAGGAGE_ITEMS_SEPARATOR=`,`,e.BAGGAGE_HEADER=`baggage`,e.BAGGAGE_MAX_NAME_VALUE_PAIRS=180,e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,e.BAGGAGE_MAX_TOTAL_LENGTH=8192})),require_utils$16=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseKeyPairsIntoRecord=e.parsePairKeyValue=e.getKeyPairs=e.serializeKeyPairs=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_constants$7();function g(e){return e.reduce((e,t)=>{let g=`${e}${e===``?``:s.BAGGAGE_ITEMS_SEPARATOR}${t}`;return g.length>s.BAGGAGE_MAX_TOTAL_LENGTH?e:g},``)}e.serializeKeyPairs=g;function S(e){return e.getAllEntries().map(([e,t])=>{let g=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return t.metadata!==void 0&&(g+=s.BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),g})}e.getKeyPairs=S;function w(e){if(!e)return;let g=e.indexOf(s.BAGGAGE_PROPERTIES_SEPARATOR),S=g===-1?e:e.substring(0,g),w=S.indexOf(s.BAGGAGE_KEY_PAIR_SEPARATOR);if(w<=0)return;let E=S.substring(0,w).trim(),D=S.substring(w+1).trim();if(!E||!D)return;let O,k;try{O=decodeURIComponent(E),k=decodeURIComponent(D)}catch{return}let j;if(g!==-1&&g<e.length-1){let s=e.substring(g+1);j=(0,t.baggageEntryMetadataFromString)(s)}return{key:O,value:k,metadata:j}}e.parsePairKeyValue=w;function E(e){let t={};return typeof e==`string`&&e.length>0&&e.split(s.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let s=w(e);s!==void 0&&s.value.length>0&&(t[s.key]=s.value)}),t}e.parseKeyPairsIntoRecord=E})),require_W3CBaggagePropagator$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CBaggagePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$3(),g=require_constants$7(),S=require_utils$16();e.W3CBaggagePropagator=class{inject(e,w,E){let D=t.propagation.getBaggage(e);if(!D||(0,s.isTracingSuppressed)(e))return;let O=(0,S.getKeyPairs)(D).filter(e=>e.length<=g.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,g.BAGGAGE_MAX_NAME_VALUE_PAIRS),k=(0,S.serializeKeyPairs)(O);k.length>0&&E.set(w,g.BAGGAGE_HEADER,k)}extract(e,s,w){let E=w.get(s,g.BAGGAGE_HEADER),D=Array.isArray(E)?E.join(g.BAGGAGE_ITEMS_SEPARATOR):E;if(!D)return e;let O={};return D.length===0||(D.split(g.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let t=(0,S.parsePairKeyValue)(e);if(t){let e={value:t.value};t.metadata&&(e.metadata=t.metadata),O[t.key]=e}}),Object.entries(O).length===0)?e:t.propagation.setBaggage(e,t.propagation.createBaggage(O))}fields(){return[g.BAGGAGE_HEADER]}}})),require_anchored_clock$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AnchoredClock=void 0,e.AnchoredClock=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}})),require_attributes$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isAttributeValue=e.isAttributeKey=e.sanitizeAttributes=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function s(e){let s={};if(typeof e!=`object`||!e)return s;for(let w in e){if(!Object.prototype.hasOwnProperty.call(e,w))continue;if(!g(w)){t.diag.warn(`Invalid attribute key: ${w}`);continue}let E=e[w];if(!S(E)){t.diag.warn(`Invalid attribute value set for key: ${w}`);continue}Array.isArray(E)?s[w]=E.slice():s[w]=E}return s}e.sanitizeAttributes=s;function g(e){return typeof e==`string`&&e!==``}e.isAttributeKey=g;function S(e){return e==null?!0:Array.isArray(e)?w(e):E(typeof e)}e.isAttributeValue=S;function w(e){let t;for(let s of e){if(s==null)continue;let e=typeof s;if(e!==t){if(!t){if(E(e)){t=e;continue}return!1}return!1}}return!0}function E(e){switch(e){case`number`:case`boolean`:case`string`:return!0}return!1}})),require_logging_error_handler$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.loggingErrorHandler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function s(){return e=>{t.diag.error(g(e))}}e.loggingErrorHandler=s;function g(e){return typeof e==`string`?e:JSON.stringify(S(e))}function S(e){let t={},s=e;for(;s!==null;)Object.getOwnPropertyNames(s).forEach(e=>{if(t[e])return;let g=s[e];g&&(t[e]=String(g))}),s=Object.getPrototypeOf(s);return t}})),require_global_error_handler$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.globalErrorHandler=e.setGlobalErrorHandler=void 0;let t=(0,require_logging_error_handler$3().loggingErrorHandler)();function s(e){t=e}e.setGlobalErrorHandler=s;function g(e){try{t(e)}catch{}}e.globalErrorHandler=g})),require_environment$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e.getNumberFromEnv=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=__require$2(`util`);function g(e){let g=process.env[e];if(g==null||g.trim()===``)return;let S=Number(g);if(isNaN(S)){t.diag.warn(`Unknown value ${(0,s.inspect)(g)} for ${e}, expected a number, using defaults`);return}return S}e.getNumberFromEnv=g;function S(e){let t=process.env[e];if(!(t==null||t.trim()===``))return t}e.getStringFromEnv=S;function w(e){let g=process.env[e]?.trim().toLowerCase();return g==null||g===``?!1:g===`true`?!0:(g===`false`||t.diag.warn(`Unknown value ${(0,s.inspect)(g)} for ${e}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}e.getBooleanFromEnv=w;function E(e){return S(e)?.split(`,`).map(e=>e.trim()).filter(e=>e!==``)}e.getStringListFromEnv=E})),require_globalThis$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._globalThis=void 0,e._globalThis=globalThis})),require_version$6=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.7.0`}));function createConstMap(e){let t={},s=e.length;for(let g=0;g<s;g++){let s=e[g];s&&(t[String(s).toUpperCase().replace(/[-.]/g,`_`)]=s)}return t}var init_utils=__esmMin((()=>{})),TMP_AWS_LAMBDA_INVOKED_ARN,TMP_DB_SYSTEM,TMP_DB_CONNECTION_STRING,TMP_DB_USER,TMP_DB_JDBC_DRIVER_CLASSNAME,TMP_DB_NAME,TMP_DB_STATEMENT,TMP_DB_OPERATION,TMP_DB_MSSQL_INSTANCE_NAME,TMP_DB_CASSANDRA_KEYSPACE,TMP_DB_CASSANDRA_PAGE_SIZE,TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,TMP_DB_CASSANDRA_TABLE,TMP_DB_CASSANDRA_IDEMPOTENCE,TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,TMP_DB_CASSANDRA_COORDINATOR_ID,TMP_DB_CASSANDRA_COORDINATOR_DC,TMP_DB_HBASE_NAMESPACE,TMP_DB_REDIS_DATABASE_INDEX,TMP_DB_MONGODB_COLLECTION,TMP_DB_SQL_TABLE,TMP_EXCEPTION_TYPE,TMP_EXCEPTION_MESSAGE,TMP_EXCEPTION_STACKTRACE,TMP_EXCEPTION_ESCAPED,TMP_FAAS_TRIGGER,TMP_FAAS_EXECUTION,TMP_FAAS_DOCUMENT_COLLECTION,TMP_FAAS_DOCUMENT_OPERATION,TMP_FAAS_DOCUMENT_TIME,TMP_FAAS_DOCUMENT_NAME,TMP_FAAS_TIME,TMP_FAAS_CRON,TMP_FAAS_COLDSTART,TMP_FAAS_INVOKED_NAME,TMP_FAAS_INVOKED_PROVIDER,TMP_FAAS_INVOKED_REGION,TMP_NET_TRANSPORT,TMP_NET_PEER_IP,TMP_NET_PEER_PORT,TMP_NET_PEER_NAME,TMP_NET_HOST_IP,TMP_NET_HOST_PORT,TMP_NET_HOST_NAME,TMP_NET_HOST_CONNECTION_TYPE,TMP_NET_HOST_CONNECTION_SUBTYPE,TMP_NET_HOST_CARRIER_NAME,TMP_NET_HOST_CARRIER_MCC,TMP_NET_HOST_CARRIER_MNC,TMP_NET_HOST_CARRIER_ICC,TMP_PEER_SERVICE,TMP_ENDUSER_ID,TMP_ENDUSER_ROLE,TMP_ENDUSER_SCOPE,TMP_THREAD_ID,TMP_THREAD_NAME,TMP_CODE_FUNCTION,TMP_CODE_NAMESPACE,TMP_CODE_FILEPATH,TMP_CODE_LINENO,TMP_HTTP_METHOD,TMP_HTTP_URL,TMP_HTTP_TARGET,TMP_HTTP_HOST,TMP_HTTP_SCHEME,TMP_HTTP_STATUS_CODE,TMP_HTTP_FLAVOR,TMP_HTTP_USER_AGENT,TMP_HTTP_REQUEST_CONTENT_LENGTH,TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_RESPONSE_CONTENT_LENGTH,TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_SERVER_NAME,TMP_HTTP_ROUTE,TMP_HTTP_CLIENT_IP,TMP_AWS_DYNAMODB_TABLE_NAMES,TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,TMP_AWS_DYNAMODB_CONSISTENT_READ,TMP_AWS_DYNAMODB_PROJECTION,TMP_AWS_DYNAMODB_LIMIT,TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,TMP_AWS_DYNAMODB_INDEX_NAME,TMP_AWS_DYNAMODB_SELECT,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,TMP_AWS_DYNAMODB_TABLE_COUNT,TMP_AWS_DYNAMODB_SCAN_FORWARD,TMP_AWS_DYNAMODB_SEGMENT,TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,TMP_AWS_DYNAMODB_COUNT,TMP_AWS_DYNAMODB_SCANNED_COUNT,TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,TMP_MESSAGING_SYSTEM,TMP_MESSAGING_DESTINATION,TMP_MESSAGING_DESTINATION_KIND,TMP_MESSAGING_TEMP_DESTINATION,TMP_MESSAGING_PROTOCOL,TMP_MESSAGING_PROTOCOL_VERSION,TMP_MESSAGING_URL,TMP_MESSAGING_MESSAGE_ID,TMP_MESSAGING_CONVERSATION_ID,TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,TMP_MESSAGING_OPERATION,TMP_MESSAGING_CONSUMER_ID,TMP_MESSAGING_RABBITMQ_ROUTING_KEY,TMP_MESSAGING_KAFKA_MESSAGE_KEY,TMP_MESSAGING_KAFKA_CONSUMER_GROUP,TMP_MESSAGING_KAFKA_CLIENT_ID,TMP_MESSAGING_KAFKA_PARTITION,TMP_MESSAGING_KAFKA_TOMBSTONE,TMP_RPC_SYSTEM,TMP_RPC_SERVICE,TMP_RPC_METHOD,TMP_RPC_GRPC_STATUS_CODE,TMP_RPC_JSONRPC_VERSION,TMP_RPC_JSONRPC_REQUEST_ID,TMP_RPC_JSONRPC_ERROR_CODE,TMP_RPC_JSONRPC_ERROR_MESSAGE,TMP_MESSAGE_TYPE,TMP_MESSAGE_ID,TMP_MESSAGE_COMPRESSED_SIZE,TMP_MESSAGE_UNCOMPRESSED_SIZE,SEMATTRS_AWS_LAMBDA_INVOKED_ARN,SEMATTRS_DB_SYSTEM,SEMATTRS_DB_CONNECTION_STRING,SEMATTRS_DB_USER,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME,SEMATTRS_DB_NAME,SEMATTRS_DB_STATEMENT,SEMATTRS_DB_OPERATION,SEMATTRS_DB_MSSQL_INSTANCE_NAME,SEMATTRS_DB_CASSANDRA_KEYSPACE,SEMATTRS_DB_CASSANDRA_PAGE_SIZE,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL,SEMATTRS_DB_CASSANDRA_TABLE,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC,SEMATTRS_DB_HBASE_NAMESPACE,SEMATTRS_DB_REDIS_DATABASE_INDEX,SEMATTRS_DB_MONGODB_COLLECTION,SEMATTRS_DB_SQL_TABLE,SEMATTRS_EXCEPTION_TYPE,SEMATTRS_EXCEPTION_MESSAGE,SEMATTRS_EXCEPTION_STACKTRACE,SEMATTRS_EXCEPTION_ESCAPED,SEMATTRS_FAAS_TRIGGER,SEMATTRS_FAAS_EXECUTION,SEMATTRS_FAAS_DOCUMENT_COLLECTION,SEMATTRS_FAAS_DOCUMENT_OPERATION,SEMATTRS_FAAS_DOCUMENT_TIME,SEMATTRS_FAAS_DOCUMENT_NAME,SEMATTRS_FAAS_TIME,SEMATTRS_FAAS_CRON,SEMATTRS_FAAS_COLDSTART,SEMATTRS_FAAS_INVOKED_NAME,SEMATTRS_FAAS_INVOKED_PROVIDER,SEMATTRS_FAAS_INVOKED_REGION,SEMATTRS_NET_TRANSPORT,SEMATTRS_NET_PEER_IP,SEMATTRS_NET_PEER_PORT,SEMATTRS_NET_PEER_NAME,SEMATTRS_NET_HOST_IP,SEMATTRS_NET_HOST_PORT,SEMATTRS_NET_HOST_NAME,SEMATTRS_NET_HOST_CONNECTION_TYPE,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE,SEMATTRS_NET_HOST_CARRIER_NAME,SEMATTRS_NET_HOST_CARRIER_MCC,SEMATTRS_NET_HOST_CARRIER_MNC,SEMATTRS_NET_HOST_CARRIER_ICC,SEMATTRS_PEER_SERVICE,SEMATTRS_ENDUSER_ID,SEMATTRS_ENDUSER_ROLE,SEMATTRS_ENDUSER_SCOPE,SEMATTRS_THREAD_ID,SEMATTRS_THREAD_NAME,SEMATTRS_CODE_FUNCTION,SEMATTRS_CODE_NAMESPACE,SEMATTRS_CODE_FILEPATH,SEMATTRS_CODE_LINENO,SEMATTRS_HTTP_METHOD,SEMATTRS_HTTP_URL,SEMATTRS_HTTP_TARGET,SEMATTRS_HTTP_HOST,SEMATTRS_HTTP_SCHEME,SEMATTRS_HTTP_STATUS_CODE,SEMATTRS_HTTP_FLAVOR,SEMATTRS_HTTP_USER_AGENT,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_SERVER_NAME,SEMATTRS_HTTP_ROUTE,SEMATTRS_HTTP_CLIENT_IP,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ,SEMATTRS_AWS_DYNAMODB_PROJECTION,SEMATTRS_AWS_DYNAMODB_LIMIT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET,SEMATTRS_AWS_DYNAMODB_INDEX_NAME,SEMATTRS_AWS_DYNAMODB_SELECT,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD,SEMATTRS_AWS_DYNAMODB_SEGMENT,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS,SEMATTRS_AWS_DYNAMODB_COUNT,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,SEMATTRS_MESSAGING_SYSTEM,SEMATTRS_MESSAGING_DESTINATION,SEMATTRS_MESSAGING_DESTINATION_KIND,SEMATTRS_MESSAGING_TEMP_DESTINATION,SEMATTRS_MESSAGING_PROTOCOL,SEMATTRS_MESSAGING_PROTOCOL_VERSION,SEMATTRS_MESSAGING_URL,SEMATTRS_MESSAGING_MESSAGE_ID,SEMATTRS_MESSAGING_CONVERSATION_ID,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,SEMATTRS_MESSAGING_OPERATION,SEMATTRS_MESSAGING_CONSUMER_ID,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID,SEMATTRS_MESSAGING_KAFKA_PARTITION,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE,SEMATTRS_RPC_SYSTEM,SEMATTRS_RPC_SERVICE,SEMATTRS_RPC_METHOD,SEMATTRS_RPC_GRPC_STATUS_CODE,SEMATTRS_RPC_JSONRPC_VERSION,SEMATTRS_RPC_JSONRPC_REQUEST_ID,SEMATTRS_RPC_JSONRPC_ERROR_CODE,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE,SEMATTRS_MESSAGE_TYPE,SEMATTRS_MESSAGE_ID,SEMATTRS_MESSAGE_COMPRESSED_SIZE,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE,SemanticAttributes,TMP_DBSYSTEMVALUES_OTHER_SQL,TMP_DBSYSTEMVALUES_MSSQL,TMP_DBSYSTEMVALUES_MYSQL,TMP_DBSYSTEMVALUES_ORACLE,TMP_DBSYSTEMVALUES_DB2,TMP_DBSYSTEMVALUES_POSTGRESQL,TMP_DBSYSTEMVALUES_REDSHIFT,TMP_DBSYSTEMVALUES_HIVE,TMP_DBSYSTEMVALUES_CLOUDSCAPE,TMP_DBSYSTEMVALUES_HSQLDB,TMP_DBSYSTEMVALUES_PROGRESS,TMP_DBSYSTEMVALUES_MAXDB,TMP_DBSYSTEMVALUES_HANADB,TMP_DBSYSTEMVALUES_INGRES,TMP_DBSYSTEMVALUES_FIRSTSQL,TMP_DBSYSTEMVALUES_EDB,TMP_DBSYSTEMVALUES_CACHE,TMP_DBSYSTEMVALUES_ADABAS,TMP_DBSYSTEMVALUES_FIREBIRD,TMP_DBSYSTEMVALUES_DERBY,TMP_DBSYSTEMVALUES_FILEMAKER,TMP_DBSYSTEMVALUES_INFORMIX,TMP_DBSYSTEMVALUES_INSTANTDB,TMP_DBSYSTEMVALUES_INTERBASE,TMP_DBSYSTEMVALUES_MARIADB,TMP_DBSYSTEMVALUES_NETEZZA,TMP_DBSYSTEMVALUES_PERVASIVE,TMP_DBSYSTEMVALUES_POINTBASE,TMP_DBSYSTEMVALUES_SQLITE,TMP_DBSYSTEMVALUES_SYBASE,TMP_DBSYSTEMVALUES_TERADATA,TMP_DBSYSTEMVALUES_VERTICA,TMP_DBSYSTEMVALUES_H2,TMP_DBSYSTEMVALUES_COLDFUSION,TMP_DBSYSTEMVALUES_CASSANDRA,TMP_DBSYSTEMVALUES_HBASE,TMP_DBSYSTEMVALUES_MONGODB,TMP_DBSYSTEMVALUES_REDIS,TMP_DBSYSTEMVALUES_COUCHBASE,TMP_DBSYSTEMVALUES_COUCHDB,TMP_DBSYSTEMVALUES_COSMOSDB,TMP_DBSYSTEMVALUES_DYNAMODB,TMP_DBSYSTEMVALUES_NEO4J,TMP_DBSYSTEMVALUES_GEODE,TMP_DBSYSTEMVALUES_ELASTICSEARCH,TMP_DBSYSTEMVALUES_MEMCACHED,TMP_DBSYSTEMVALUES_COCKROACHDB,DBSYSTEMVALUES_OTHER_SQL,DBSYSTEMVALUES_MSSQL,DBSYSTEMVALUES_MYSQL,DBSYSTEMVALUES_ORACLE,DBSYSTEMVALUES_DB2,DBSYSTEMVALUES_POSTGRESQL,DBSYSTEMVALUES_REDSHIFT,DBSYSTEMVALUES_HIVE,DBSYSTEMVALUES_CLOUDSCAPE,DBSYSTEMVALUES_HSQLDB,DBSYSTEMVALUES_PROGRESS,DBSYSTEMVALUES_MAXDB,DBSYSTEMVALUES_HANADB,DBSYSTEMVALUES_INGRES,DBSYSTEMVALUES_FIRSTSQL,DBSYSTEMVALUES_EDB,DBSYSTEMVALUES_CACHE,DBSYSTEMVALUES_ADABAS,DBSYSTEMVALUES_FIREBIRD,DBSYSTEMVALUES_DERBY,DBSYSTEMVALUES_FILEMAKER,DBSYSTEMVALUES_INFORMIX,DBSYSTEMVALUES_INSTANTDB,DBSYSTEMVALUES_INTERBASE,DBSYSTEMVALUES_MARIADB,DBSYSTEMVALUES_NETEZZA,DBSYSTEMVALUES_PERVASIVE,DBSYSTEMVALUES_POINTBASE,DBSYSTEMVALUES_SQLITE,DBSYSTEMVALUES_SYBASE,DBSYSTEMVALUES_TERADATA,DBSYSTEMVALUES_VERTICA,DBSYSTEMVALUES_H2,DBSYSTEMVALUES_COLDFUSION,DBSYSTEMVALUES_CASSANDRA,DBSYSTEMVALUES_HBASE,DBSYSTEMVALUES_MONGODB,DBSYSTEMVALUES_REDIS,DBSYSTEMVALUES_COUCHBASE,DBSYSTEMVALUES_COUCHDB,DBSYSTEMVALUES_COSMOSDB,DBSYSTEMVALUES_DYNAMODB,DBSYSTEMVALUES_NEO4J,DBSYSTEMVALUES_GEODE,DBSYSTEMVALUES_ELASTICSEARCH,DBSYSTEMVALUES_MEMCACHED,DBSYSTEMVALUES_COCKROACHDB,DbSystemValues,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_ALL,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_TWO,DBCASSANDRACONSISTENCYLEVELVALUES_THREE,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_ANY,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DbCassandraConsistencyLevelValues,TMP_FAASTRIGGERVALUES_DATASOURCE,TMP_FAASTRIGGERVALUES_HTTP,TMP_FAASTRIGGERVALUES_PUBSUB,TMP_FAASTRIGGERVALUES_TIMER,TMP_FAASTRIGGERVALUES_OTHER,FAASTRIGGERVALUES_DATASOURCE,FAASTRIGGERVALUES_HTTP,FAASTRIGGERVALUES_PUBSUB,FAASTRIGGERVALUES_TIMER,FAASTRIGGERVALUES_OTHER,FaasTriggerValues,TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,TMP_FAASDOCUMENTOPERATIONVALUES_DELETE,FAASDOCUMENTOPERATIONVALUES_INSERT,FAASDOCUMENTOPERATIONVALUES_EDIT,FAASDOCUMENTOPERATIONVALUES_DELETE,FaasDocumentOperationValues,TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,TMP_FAASINVOKEDPROVIDERVALUES_AWS,TMP_FAASINVOKEDPROVIDERVALUES_AZURE,TMP_FAASINVOKEDPROVIDERVALUES_GCP,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,FAASINVOKEDPROVIDERVALUES_AWS,FAASINVOKEDPROVIDERVALUES_AZURE,FAASINVOKEDPROVIDERVALUES_GCP,FaasInvokedProviderValues,TMP_NETTRANSPORTVALUES_IP_TCP,TMP_NETTRANSPORTVALUES_IP_UDP,TMP_NETTRANSPORTVALUES_IP,TMP_NETTRANSPORTVALUES_UNIX,TMP_NETTRANSPORTVALUES_PIPE,TMP_NETTRANSPORTVALUES_INPROC,TMP_NETTRANSPORTVALUES_OTHER,NETTRANSPORTVALUES_IP_TCP,NETTRANSPORTVALUES_IP_UDP,NETTRANSPORTVALUES_IP,NETTRANSPORTVALUES_UNIX,NETTRANSPORTVALUES_PIPE,NETTRANSPORTVALUES_INPROC,NETTRANSPORTVALUES_OTHER,NetTransportValues,TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NETHOSTCONNECTIONTYPEVALUES_WIFI,NETHOSTCONNECTIONTYPEVALUES_WIRED,NETHOSTCONNECTIONTYPEVALUES_CELL,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NetHostConnectionTypeValues,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,NETHOSTCONNECTIONSUBTYPEVALUES_LTE,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,NETHOSTCONNECTIONSUBTYPEVALUES_GSM,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,NETHOSTCONNECTIONSUBTYPEVALUES_NR,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NetHostConnectionSubtypeValues,TMP_HTTPFLAVORVALUES_HTTP_1_0,TMP_HTTPFLAVORVALUES_HTTP_1_1,TMP_HTTPFLAVORVALUES_HTTP_2_0,TMP_HTTPFLAVORVALUES_SPDY,TMP_HTTPFLAVORVALUES_QUIC,HTTPFLAVORVALUES_HTTP_1_0,HTTPFLAVORVALUES_HTTP_1_1,HTTPFLAVORVALUES_HTTP_2_0,HTTPFLAVORVALUES_SPDY,HTTPFLAVORVALUES_QUIC,HttpFlavorValues,TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC,MESSAGINGDESTINATIONKINDVALUES_QUEUE,MESSAGINGDESTINATIONKINDVALUES_TOPIC,MessagingDestinationKindValues,TMP_MESSAGINGOPERATIONVALUES_RECEIVE,TMP_MESSAGINGOPERATIONVALUES_PROCESS,MESSAGINGOPERATIONVALUES_RECEIVE,MESSAGINGOPERATIONVALUES_PROCESS,MessagingOperationValues,TMP_RPCGRPCSTATUSCODEVALUES_OK,TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED,TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN,TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND,TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,TMP_RPCGRPCSTATUSCODEVALUES_ABORTED,TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL,TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS,TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED,RPCGRPCSTATUSCODEVALUES_OK,RPCGRPCSTATUSCODEVALUES_CANCELLED,RPCGRPCSTATUSCODEVALUES_UNKNOWN,RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,RPCGRPCSTATUSCODEVALUES_NOT_FOUND,RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,RPCGRPCSTATUSCODEVALUES_ABORTED,RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,RPCGRPCSTATUSCODEVALUES_INTERNAL,RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,RPCGRPCSTATUSCODEVALUES_DATA_LOSS,RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED,RpcGrpcStatusCodeValues,TMP_MESSAGETYPEVALUES_SENT,TMP_MESSAGETYPEVALUES_RECEIVED,MESSAGETYPEVALUES_SENT,MESSAGETYPEVALUES_RECEIVED,MessageTypeValues,init_SemanticAttributes=__esmMin((()=>{init_utils(),TMP_AWS_LAMBDA_INVOKED_ARN=`aws.lambda.invoked_arn`,TMP_DB_SYSTEM=`db.system`,TMP_DB_CONNECTION_STRING=`db.connection_string`,TMP_DB_USER=`db.user`,TMP_DB_JDBC_DRIVER_CLASSNAME=`db.jdbc.driver_classname`,TMP_DB_NAME=`db.name`,TMP_DB_STATEMENT=`db.statement`,TMP_DB_OPERATION=`db.operation`,TMP_DB_MSSQL_INSTANCE_NAME=`db.mssql.instance_name`,TMP_DB_CASSANDRA_KEYSPACE=`db.cassandra.keyspace`,TMP_DB_CASSANDRA_PAGE_SIZE=`db.cassandra.page_size`,TMP_DB_CASSANDRA_CONSISTENCY_LEVEL=`db.cassandra.consistency_level`,TMP_DB_CASSANDRA_TABLE=`db.cassandra.table`,TMP_DB_CASSANDRA_IDEMPOTENCE=`db.cassandra.idempotence`,TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT=`db.cassandra.speculative_execution_count`,TMP_DB_CASSANDRA_COORDINATOR_ID=`db.cassandra.coordinator.id`,TMP_DB_CASSANDRA_COORDINATOR_DC=`db.cassandra.coordinator.dc`,TMP_DB_HBASE_NAMESPACE=`db.hbase.namespace`,TMP_DB_REDIS_DATABASE_INDEX=`db.redis.database_index`,TMP_DB_MONGODB_COLLECTION=`db.mongodb.collection`,TMP_DB_SQL_TABLE=`db.sql.table`,TMP_EXCEPTION_TYPE=`exception.type`,TMP_EXCEPTION_MESSAGE=`exception.message`,TMP_EXCEPTION_STACKTRACE=`exception.stacktrace`,TMP_EXCEPTION_ESCAPED=`exception.escaped`,TMP_FAAS_TRIGGER=`faas.trigger`,TMP_FAAS_EXECUTION=`faas.execution`,TMP_FAAS_DOCUMENT_COLLECTION=`faas.document.collection`,TMP_FAAS_DOCUMENT_OPERATION=`faas.document.operation`,TMP_FAAS_DOCUMENT_TIME=`faas.document.time`,TMP_FAAS_DOCUMENT_NAME=`faas.document.name`,TMP_FAAS_TIME=`faas.time`,TMP_FAAS_CRON=`faas.cron`,TMP_FAAS_COLDSTART=`faas.coldstart`,TMP_FAAS_INVOKED_NAME=`faas.invoked_name`,TMP_FAAS_INVOKED_PROVIDER=`faas.invoked_provider`,TMP_FAAS_INVOKED_REGION=`faas.invoked_region`,TMP_NET_TRANSPORT=`net.transport`,TMP_NET_PEER_IP=`net.peer.ip`,TMP_NET_PEER_PORT=`net.peer.port`,TMP_NET_PEER_NAME=`net.peer.name`,TMP_NET_HOST_IP=`net.host.ip`,TMP_NET_HOST_PORT=`net.host.port`,TMP_NET_HOST_NAME=`net.host.name`,TMP_NET_HOST_CONNECTION_TYPE=`net.host.connection.type`,TMP_NET_HOST_CONNECTION_SUBTYPE=`net.host.connection.subtype`,TMP_NET_HOST_CARRIER_NAME=`net.host.carrier.name`,TMP_NET_HOST_CARRIER_MCC=`net.host.carrier.mcc`,TMP_NET_HOST_CARRIER_MNC=`net.host.carrier.mnc`,TMP_NET_HOST_CARRIER_ICC=`net.host.carrier.icc`,TMP_PEER_SERVICE=`peer.service`,TMP_ENDUSER_ID=`enduser.id`,TMP_ENDUSER_ROLE=`enduser.role`,TMP_ENDUSER_SCOPE=`enduser.scope`,TMP_THREAD_ID=`thread.id`,TMP_THREAD_NAME=`thread.name`,TMP_CODE_FUNCTION=`code.function`,TMP_CODE_NAMESPACE=`code.namespace`,TMP_CODE_FILEPATH=`code.filepath`,TMP_CODE_LINENO=`code.lineno`,TMP_HTTP_METHOD=`http.method`,TMP_HTTP_URL=`http.url`,TMP_HTTP_TARGET=`http.target`,TMP_HTTP_HOST=`http.host`,TMP_HTTP_SCHEME=`http.scheme`,TMP_HTTP_STATUS_CODE=`http.status_code`,TMP_HTTP_FLAVOR=`http.flavor`,TMP_HTTP_USER_AGENT=`http.user_agent`,TMP_HTTP_REQUEST_CONTENT_LENGTH=`http.request_content_length`,TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED=`http.request_content_length_uncompressed`,TMP_HTTP_RESPONSE_CONTENT_LENGTH=`http.response_content_length`,TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED=`http.response_content_length_uncompressed`,TMP_HTTP_SERVER_NAME=`http.server_name`,TMP_HTTP_ROUTE=`http.route`,TMP_HTTP_CLIENT_IP=`http.client_ip`,TMP_AWS_DYNAMODB_TABLE_NAMES=`aws.dynamodb.table_names`,TMP_AWS_DYNAMODB_CONSUMED_CAPACITY=`aws.dynamodb.consumed_capacity`,TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS=`aws.dynamodb.item_collection_metrics`,TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY=`aws.dynamodb.provisioned_read_capacity`,TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY=`aws.dynamodb.provisioned_write_capacity`,TMP_AWS_DYNAMODB_CONSISTENT_READ=`aws.dynamodb.consistent_read`,TMP_AWS_DYNAMODB_PROJECTION=`aws.dynamodb.projection`,TMP_AWS_DYNAMODB_LIMIT=`aws.dynamodb.limit`,TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET=`aws.dynamodb.attributes_to_get`,TMP_AWS_DYNAMODB_INDEX_NAME=`aws.dynamodb.index_name`,TMP_AWS_DYNAMODB_SELECT=`aws.dynamodb.select`,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES=`aws.dynamodb.global_secondary_indexes`,TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES=`aws.dynamodb.local_secondary_indexes`,TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE=`aws.dynamodb.exclusive_start_table`,TMP_AWS_DYNAMODB_TABLE_COUNT=`aws.dynamodb.table_count`,TMP_AWS_DYNAMODB_SCAN_FORWARD=`aws.dynamodb.scan_forward`,TMP_AWS_DYNAMODB_SEGMENT=`aws.dynamodb.segment`,TMP_AWS_DYNAMODB_TOTAL_SEGMENTS=`aws.dynamodb.total_segments`,TMP_AWS_DYNAMODB_COUNT=`aws.dynamodb.count`,TMP_AWS_DYNAMODB_SCANNED_COUNT=`aws.dynamodb.scanned_count`,TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS=`aws.dynamodb.attribute_definitions`,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES=`aws.dynamodb.global_secondary_index_updates`,TMP_MESSAGING_SYSTEM=`messaging.system`,TMP_MESSAGING_DESTINATION=`messaging.destination`,TMP_MESSAGING_DESTINATION_KIND=`messaging.destination_kind`,TMP_MESSAGING_TEMP_DESTINATION=`messaging.temp_destination`,TMP_MESSAGING_PROTOCOL=`messaging.protocol`,TMP_MESSAGING_PROTOCOL_VERSION=`messaging.protocol_version`,TMP_MESSAGING_URL=`messaging.url`,TMP_MESSAGING_MESSAGE_ID=`messaging.message_id`,TMP_MESSAGING_CONVERSATION_ID=`messaging.conversation_id`,TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES=`messaging.message_payload_size_bytes`,TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES=`messaging.message_payload_compressed_size_bytes`,TMP_MESSAGING_OPERATION=`messaging.operation`,TMP_MESSAGING_CONSUMER_ID=`messaging.consumer_id`,TMP_MESSAGING_RABBITMQ_ROUTING_KEY=`messaging.rabbitmq.routing_key`,TMP_MESSAGING_KAFKA_MESSAGE_KEY=`messaging.kafka.message_key`,TMP_MESSAGING_KAFKA_CONSUMER_GROUP=`messaging.kafka.consumer_group`,TMP_MESSAGING_KAFKA_CLIENT_ID=`messaging.kafka.client_id`,TMP_MESSAGING_KAFKA_PARTITION=`messaging.kafka.partition`,TMP_MESSAGING_KAFKA_TOMBSTONE=`messaging.kafka.tombstone`,TMP_RPC_SYSTEM=`rpc.system`,TMP_RPC_SERVICE=`rpc.service`,TMP_RPC_METHOD=`rpc.method`,TMP_RPC_GRPC_STATUS_CODE=`rpc.grpc.status_code`,TMP_RPC_JSONRPC_VERSION=`rpc.jsonrpc.version`,TMP_RPC_JSONRPC_REQUEST_ID=`rpc.jsonrpc.request_id`,TMP_RPC_JSONRPC_ERROR_CODE=`rpc.jsonrpc.error_code`,TMP_RPC_JSONRPC_ERROR_MESSAGE=`rpc.jsonrpc.error_message`,TMP_MESSAGE_TYPE=`message.type`,TMP_MESSAGE_ID=`message.id`,TMP_MESSAGE_COMPRESSED_SIZE=`message.compressed_size`,TMP_MESSAGE_UNCOMPRESSED_SIZE=`message.uncompressed_size`,SEMATTRS_AWS_LAMBDA_INVOKED_ARN=TMP_AWS_LAMBDA_INVOKED_ARN,SEMATTRS_DB_SYSTEM=TMP_DB_SYSTEM,SEMATTRS_DB_CONNECTION_STRING=TMP_DB_CONNECTION_STRING,SEMATTRS_DB_USER=TMP_DB_USER,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME=TMP_DB_JDBC_DRIVER_CLASSNAME,SEMATTRS_DB_NAME=TMP_DB_NAME,SEMATTRS_DB_STATEMENT=TMP_DB_STATEMENT,SEMATTRS_DB_OPERATION=TMP_DB_OPERATION,SEMATTRS_DB_MSSQL_INSTANCE_NAME=TMP_DB_MSSQL_INSTANCE_NAME,SEMATTRS_DB_CASSANDRA_KEYSPACE=TMP_DB_CASSANDRA_KEYSPACE,SEMATTRS_DB_CASSANDRA_PAGE_SIZE=TMP_DB_CASSANDRA_PAGE_SIZE,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL=TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,SEMATTRS_DB_CASSANDRA_TABLE=TMP_DB_CASSANDRA_TABLE,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE=TMP_DB_CASSANDRA_IDEMPOTENCE,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT=TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID=TMP_DB_CASSANDRA_COORDINATOR_ID,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC=TMP_DB_CASSANDRA_COORDINATOR_DC,SEMATTRS_DB_HBASE_NAMESPACE=TMP_DB_HBASE_NAMESPACE,SEMATTRS_DB_REDIS_DATABASE_INDEX=TMP_DB_REDIS_DATABASE_INDEX,SEMATTRS_DB_MONGODB_COLLECTION=TMP_DB_MONGODB_COLLECTION,SEMATTRS_DB_SQL_TABLE=TMP_DB_SQL_TABLE,SEMATTRS_EXCEPTION_TYPE=TMP_EXCEPTION_TYPE,SEMATTRS_EXCEPTION_MESSAGE=TMP_EXCEPTION_MESSAGE,SEMATTRS_EXCEPTION_STACKTRACE=TMP_EXCEPTION_STACKTRACE,SEMATTRS_EXCEPTION_ESCAPED=TMP_EXCEPTION_ESCAPED,SEMATTRS_FAAS_TRIGGER=TMP_FAAS_TRIGGER,SEMATTRS_FAAS_EXECUTION=TMP_FAAS_EXECUTION,SEMATTRS_FAAS_DOCUMENT_COLLECTION=TMP_FAAS_DOCUMENT_COLLECTION,SEMATTRS_FAAS_DOCUMENT_OPERATION=TMP_FAAS_DOCUMENT_OPERATION,SEMATTRS_FAAS_DOCUMENT_TIME=TMP_FAAS_DOCUMENT_TIME,SEMATTRS_FAAS_DOCUMENT_NAME=TMP_FAAS_DOCUMENT_NAME,SEMATTRS_FAAS_TIME=TMP_FAAS_TIME,SEMATTRS_FAAS_CRON=TMP_FAAS_CRON,SEMATTRS_FAAS_COLDSTART=TMP_FAAS_COLDSTART,SEMATTRS_FAAS_INVOKED_NAME=TMP_FAAS_INVOKED_NAME,SEMATTRS_FAAS_INVOKED_PROVIDER=TMP_FAAS_INVOKED_PROVIDER,SEMATTRS_FAAS_INVOKED_REGION=TMP_FAAS_INVOKED_REGION,SEMATTRS_NET_TRANSPORT=TMP_NET_TRANSPORT,SEMATTRS_NET_PEER_IP=TMP_NET_PEER_IP,SEMATTRS_NET_PEER_PORT=TMP_NET_PEER_PORT,SEMATTRS_NET_PEER_NAME=TMP_NET_PEER_NAME,SEMATTRS_NET_HOST_IP=TMP_NET_HOST_IP,SEMATTRS_NET_HOST_PORT=TMP_NET_HOST_PORT,SEMATTRS_NET_HOST_NAME=TMP_NET_HOST_NAME,SEMATTRS_NET_HOST_CONNECTION_TYPE=TMP_NET_HOST_CONNECTION_TYPE,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE=TMP_NET_HOST_CONNECTION_SUBTYPE,SEMATTRS_NET_HOST_CARRIER_NAME=TMP_NET_HOST_CARRIER_NAME,SEMATTRS_NET_HOST_CARRIER_MCC=TMP_NET_HOST_CARRIER_MCC,SEMATTRS_NET_HOST_CARRIER_MNC=TMP_NET_HOST_CARRIER_MNC,SEMATTRS_NET_HOST_CARRIER_ICC=TMP_NET_HOST_CARRIER_ICC,SEMATTRS_PEER_SERVICE=TMP_PEER_SERVICE,SEMATTRS_ENDUSER_ID=TMP_ENDUSER_ID,SEMATTRS_ENDUSER_ROLE=TMP_ENDUSER_ROLE,SEMATTRS_ENDUSER_SCOPE=TMP_ENDUSER_SCOPE,SEMATTRS_THREAD_ID=TMP_THREAD_ID,SEMATTRS_THREAD_NAME=TMP_THREAD_NAME,SEMATTRS_CODE_FUNCTION=TMP_CODE_FUNCTION,SEMATTRS_CODE_NAMESPACE=TMP_CODE_NAMESPACE,SEMATTRS_CODE_FILEPATH=TMP_CODE_FILEPATH,SEMATTRS_CODE_LINENO=TMP_CODE_LINENO,SEMATTRS_HTTP_METHOD=TMP_HTTP_METHOD,SEMATTRS_HTTP_URL=TMP_HTTP_URL,SEMATTRS_HTTP_TARGET=TMP_HTTP_TARGET,SEMATTRS_HTTP_HOST=TMP_HTTP_HOST,SEMATTRS_HTTP_SCHEME=TMP_HTTP_SCHEME,SEMATTRS_HTTP_STATUS_CODE=TMP_HTTP_STATUS_CODE,SEMATTRS_HTTP_FLAVOR=TMP_HTTP_FLAVOR,SEMATTRS_HTTP_USER_AGENT=TMP_HTTP_USER_AGENT,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH=TMP_HTTP_REQUEST_CONTENT_LENGTH,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED=TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH=TMP_HTTP_RESPONSE_CONTENT_LENGTH,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED=TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_SERVER_NAME=TMP_HTTP_SERVER_NAME,SEMATTRS_HTTP_ROUTE=TMP_HTTP_ROUTE,SEMATTRS_HTTP_CLIENT_IP=TMP_HTTP_CLIENT_IP,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES=TMP_AWS_DYNAMODB_TABLE_NAMES,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY=TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS=TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY=TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY=TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ=TMP_AWS_DYNAMODB_CONSISTENT_READ,SEMATTRS_AWS_DYNAMODB_PROJECTION=TMP_AWS_DYNAMODB_PROJECTION,SEMATTRS_AWS_DYNAMODB_LIMIT=TMP_AWS_DYNAMODB_LIMIT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET=TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,SEMATTRS_AWS_DYNAMODB_INDEX_NAME=TMP_AWS_DYNAMODB_INDEX_NAME,SEMATTRS_AWS_DYNAMODB_SELECT=TMP_AWS_DYNAMODB_SELECT,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES=TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES=TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE=TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT=TMP_AWS_DYNAMODB_TABLE_COUNT,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD=TMP_AWS_DYNAMODB_SCAN_FORWARD,SEMATTRS_AWS_DYNAMODB_SEGMENT=TMP_AWS_DYNAMODB_SEGMENT,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS=TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,SEMATTRS_AWS_DYNAMODB_COUNT=TMP_AWS_DYNAMODB_COUNT,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT=TMP_AWS_DYNAMODB_SCANNED_COUNT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS=TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES=TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,SEMATTRS_MESSAGING_SYSTEM=TMP_MESSAGING_SYSTEM,SEMATTRS_MESSAGING_DESTINATION=TMP_MESSAGING_DESTINATION,SEMATTRS_MESSAGING_DESTINATION_KIND=TMP_MESSAGING_DESTINATION_KIND,SEMATTRS_MESSAGING_TEMP_DESTINATION=TMP_MESSAGING_TEMP_DESTINATION,SEMATTRS_MESSAGING_PROTOCOL=TMP_MESSAGING_PROTOCOL,SEMATTRS_MESSAGING_PROTOCOL_VERSION=TMP_MESSAGING_PROTOCOL_VERSION,SEMATTRS_MESSAGING_URL=TMP_MESSAGING_URL,SEMATTRS_MESSAGING_MESSAGE_ID=TMP_MESSAGING_MESSAGE_ID,SEMATTRS_MESSAGING_CONVERSATION_ID=TMP_MESSAGING_CONVERSATION_ID,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES=TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES=TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,SEMATTRS_MESSAGING_OPERATION=TMP_MESSAGING_OPERATION,SEMATTRS_MESSAGING_CONSUMER_ID=TMP_MESSAGING_CONSUMER_ID,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY=TMP_MESSAGING_RABBITMQ_ROUTING_KEY,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY=TMP_MESSAGING_KAFKA_MESSAGE_KEY,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP=TMP_MESSAGING_KAFKA_CONSUMER_GROUP,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID=TMP_MESSAGING_KAFKA_CLIENT_ID,SEMATTRS_MESSAGING_KAFKA_PARTITION=TMP_MESSAGING_KAFKA_PARTITION,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE=TMP_MESSAGING_KAFKA_TOMBSTONE,SEMATTRS_RPC_SYSTEM=TMP_RPC_SYSTEM,SEMATTRS_RPC_SERVICE=TMP_RPC_SERVICE,SEMATTRS_RPC_METHOD=TMP_RPC_METHOD,SEMATTRS_RPC_GRPC_STATUS_CODE=TMP_RPC_GRPC_STATUS_CODE,SEMATTRS_RPC_JSONRPC_VERSION=TMP_RPC_JSONRPC_VERSION,SEMATTRS_RPC_JSONRPC_REQUEST_ID=TMP_RPC_JSONRPC_REQUEST_ID,SEMATTRS_RPC_JSONRPC_ERROR_CODE=TMP_RPC_JSONRPC_ERROR_CODE,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE=TMP_RPC_JSONRPC_ERROR_MESSAGE,SEMATTRS_MESSAGE_TYPE=TMP_MESSAGE_TYPE,SEMATTRS_MESSAGE_ID=TMP_MESSAGE_ID,SEMATTRS_MESSAGE_COMPRESSED_SIZE=TMP_MESSAGE_COMPRESSED_SIZE,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE=TMP_MESSAGE_UNCOMPRESSED_SIZE,SemanticAttributes=createConstMap([TMP_AWS_LAMBDA_INVOKED_ARN,TMP_DB_SYSTEM,TMP_DB_CONNECTION_STRING,TMP_DB_USER,TMP_DB_JDBC_DRIVER_CLASSNAME,TMP_DB_NAME,TMP_DB_STATEMENT,TMP_DB_OPERATION,TMP_DB_MSSQL_INSTANCE_NAME,TMP_DB_CASSANDRA_KEYSPACE,TMP_DB_CASSANDRA_PAGE_SIZE,TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,TMP_DB_CASSANDRA_TABLE,TMP_DB_CASSANDRA_IDEMPOTENCE,TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,TMP_DB_CASSANDRA_COORDINATOR_ID,TMP_DB_CASSANDRA_COORDINATOR_DC,TMP_DB_HBASE_NAMESPACE,TMP_DB_REDIS_DATABASE_INDEX,TMP_DB_MONGODB_COLLECTION,TMP_DB_SQL_TABLE,TMP_EXCEPTION_TYPE,TMP_EXCEPTION_MESSAGE,TMP_EXCEPTION_STACKTRACE,TMP_EXCEPTION_ESCAPED,TMP_FAAS_TRIGGER,TMP_FAAS_EXECUTION,TMP_FAAS_DOCUMENT_COLLECTION,TMP_FAAS_DOCUMENT_OPERATION,TMP_FAAS_DOCUMENT_TIME,TMP_FAAS_DOCUMENT_NAME,TMP_FAAS_TIME,TMP_FAAS_CRON,TMP_FAAS_COLDSTART,TMP_FAAS_INVOKED_NAME,TMP_FAAS_INVOKED_PROVIDER,TMP_FAAS_INVOKED_REGION,TMP_NET_TRANSPORT,TMP_NET_PEER_IP,TMP_NET_PEER_PORT,TMP_NET_PEER_NAME,TMP_NET_HOST_IP,TMP_NET_HOST_PORT,TMP_NET_HOST_NAME,TMP_NET_HOST_CONNECTION_TYPE,TMP_NET_HOST_CONNECTION_SUBTYPE,TMP_NET_HOST_CARRIER_NAME,TMP_NET_HOST_CARRIER_MCC,TMP_NET_HOST_CARRIER_MNC,TMP_NET_HOST_CARRIER_ICC,TMP_PEER_SERVICE,TMP_ENDUSER_ID,TMP_ENDUSER_ROLE,TMP_ENDUSER_SCOPE,TMP_THREAD_ID,TMP_THREAD_NAME,TMP_CODE_FUNCTION,TMP_CODE_NAMESPACE,TMP_CODE_FILEPATH,TMP_CODE_LINENO,TMP_HTTP_METHOD,TMP_HTTP_URL,TMP_HTTP_TARGET,TMP_HTTP_HOST,TMP_HTTP_SCHEME,TMP_HTTP_STATUS_CODE,TMP_HTTP_FLAVOR,TMP_HTTP_USER_AGENT,TMP_HTTP_REQUEST_CONTENT_LENGTH,TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_RESPONSE_CONTENT_LENGTH,TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_SERVER_NAME,TMP_HTTP_ROUTE,TMP_HTTP_CLIENT_IP,TMP_AWS_DYNAMODB_TABLE_NAMES,TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,TMP_AWS_DYNAMODB_CONSISTENT_READ,TMP_AWS_DYNAMODB_PROJECTION,TMP_AWS_DYNAMODB_LIMIT,TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,TMP_AWS_DYNAMODB_INDEX_NAME,TMP_AWS_DYNAMODB_SELECT,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,TMP_AWS_DYNAMODB_TABLE_COUNT,TMP_AWS_DYNAMODB_SCAN_FORWARD,TMP_AWS_DYNAMODB_SEGMENT,TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,TMP_AWS_DYNAMODB_COUNT,TMP_AWS_DYNAMODB_SCANNED_COUNT,TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,TMP_MESSAGING_SYSTEM,TMP_MESSAGING_DESTINATION,TMP_MESSAGING_DESTINATION_KIND,TMP_MESSAGING_TEMP_DESTINATION,TMP_MESSAGING_PROTOCOL,TMP_MESSAGING_PROTOCOL_VERSION,TMP_MESSAGING_URL,TMP_MESSAGING_MESSAGE_ID,TMP_MESSAGING_CONVERSATION_ID,TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,TMP_MESSAGING_OPERATION,TMP_MESSAGING_CONSUMER_ID,TMP_MESSAGING_RABBITMQ_ROUTING_KEY,TMP_MESSAGING_KAFKA_MESSAGE_KEY,TMP_MESSAGING_KAFKA_CONSUMER_GROUP,TMP_MESSAGING_KAFKA_CLIENT_ID,TMP_MESSAGING_KAFKA_PARTITION,TMP_MESSAGING_KAFKA_TOMBSTONE,TMP_RPC_SYSTEM,TMP_RPC_SERVICE,TMP_RPC_METHOD,TMP_RPC_GRPC_STATUS_CODE,TMP_RPC_JSONRPC_VERSION,TMP_RPC_JSONRPC_REQUEST_ID,TMP_RPC_JSONRPC_ERROR_CODE,TMP_RPC_JSONRPC_ERROR_MESSAGE,TMP_MESSAGE_TYPE,TMP_MESSAGE_ID,TMP_MESSAGE_COMPRESSED_SIZE,TMP_MESSAGE_UNCOMPRESSED_SIZE]),TMP_DBSYSTEMVALUES_OTHER_SQL=`other_sql`,TMP_DBSYSTEMVALUES_MSSQL=`mssql`,TMP_DBSYSTEMVALUES_MYSQL=`mysql`,TMP_DBSYSTEMVALUES_ORACLE=`oracle`,TMP_DBSYSTEMVALUES_DB2=`db2`,TMP_DBSYSTEMVALUES_POSTGRESQL=`postgresql`,TMP_DBSYSTEMVALUES_REDSHIFT=`redshift`,TMP_DBSYSTEMVALUES_HIVE=`hive`,TMP_DBSYSTEMVALUES_CLOUDSCAPE=`cloudscape`,TMP_DBSYSTEMVALUES_HSQLDB=`hsqldb`,TMP_DBSYSTEMVALUES_PROGRESS=`progress`,TMP_DBSYSTEMVALUES_MAXDB=`maxdb`,TMP_DBSYSTEMVALUES_HANADB=`hanadb`,TMP_DBSYSTEMVALUES_INGRES=`ingres`,TMP_DBSYSTEMVALUES_FIRSTSQL=`firstsql`,TMP_DBSYSTEMVALUES_EDB=`edb`,TMP_DBSYSTEMVALUES_CACHE=`cache`,TMP_DBSYSTEMVALUES_ADABAS=`adabas`,TMP_DBSYSTEMVALUES_FIREBIRD=`firebird`,TMP_DBSYSTEMVALUES_DERBY=`derby`,TMP_DBSYSTEMVALUES_FILEMAKER=`filemaker`,TMP_DBSYSTEMVALUES_INFORMIX=`informix`,TMP_DBSYSTEMVALUES_INSTANTDB=`instantdb`,TMP_DBSYSTEMVALUES_INTERBASE=`interbase`,TMP_DBSYSTEMVALUES_MARIADB=`mariadb`,TMP_DBSYSTEMVALUES_NETEZZA=`netezza`,TMP_DBSYSTEMVALUES_PERVASIVE=`pervasive`,TMP_DBSYSTEMVALUES_POINTBASE=`pointbase`,TMP_DBSYSTEMVALUES_SQLITE=`sqlite`,TMP_DBSYSTEMVALUES_SYBASE=`sybase`,TMP_DBSYSTEMVALUES_TERADATA=`teradata`,TMP_DBSYSTEMVALUES_VERTICA=`vertica`,TMP_DBSYSTEMVALUES_H2=`h2`,TMP_DBSYSTEMVALUES_COLDFUSION=`coldfusion`,TMP_DBSYSTEMVALUES_CASSANDRA=`cassandra`,TMP_DBSYSTEMVALUES_HBASE=`hbase`,TMP_DBSYSTEMVALUES_MONGODB=`mongodb`,TMP_DBSYSTEMVALUES_REDIS=`redis`,TMP_DBSYSTEMVALUES_COUCHBASE=`couchbase`,TMP_DBSYSTEMVALUES_COUCHDB=`couchdb`,TMP_DBSYSTEMVALUES_COSMOSDB=`cosmosdb`,TMP_DBSYSTEMVALUES_DYNAMODB=`dynamodb`,TMP_DBSYSTEMVALUES_NEO4J=`neo4j`,TMP_DBSYSTEMVALUES_GEODE=`geode`,TMP_DBSYSTEMVALUES_ELASTICSEARCH=`elasticsearch`,TMP_DBSYSTEMVALUES_MEMCACHED=`memcached`,TMP_DBSYSTEMVALUES_COCKROACHDB=`cockroachdb`,DBSYSTEMVALUES_OTHER_SQL=TMP_DBSYSTEMVALUES_OTHER_SQL,DBSYSTEMVALUES_MSSQL=TMP_DBSYSTEMVALUES_MSSQL,DBSYSTEMVALUES_MYSQL=TMP_DBSYSTEMVALUES_MYSQL,DBSYSTEMVALUES_ORACLE=TMP_DBSYSTEMVALUES_ORACLE,DBSYSTEMVALUES_POSTGRESQL=TMP_DBSYSTEMVALUES_POSTGRESQL,DBSYSTEMVALUES_REDSHIFT=TMP_DBSYSTEMVALUES_REDSHIFT,DBSYSTEMVALUES_HIVE=TMP_DBSYSTEMVALUES_HIVE,DBSYSTEMVALUES_CLOUDSCAPE=TMP_DBSYSTEMVALUES_CLOUDSCAPE,DBSYSTEMVALUES_HSQLDB=TMP_DBSYSTEMVALUES_HSQLDB,DBSYSTEMVALUES_PROGRESS=TMP_DBSYSTEMVALUES_PROGRESS,DBSYSTEMVALUES_MAXDB=TMP_DBSYSTEMVALUES_MAXDB,DBSYSTEMVALUES_HANADB=TMP_DBSYSTEMVALUES_HANADB,DBSYSTEMVALUES_INGRES=TMP_DBSYSTEMVALUES_INGRES,DBSYSTEMVALUES_FIRSTSQL=TMP_DBSYSTEMVALUES_FIRSTSQL,DBSYSTEMVALUES_CACHE=TMP_DBSYSTEMVALUES_CACHE,DBSYSTEMVALUES_ADABAS=TMP_DBSYSTEMVALUES_ADABAS,DBSYSTEMVALUES_FIREBIRD=TMP_DBSYSTEMVALUES_FIREBIRD,DBSYSTEMVALUES_DERBY=TMP_DBSYSTEMVALUES_DERBY,DBSYSTEMVALUES_FILEMAKER=TMP_DBSYSTEMVALUES_FILEMAKER,DBSYSTEMVALUES_INFORMIX=TMP_DBSYSTEMVALUES_INFORMIX,DBSYSTEMVALUES_INSTANTDB=TMP_DBSYSTEMVALUES_INSTANTDB,DBSYSTEMVALUES_INTERBASE=TMP_DBSYSTEMVALUES_INTERBASE,DBSYSTEMVALUES_MARIADB=TMP_DBSYSTEMVALUES_MARIADB,DBSYSTEMVALUES_NETEZZA=TMP_DBSYSTEMVALUES_NETEZZA,DBSYSTEMVALUES_PERVASIVE=TMP_DBSYSTEMVALUES_PERVASIVE,DBSYSTEMVALUES_POINTBASE=TMP_DBSYSTEMVALUES_POINTBASE,DBSYSTEMVALUES_SQLITE=TMP_DBSYSTEMVALUES_SQLITE,DBSYSTEMVALUES_SYBASE=TMP_DBSYSTEMVALUES_SYBASE,DBSYSTEMVALUES_TERADATA=TMP_DBSYSTEMVALUES_TERADATA,DBSYSTEMVALUES_VERTICA=TMP_DBSYSTEMVALUES_VERTICA,DBSYSTEMVALUES_COLDFUSION=TMP_DBSYSTEMVALUES_COLDFUSION,DBSYSTEMVALUES_CASSANDRA=TMP_DBSYSTEMVALUES_CASSANDRA,DBSYSTEMVALUES_HBASE=TMP_DBSYSTEMVALUES_HBASE,DBSYSTEMVALUES_MONGODB=TMP_DBSYSTEMVALUES_MONGODB,DBSYSTEMVALUES_REDIS=TMP_DBSYSTEMVALUES_REDIS,DBSYSTEMVALUES_COUCHBASE=TMP_DBSYSTEMVALUES_COUCHBASE,DBSYSTEMVALUES_COUCHDB=TMP_DBSYSTEMVALUES_COUCHDB,DBSYSTEMVALUES_COSMOSDB=TMP_DBSYSTEMVALUES_COSMOSDB,DBSYSTEMVALUES_DYNAMODB=TMP_DBSYSTEMVALUES_DYNAMODB,DBSYSTEMVALUES_NEO4J=TMP_DBSYSTEMVALUES_NEO4J,DBSYSTEMVALUES_GEODE=TMP_DBSYSTEMVALUES_GEODE,DBSYSTEMVALUES_ELASTICSEARCH=TMP_DBSYSTEMVALUES_ELASTICSEARCH,DBSYSTEMVALUES_MEMCACHED=TMP_DBSYSTEMVALUES_MEMCACHED,DBSYSTEMVALUES_COCKROACHDB=TMP_DBSYSTEMVALUES_COCKROACHDB,DbSystemValues=createConstMap([TMP_DBSYSTEMVALUES_OTHER_SQL,TMP_DBSYSTEMVALUES_MSSQL,TMP_DBSYSTEMVALUES_MYSQL,TMP_DBSYSTEMVALUES_ORACLE,TMP_DBSYSTEMVALUES_DB2,TMP_DBSYSTEMVALUES_POSTGRESQL,TMP_DBSYSTEMVALUES_REDSHIFT,TMP_DBSYSTEMVALUES_HIVE,TMP_DBSYSTEMVALUES_CLOUDSCAPE,TMP_DBSYSTEMVALUES_HSQLDB,TMP_DBSYSTEMVALUES_PROGRESS,TMP_DBSYSTEMVALUES_MAXDB,TMP_DBSYSTEMVALUES_HANADB,TMP_DBSYSTEMVALUES_INGRES,TMP_DBSYSTEMVALUES_FIRSTSQL,TMP_DBSYSTEMVALUES_EDB,TMP_DBSYSTEMVALUES_CACHE,TMP_DBSYSTEMVALUES_ADABAS,TMP_DBSYSTEMVALUES_FIREBIRD,TMP_DBSYSTEMVALUES_DERBY,TMP_DBSYSTEMVALUES_FILEMAKER,TMP_DBSYSTEMVALUES_INFORMIX,TMP_DBSYSTEMVALUES_INSTANTDB,TMP_DBSYSTEMVALUES_INTERBASE,TMP_DBSYSTEMVALUES_MARIADB,TMP_DBSYSTEMVALUES_NETEZZA,TMP_DBSYSTEMVALUES_PERVASIVE,TMP_DBSYSTEMVALUES_POINTBASE,TMP_DBSYSTEMVALUES_SQLITE,TMP_DBSYSTEMVALUES_SYBASE,TMP_DBSYSTEMVALUES_TERADATA,TMP_DBSYSTEMVALUES_VERTICA,TMP_DBSYSTEMVALUES_H2,TMP_DBSYSTEMVALUES_COLDFUSION,TMP_DBSYSTEMVALUES_CASSANDRA,TMP_DBSYSTEMVALUES_HBASE,TMP_DBSYSTEMVALUES_MONGODB,TMP_DBSYSTEMVALUES_REDIS,TMP_DBSYSTEMVALUES_COUCHBASE,TMP_DBSYSTEMVALUES_COUCHDB,TMP_DBSYSTEMVALUES_COSMOSDB,TMP_DBSYSTEMVALUES_DYNAMODB,TMP_DBSYSTEMVALUES_NEO4J,TMP_DBSYSTEMVALUES_GEODE,TMP_DBSYSTEMVALUES_ELASTICSEARCH,TMP_DBSYSTEMVALUES_MEMCACHED,TMP_DBSYSTEMVALUES_COCKROACHDB]),TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL=`all`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM=`each_quorum`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM=`quorum`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM=`local_quorum`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE=`one`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO=`two`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE=`three`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE=`local_one`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY=`any`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL=`serial`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL=`local_serial`,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_THREE=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DbCassandraConsistencyLevelValues=createConstMap([TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL]),TMP_FAASTRIGGERVALUES_DATASOURCE=`datasource`,TMP_FAASTRIGGERVALUES_HTTP=`http`,TMP_FAASTRIGGERVALUES_PUBSUB=`pubsub`,TMP_FAASTRIGGERVALUES_TIMER=`timer`,TMP_FAASTRIGGERVALUES_OTHER=`other`,FAASTRIGGERVALUES_DATASOURCE=TMP_FAASTRIGGERVALUES_DATASOURCE,FAASTRIGGERVALUES_HTTP=TMP_FAASTRIGGERVALUES_HTTP,FAASTRIGGERVALUES_PUBSUB=TMP_FAASTRIGGERVALUES_PUBSUB,FAASTRIGGERVALUES_TIMER=TMP_FAASTRIGGERVALUES_TIMER,FAASTRIGGERVALUES_OTHER=TMP_FAASTRIGGERVALUES_OTHER,FaasTriggerValues=createConstMap([TMP_FAASTRIGGERVALUES_DATASOURCE,TMP_FAASTRIGGERVALUES_HTTP,TMP_FAASTRIGGERVALUES_PUBSUB,TMP_FAASTRIGGERVALUES_TIMER,TMP_FAASTRIGGERVALUES_OTHER]),TMP_FAASDOCUMENTOPERATIONVALUES_INSERT=`insert`,TMP_FAASDOCUMENTOPERATIONVALUES_EDIT=`edit`,TMP_FAASDOCUMENTOPERATIONVALUES_DELETE=`delete`,FAASDOCUMENTOPERATIONVALUES_INSERT=TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,FAASDOCUMENTOPERATIONVALUES_EDIT=TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,FAASDOCUMENTOPERATIONVALUES_DELETE=TMP_FAASDOCUMENTOPERATIONVALUES_DELETE,FaasDocumentOperationValues=createConstMap([TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,TMP_FAASDOCUMENTOPERATIONVALUES_DELETE]),TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD=`alibaba_cloud`,TMP_FAASINVOKEDPROVIDERVALUES_AWS=`aws`,TMP_FAASINVOKEDPROVIDERVALUES_AZURE=`azure`,TMP_FAASINVOKEDPROVIDERVALUES_GCP=`gcp`,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD=TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,FAASINVOKEDPROVIDERVALUES_AZURE=TMP_FAASINVOKEDPROVIDERVALUES_AZURE,FaasInvokedProviderValues=createConstMap([TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,TMP_FAASINVOKEDPROVIDERVALUES_AWS,TMP_FAASINVOKEDPROVIDERVALUES_AZURE,TMP_FAASINVOKEDPROVIDERVALUES_GCP]),TMP_NETTRANSPORTVALUES_IP_TCP=`ip_tcp`,TMP_NETTRANSPORTVALUES_IP_UDP=`ip_udp`,TMP_NETTRANSPORTVALUES_IP=`ip`,TMP_NETTRANSPORTVALUES_UNIX=`unix`,TMP_NETTRANSPORTVALUES_PIPE=`pipe`,TMP_NETTRANSPORTVALUES_INPROC=`inproc`,TMP_NETTRANSPORTVALUES_OTHER=`other`,NETTRANSPORTVALUES_IP_TCP=TMP_NETTRANSPORTVALUES_IP_TCP,NETTRANSPORTVALUES_IP_UDP=TMP_NETTRANSPORTVALUES_IP_UDP,NETTRANSPORTVALUES_UNIX=TMP_NETTRANSPORTVALUES_UNIX,NETTRANSPORTVALUES_PIPE=TMP_NETTRANSPORTVALUES_PIPE,NETTRANSPORTVALUES_INPROC=TMP_NETTRANSPORTVALUES_INPROC,NETTRANSPORTVALUES_OTHER=TMP_NETTRANSPORTVALUES_OTHER,NetTransportValues=createConstMap([TMP_NETTRANSPORTVALUES_IP_TCP,TMP_NETTRANSPORTVALUES_IP_UDP,TMP_NETTRANSPORTVALUES_IP,TMP_NETTRANSPORTVALUES_UNIX,TMP_NETTRANSPORTVALUES_PIPE,TMP_NETTRANSPORTVALUES_INPROC,TMP_NETTRANSPORTVALUES_OTHER]),TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI=`wifi`,TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED=`wired`,TMP_NETHOSTCONNECTIONTYPEVALUES_CELL=`cell`,TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE=`unavailable`,TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN=`unknown`,NETHOSTCONNECTIONTYPEVALUES_WIFI=TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,NETHOSTCONNECTIONTYPEVALUES_WIRED=TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,NETHOSTCONNECTIONTYPEVALUES_CELL=TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE=TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN=TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NetHostConnectionTypeValues=createConstMap([TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN]),TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS=`gprs`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE=`edge`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS=`umts`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA=`cdma`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0=`evdo_0`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A=`evdo_a`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT=`cdma2000_1xrtt`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA=`hsdpa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA=`hsupa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA=`hspa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN=`iden`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B=`evdo_b`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE=`lte`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD=`ehrpd`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP=`hspap`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM=`gsm`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA=`td_scdma`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN=`iwlan`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR=`nr`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA=`nrnsa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA=`lte_ca`,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NetHostConnectionSubtypeValues=createConstMap([TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA]),TMP_HTTPFLAVORVALUES_HTTP_1_0=`1.0`,TMP_HTTPFLAVORVALUES_HTTP_1_1=`1.1`,TMP_HTTPFLAVORVALUES_HTTP_2_0=`2.0`,TMP_HTTPFLAVORVALUES_SPDY=`SPDY`,TMP_HTTPFLAVORVALUES_QUIC=`QUIC`,HTTPFLAVORVALUES_SPDY=TMP_HTTPFLAVORVALUES_SPDY,HTTPFLAVORVALUES_QUIC=TMP_HTTPFLAVORVALUES_QUIC,HttpFlavorValues={HTTP_1_0:TMP_HTTPFLAVORVALUES_HTTP_1_0,HTTP_1_1:TMP_HTTPFLAVORVALUES_HTTP_1_1,HTTP_2_0:TMP_HTTPFLAVORVALUES_HTTP_2_0,SPDY:TMP_HTTPFLAVORVALUES_SPDY,QUIC:TMP_HTTPFLAVORVALUES_QUIC},TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE=`queue`,TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC=`topic`,MESSAGINGDESTINATIONKINDVALUES_QUEUE=TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,MESSAGINGDESTINATIONKINDVALUES_TOPIC=TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC,MessagingDestinationKindValues=createConstMap([TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC]),TMP_MESSAGINGOPERATIONVALUES_RECEIVE=`receive`,TMP_MESSAGINGOPERATIONVALUES_PROCESS=`process`,MESSAGINGOPERATIONVALUES_RECEIVE=TMP_MESSAGINGOPERATIONVALUES_RECEIVE,MESSAGINGOPERATIONVALUES_PROCESS=TMP_MESSAGINGOPERATIONVALUES_PROCESS,MessagingOperationValues=createConstMap([TMP_MESSAGINGOPERATIONVALUES_RECEIVE,TMP_MESSAGINGOPERATIONVALUES_PROCESS]),TMP_RPCGRPCSTATUSCODEVALUES_OK=0,TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED=1,TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN=2,TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT=3,TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED=4,TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND=5,TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS=6,TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED=7,TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED=8,TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION=9,TMP_RPCGRPCSTATUSCODEVALUES_ABORTED=10,TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE=11,TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED=12,TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL=13,TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE=14,TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS=15,TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED=16,RpcGrpcStatusCodeValues={OK:TMP_RPCGRPCSTATUSCODEVALUES_OK,CANCELLED:TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED,UNKNOWN:TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN,INVALID_ARGUMENT:TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,DEADLINE_EXCEEDED:TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,NOT_FOUND:TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND,ALREADY_EXISTS:TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,PERMISSION_DENIED:TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,RESOURCE_EXHAUSTED:TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,FAILED_PRECONDITION:TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,ABORTED:TMP_RPCGRPCSTATUSCODEVALUES_ABORTED,OUT_OF_RANGE:TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,UNIMPLEMENTED:TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,INTERNAL:TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL,UNAVAILABLE:TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,DATA_LOSS:TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS,UNAUTHENTICATED:TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED},TMP_MESSAGETYPEVALUES_SENT=`SENT`,TMP_MESSAGETYPEVALUES_RECEIVED=`RECEIVED`,MESSAGETYPEVALUES_SENT=TMP_MESSAGETYPEVALUES_SENT,MESSAGETYPEVALUES_RECEIVED=TMP_MESSAGETYPEVALUES_RECEIVED,MessageTypeValues=createConstMap([TMP_MESSAGETYPEVALUES_SENT,TMP_MESSAGETYPEVALUES_RECEIVED])})),init_trace=__esmMin((()=>{init_SemanticAttributes()})),TMP_CLOUD_PROVIDER,TMP_CLOUD_ACCOUNT_ID,TMP_CLOUD_REGION,TMP_CLOUD_AVAILABILITY_ZONE,TMP_CLOUD_PLATFORM,TMP_AWS_ECS_CONTAINER_ARN,TMP_AWS_ECS_CLUSTER_ARN,TMP_AWS_ECS_LAUNCHTYPE,TMP_AWS_ECS_TASK_ARN,TMP_AWS_ECS_TASK_FAMILY,TMP_AWS_ECS_TASK_REVISION,TMP_AWS_EKS_CLUSTER_ARN,TMP_AWS_LOG_GROUP_NAMES,TMP_AWS_LOG_GROUP_ARNS,TMP_AWS_LOG_STREAM_NAMES,TMP_AWS_LOG_STREAM_ARNS,TMP_CONTAINER_NAME,TMP_CONTAINER_ID,TMP_CONTAINER_RUNTIME,TMP_CONTAINER_IMAGE_NAME,TMP_CONTAINER_IMAGE_TAG,TMP_DEPLOYMENT_ENVIRONMENT,TMP_DEVICE_ID,TMP_DEVICE_MODEL_IDENTIFIER,TMP_DEVICE_MODEL_NAME,TMP_FAAS_NAME,TMP_FAAS_ID,TMP_FAAS_VERSION,TMP_FAAS_INSTANCE,TMP_FAAS_MAX_MEMORY,TMP_HOST_ID,TMP_HOST_NAME,TMP_HOST_TYPE,TMP_HOST_ARCH,TMP_HOST_IMAGE_NAME,TMP_HOST_IMAGE_ID,TMP_HOST_IMAGE_VERSION,TMP_K8S_CLUSTER_NAME,TMP_K8S_NODE_NAME,TMP_K8S_NODE_UID,TMP_K8S_NAMESPACE_NAME,TMP_K8S_POD_UID,TMP_K8S_POD_NAME,TMP_K8S_CONTAINER_NAME,TMP_K8S_REPLICASET_UID,TMP_K8S_REPLICASET_NAME,TMP_K8S_DEPLOYMENT_UID,TMP_K8S_DEPLOYMENT_NAME,TMP_K8S_STATEFULSET_UID,TMP_K8S_STATEFULSET_NAME,TMP_K8S_DAEMONSET_UID,TMP_K8S_DAEMONSET_NAME,TMP_K8S_JOB_UID,TMP_K8S_JOB_NAME,TMP_K8S_CRONJOB_UID,TMP_K8S_CRONJOB_NAME,TMP_OS_TYPE,TMP_OS_DESCRIPTION,TMP_OS_NAME,TMP_OS_VERSION,TMP_PROCESS_PID,TMP_PROCESS_EXECUTABLE_NAME,TMP_PROCESS_EXECUTABLE_PATH,TMP_PROCESS_COMMAND,TMP_PROCESS_COMMAND_LINE,TMP_PROCESS_COMMAND_ARGS,TMP_PROCESS_OWNER,TMP_PROCESS_RUNTIME_NAME,TMP_PROCESS_RUNTIME_VERSION,TMP_PROCESS_RUNTIME_DESCRIPTION,TMP_SERVICE_NAME,TMP_SERVICE_NAMESPACE,TMP_SERVICE_INSTANCE_ID,TMP_SERVICE_VERSION,TMP_TELEMETRY_SDK_NAME,TMP_TELEMETRY_SDK_LANGUAGE,TMP_TELEMETRY_SDK_VERSION,TMP_TELEMETRY_AUTO_VERSION,TMP_WEBENGINE_NAME,TMP_WEBENGINE_VERSION,TMP_WEBENGINE_DESCRIPTION,SEMRESATTRS_CLOUD_PROVIDER,SEMRESATTRS_CLOUD_ACCOUNT_ID,SEMRESATTRS_CLOUD_REGION,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE,SEMRESATTRS_CLOUD_PLATFORM,SEMRESATTRS_AWS_ECS_CONTAINER_ARN,SEMRESATTRS_AWS_ECS_CLUSTER_ARN,SEMRESATTRS_AWS_ECS_LAUNCHTYPE,SEMRESATTRS_AWS_ECS_TASK_ARN,SEMRESATTRS_AWS_ECS_TASK_FAMILY,SEMRESATTRS_AWS_ECS_TASK_REVISION,SEMRESATTRS_AWS_EKS_CLUSTER_ARN,SEMRESATTRS_AWS_LOG_GROUP_NAMES,SEMRESATTRS_AWS_LOG_GROUP_ARNS,SEMRESATTRS_AWS_LOG_STREAM_NAMES,SEMRESATTRS_AWS_LOG_STREAM_ARNS,SEMRESATTRS_CONTAINER_NAME,SEMRESATTRS_CONTAINER_ID,SEMRESATTRS_CONTAINER_RUNTIME,SEMRESATTRS_CONTAINER_IMAGE_NAME,SEMRESATTRS_CONTAINER_IMAGE_TAG,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,SEMRESATTRS_DEVICE_ID,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER,SEMRESATTRS_DEVICE_MODEL_NAME,SEMRESATTRS_FAAS_NAME,SEMRESATTRS_FAAS_ID,SEMRESATTRS_FAAS_VERSION,SEMRESATTRS_FAAS_INSTANCE,SEMRESATTRS_FAAS_MAX_MEMORY,SEMRESATTRS_HOST_ID,SEMRESATTRS_HOST_NAME,SEMRESATTRS_HOST_TYPE,SEMRESATTRS_HOST_ARCH,SEMRESATTRS_HOST_IMAGE_NAME,SEMRESATTRS_HOST_IMAGE_ID,SEMRESATTRS_HOST_IMAGE_VERSION,SEMRESATTRS_K8S_CLUSTER_NAME,SEMRESATTRS_K8S_NODE_NAME,SEMRESATTRS_K8S_NODE_UID,SEMRESATTRS_K8S_NAMESPACE_NAME,SEMRESATTRS_K8S_POD_UID,SEMRESATTRS_K8S_POD_NAME,SEMRESATTRS_K8S_CONTAINER_NAME,SEMRESATTRS_K8S_REPLICASET_UID,SEMRESATTRS_K8S_REPLICASET_NAME,SEMRESATTRS_K8S_DEPLOYMENT_UID,SEMRESATTRS_K8S_DEPLOYMENT_NAME,SEMRESATTRS_K8S_STATEFULSET_UID,SEMRESATTRS_K8S_STATEFULSET_NAME,SEMRESATTRS_K8S_DAEMONSET_UID,SEMRESATTRS_K8S_DAEMONSET_NAME,SEMRESATTRS_K8S_JOB_UID,SEMRESATTRS_K8S_JOB_NAME,SEMRESATTRS_K8S_CRONJOB_UID,SEMRESATTRS_K8S_CRONJOB_NAME,SEMRESATTRS_OS_TYPE,SEMRESATTRS_OS_DESCRIPTION,SEMRESATTRS_OS_NAME,SEMRESATTRS_OS_VERSION,SEMRESATTRS_PROCESS_PID,SEMRESATTRS_PROCESS_EXECUTABLE_NAME,SEMRESATTRS_PROCESS_EXECUTABLE_PATH,SEMRESATTRS_PROCESS_COMMAND,SEMRESATTRS_PROCESS_COMMAND_LINE,SEMRESATTRS_PROCESS_COMMAND_ARGS,SEMRESATTRS_PROCESS_OWNER,SEMRESATTRS_PROCESS_RUNTIME_NAME,SEMRESATTRS_PROCESS_RUNTIME_VERSION,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION,SEMRESATTRS_SERVICE_NAME,SEMRESATTRS_SERVICE_NAMESPACE,SEMRESATTRS_SERVICE_INSTANCE_ID,SEMRESATTRS_SERVICE_VERSION,SEMRESATTRS_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_VERSION,SEMRESATTRS_TELEMETRY_AUTO_VERSION,SEMRESATTRS_WEBENGINE_NAME,SEMRESATTRS_WEBENGINE_VERSION,SEMRESATTRS_WEBENGINE_DESCRIPTION,SemanticResourceAttributes,TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,TMP_CLOUDPROVIDERVALUES_AWS,TMP_CLOUDPROVIDERVALUES_AZURE,TMP_CLOUDPROVIDERVALUES_GCP,CLOUDPROVIDERVALUES_ALIBABA_CLOUD,CLOUDPROVIDERVALUES_AWS,CLOUDPROVIDERVALUES_AZURE,CLOUDPROVIDERVALUES_GCP,CloudProviderValues,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,TMP_CLOUDPLATFORMVALUES_AWS_EC2,TMP_CLOUDPLATFORMVALUES_AWS_ECS,TMP_CLOUDPLATFORMVALUES_AWS_EKS,TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,TMP_CLOUDPLATFORMVALUES_AZURE_VM,TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,TMP_CLOUDPLATFORMVALUES_AZURE_AKS,TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,CLOUDPLATFORMVALUES_AWS_EC2,CLOUDPLATFORMVALUES_AWS_ECS,CLOUDPLATFORMVALUES_AWS_EKS,CLOUDPLATFORMVALUES_AWS_LAMBDA,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,CLOUDPLATFORMVALUES_AZURE_VM,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,CLOUDPLATFORMVALUES_AZURE_AKS,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CloudPlatformValues,TMP_AWSECSLAUNCHTYPEVALUES_EC2,TMP_AWSECSLAUNCHTYPEVALUES_FARGATE,AWSECSLAUNCHTYPEVALUES_EC2,AWSECSLAUNCHTYPEVALUES_FARGATE,AwsEcsLaunchtypeValues,TMP_HOSTARCHVALUES_AMD64,TMP_HOSTARCHVALUES_ARM32,TMP_HOSTARCHVALUES_ARM64,TMP_HOSTARCHVALUES_IA64,TMP_HOSTARCHVALUES_PPC32,TMP_HOSTARCHVALUES_PPC64,TMP_HOSTARCHVALUES_X86,HOSTARCHVALUES_AMD64,HOSTARCHVALUES_ARM32,HOSTARCHVALUES_ARM64,HOSTARCHVALUES_IA64,HOSTARCHVALUES_PPC32,HOSTARCHVALUES_PPC64,HOSTARCHVALUES_X86,HostArchValues,TMP_OSTYPEVALUES_WINDOWS,TMP_OSTYPEVALUES_LINUX,TMP_OSTYPEVALUES_DARWIN,TMP_OSTYPEVALUES_FREEBSD,TMP_OSTYPEVALUES_NETBSD,TMP_OSTYPEVALUES_OPENBSD,TMP_OSTYPEVALUES_DRAGONFLYBSD,TMP_OSTYPEVALUES_HPUX,TMP_OSTYPEVALUES_AIX,TMP_OSTYPEVALUES_SOLARIS,TMP_OSTYPEVALUES_Z_OS,OSTYPEVALUES_WINDOWS,OSTYPEVALUES_LINUX,OSTYPEVALUES_DARWIN,OSTYPEVALUES_FREEBSD,OSTYPEVALUES_NETBSD,OSTYPEVALUES_OPENBSD,OSTYPEVALUES_DRAGONFLYBSD,OSTYPEVALUES_HPUX,OSTYPEVALUES_AIX,OSTYPEVALUES_SOLARIS,OSTYPEVALUES_Z_OS,OsTypeValues,TMP_TELEMETRYSDKLANGUAGEVALUES_CPP,TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,TMP_TELEMETRYSDKLANGUAGEVALUES_GO,TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,TMP_TELEMETRYSDKLANGUAGEVALUES_PHP,TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,TELEMETRYSDKLANGUAGEVALUES_CPP,TELEMETRYSDKLANGUAGEVALUES_DOTNET,TELEMETRYSDKLANGUAGEVALUES_ERLANG,TELEMETRYSDKLANGUAGEVALUES_GO,TELEMETRYSDKLANGUAGEVALUES_JAVA,TELEMETRYSDKLANGUAGEVALUES_NODEJS,TELEMETRYSDKLANGUAGEVALUES_PHP,TELEMETRYSDKLANGUAGEVALUES_PYTHON,TELEMETRYSDKLANGUAGEVALUES_RUBY,TELEMETRYSDKLANGUAGEVALUES_WEBJS,TelemetrySdkLanguageValues,init_SemanticResourceAttributes=__esmMin((()=>{init_utils(),TMP_CLOUD_PROVIDER=`cloud.provider`,TMP_CLOUD_ACCOUNT_ID=`cloud.account.id`,TMP_CLOUD_REGION=`cloud.region`,TMP_CLOUD_AVAILABILITY_ZONE=`cloud.availability_zone`,TMP_CLOUD_PLATFORM=`cloud.platform`,TMP_AWS_ECS_CONTAINER_ARN=`aws.ecs.container.arn`,TMP_AWS_ECS_CLUSTER_ARN=`aws.ecs.cluster.arn`,TMP_AWS_ECS_LAUNCHTYPE=`aws.ecs.launchtype`,TMP_AWS_ECS_TASK_ARN=`aws.ecs.task.arn`,TMP_AWS_ECS_TASK_FAMILY=`aws.ecs.task.family`,TMP_AWS_ECS_TASK_REVISION=`aws.ecs.task.revision`,TMP_AWS_EKS_CLUSTER_ARN=`aws.eks.cluster.arn`,TMP_AWS_LOG_GROUP_NAMES=`aws.log.group.names`,TMP_AWS_LOG_GROUP_ARNS=`aws.log.group.arns`,TMP_AWS_LOG_STREAM_NAMES=`aws.log.stream.names`,TMP_AWS_LOG_STREAM_ARNS=`aws.log.stream.arns`,TMP_CONTAINER_NAME=`container.name`,TMP_CONTAINER_ID=`container.id`,TMP_CONTAINER_RUNTIME=`container.runtime`,TMP_CONTAINER_IMAGE_NAME=`container.image.name`,TMP_CONTAINER_IMAGE_TAG=`container.image.tag`,TMP_DEPLOYMENT_ENVIRONMENT=`deployment.environment`,TMP_DEVICE_ID=`device.id`,TMP_DEVICE_MODEL_IDENTIFIER=`device.model.identifier`,TMP_DEVICE_MODEL_NAME=`device.model.name`,TMP_FAAS_NAME=`faas.name`,TMP_FAAS_ID=`faas.id`,TMP_FAAS_VERSION=`faas.version`,TMP_FAAS_INSTANCE=`faas.instance`,TMP_FAAS_MAX_MEMORY=`faas.max_memory`,TMP_HOST_ID=`host.id`,TMP_HOST_NAME=`host.name`,TMP_HOST_TYPE=`host.type`,TMP_HOST_ARCH=`host.arch`,TMP_HOST_IMAGE_NAME=`host.image.name`,TMP_HOST_IMAGE_ID=`host.image.id`,TMP_HOST_IMAGE_VERSION=`host.image.version`,TMP_K8S_CLUSTER_NAME=`k8s.cluster.name`,TMP_K8S_NODE_NAME=`k8s.node.name`,TMP_K8S_NODE_UID=`k8s.node.uid`,TMP_K8S_NAMESPACE_NAME=`k8s.namespace.name`,TMP_K8S_POD_UID=`k8s.pod.uid`,TMP_K8S_POD_NAME=`k8s.pod.name`,TMP_K8S_CONTAINER_NAME=`k8s.container.name`,TMP_K8S_REPLICASET_UID=`k8s.replicaset.uid`,TMP_K8S_REPLICASET_NAME=`k8s.replicaset.name`,TMP_K8S_DEPLOYMENT_UID=`k8s.deployment.uid`,TMP_K8S_DEPLOYMENT_NAME=`k8s.deployment.name`,TMP_K8S_STATEFULSET_UID=`k8s.statefulset.uid`,TMP_K8S_STATEFULSET_NAME=`k8s.statefulset.name`,TMP_K8S_DAEMONSET_UID=`k8s.daemonset.uid`,TMP_K8S_DAEMONSET_NAME=`k8s.daemonset.name`,TMP_K8S_JOB_UID=`k8s.job.uid`,TMP_K8S_JOB_NAME=`k8s.job.name`,TMP_K8S_CRONJOB_UID=`k8s.cronjob.uid`,TMP_K8S_CRONJOB_NAME=`k8s.cronjob.name`,TMP_OS_TYPE=`os.type`,TMP_OS_DESCRIPTION=`os.description`,TMP_OS_NAME=`os.name`,TMP_OS_VERSION=`os.version`,TMP_PROCESS_PID=`process.pid`,TMP_PROCESS_EXECUTABLE_NAME=`process.executable.name`,TMP_PROCESS_EXECUTABLE_PATH=`process.executable.path`,TMP_PROCESS_COMMAND=`process.command`,TMP_PROCESS_COMMAND_LINE=`process.command_line`,TMP_PROCESS_COMMAND_ARGS=`process.command_args`,TMP_PROCESS_OWNER=`process.owner`,TMP_PROCESS_RUNTIME_NAME=`process.runtime.name`,TMP_PROCESS_RUNTIME_VERSION=`process.runtime.version`,TMP_PROCESS_RUNTIME_DESCRIPTION=`process.runtime.description`,TMP_SERVICE_NAME=`service.name`,TMP_SERVICE_NAMESPACE=`service.namespace`,TMP_SERVICE_INSTANCE_ID=`service.instance.id`,TMP_SERVICE_VERSION=`service.version`,TMP_TELEMETRY_SDK_NAME=`telemetry.sdk.name`,TMP_TELEMETRY_SDK_LANGUAGE=`telemetry.sdk.language`,TMP_TELEMETRY_SDK_VERSION=`telemetry.sdk.version`,TMP_TELEMETRY_AUTO_VERSION=`telemetry.auto.version`,TMP_WEBENGINE_NAME=`webengine.name`,TMP_WEBENGINE_VERSION=`webengine.version`,TMP_WEBENGINE_DESCRIPTION=`webengine.description`,SEMRESATTRS_CLOUD_PROVIDER=TMP_CLOUD_PROVIDER,SEMRESATTRS_CLOUD_ACCOUNT_ID=TMP_CLOUD_ACCOUNT_ID,SEMRESATTRS_CLOUD_REGION=TMP_CLOUD_REGION,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE=TMP_CLOUD_AVAILABILITY_ZONE,SEMRESATTRS_CLOUD_PLATFORM=TMP_CLOUD_PLATFORM,SEMRESATTRS_AWS_ECS_CONTAINER_ARN=TMP_AWS_ECS_CONTAINER_ARN,SEMRESATTRS_AWS_ECS_CLUSTER_ARN=TMP_AWS_ECS_CLUSTER_ARN,SEMRESATTRS_AWS_ECS_LAUNCHTYPE=TMP_AWS_ECS_LAUNCHTYPE,SEMRESATTRS_AWS_ECS_TASK_ARN=TMP_AWS_ECS_TASK_ARN,SEMRESATTRS_AWS_ECS_TASK_FAMILY=TMP_AWS_ECS_TASK_FAMILY,SEMRESATTRS_AWS_ECS_TASK_REVISION=TMP_AWS_ECS_TASK_REVISION,SEMRESATTRS_AWS_EKS_CLUSTER_ARN=TMP_AWS_EKS_CLUSTER_ARN,SEMRESATTRS_AWS_LOG_GROUP_NAMES=TMP_AWS_LOG_GROUP_NAMES,SEMRESATTRS_AWS_LOG_GROUP_ARNS=TMP_AWS_LOG_GROUP_ARNS,SEMRESATTRS_AWS_LOG_STREAM_NAMES=TMP_AWS_LOG_STREAM_NAMES,SEMRESATTRS_AWS_LOG_STREAM_ARNS=TMP_AWS_LOG_STREAM_ARNS,SEMRESATTRS_CONTAINER_NAME=TMP_CONTAINER_NAME,SEMRESATTRS_CONTAINER_ID=TMP_CONTAINER_ID,SEMRESATTRS_CONTAINER_RUNTIME=TMP_CONTAINER_RUNTIME,SEMRESATTRS_CONTAINER_IMAGE_NAME=TMP_CONTAINER_IMAGE_NAME,SEMRESATTRS_CONTAINER_IMAGE_TAG=TMP_CONTAINER_IMAGE_TAG,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT=TMP_DEPLOYMENT_ENVIRONMENT,SEMRESATTRS_DEVICE_ID=TMP_DEVICE_ID,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER=TMP_DEVICE_MODEL_IDENTIFIER,SEMRESATTRS_DEVICE_MODEL_NAME=TMP_DEVICE_MODEL_NAME,SEMRESATTRS_FAAS_NAME=TMP_FAAS_NAME,SEMRESATTRS_FAAS_ID=TMP_FAAS_ID,SEMRESATTRS_FAAS_VERSION=TMP_FAAS_VERSION,SEMRESATTRS_FAAS_INSTANCE=TMP_FAAS_INSTANCE,SEMRESATTRS_FAAS_MAX_MEMORY=TMP_FAAS_MAX_MEMORY,SEMRESATTRS_HOST_ID=TMP_HOST_ID,SEMRESATTRS_HOST_NAME=TMP_HOST_NAME,SEMRESATTRS_HOST_TYPE=TMP_HOST_TYPE,SEMRESATTRS_HOST_ARCH=TMP_HOST_ARCH,SEMRESATTRS_HOST_IMAGE_NAME=TMP_HOST_IMAGE_NAME,SEMRESATTRS_HOST_IMAGE_ID=TMP_HOST_IMAGE_ID,SEMRESATTRS_HOST_IMAGE_VERSION=TMP_HOST_IMAGE_VERSION,SEMRESATTRS_K8S_CLUSTER_NAME=TMP_K8S_CLUSTER_NAME,SEMRESATTRS_K8S_NODE_NAME=TMP_K8S_NODE_NAME,SEMRESATTRS_K8S_NODE_UID=TMP_K8S_NODE_UID,SEMRESATTRS_K8S_NAMESPACE_NAME=TMP_K8S_NAMESPACE_NAME,SEMRESATTRS_K8S_POD_UID=TMP_K8S_POD_UID,SEMRESATTRS_K8S_POD_NAME=TMP_K8S_POD_NAME,SEMRESATTRS_K8S_CONTAINER_NAME=TMP_K8S_CONTAINER_NAME,SEMRESATTRS_K8S_REPLICASET_UID=TMP_K8S_REPLICASET_UID,SEMRESATTRS_K8S_REPLICASET_NAME=TMP_K8S_REPLICASET_NAME,SEMRESATTRS_K8S_DEPLOYMENT_UID=TMP_K8S_DEPLOYMENT_UID,SEMRESATTRS_K8S_DEPLOYMENT_NAME=TMP_K8S_DEPLOYMENT_NAME,SEMRESATTRS_K8S_STATEFULSET_UID=TMP_K8S_STATEFULSET_UID,SEMRESATTRS_K8S_STATEFULSET_NAME=TMP_K8S_STATEFULSET_NAME,SEMRESATTRS_K8S_DAEMONSET_UID=TMP_K8S_DAEMONSET_UID,SEMRESATTRS_K8S_DAEMONSET_NAME=TMP_K8S_DAEMONSET_NAME,SEMRESATTRS_K8S_JOB_UID=TMP_K8S_JOB_UID,SEMRESATTRS_K8S_JOB_NAME=TMP_K8S_JOB_NAME,SEMRESATTRS_K8S_CRONJOB_UID=TMP_K8S_CRONJOB_UID,SEMRESATTRS_K8S_CRONJOB_NAME=TMP_K8S_CRONJOB_NAME,SEMRESATTRS_OS_TYPE=TMP_OS_TYPE,SEMRESATTRS_OS_DESCRIPTION=TMP_OS_DESCRIPTION,SEMRESATTRS_OS_NAME=TMP_OS_NAME,SEMRESATTRS_OS_VERSION=TMP_OS_VERSION,SEMRESATTRS_PROCESS_PID=TMP_PROCESS_PID,SEMRESATTRS_PROCESS_EXECUTABLE_NAME=TMP_PROCESS_EXECUTABLE_NAME,SEMRESATTRS_PROCESS_EXECUTABLE_PATH=TMP_PROCESS_EXECUTABLE_PATH,SEMRESATTRS_PROCESS_COMMAND=TMP_PROCESS_COMMAND,SEMRESATTRS_PROCESS_COMMAND_LINE=TMP_PROCESS_COMMAND_LINE,SEMRESATTRS_PROCESS_COMMAND_ARGS=TMP_PROCESS_COMMAND_ARGS,SEMRESATTRS_PROCESS_OWNER=TMP_PROCESS_OWNER,SEMRESATTRS_PROCESS_RUNTIME_NAME=TMP_PROCESS_RUNTIME_NAME,SEMRESATTRS_PROCESS_RUNTIME_VERSION=TMP_PROCESS_RUNTIME_VERSION,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION=TMP_PROCESS_RUNTIME_DESCRIPTION,SEMRESATTRS_SERVICE_NAME=TMP_SERVICE_NAME,SEMRESATTRS_SERVICE_NAMESPACE=TMP_SERVICE_NAMESPACE,SEMRESATTRS_SERVICE_INSTANCE_ID=TMP_SERVICE_INSTANCE_ID,SEMRESATTRS_SERVICE_VERSION=TMP_SERVICE_VERSION,SEMRESATTRS_TELEMETRY_SDK_NAME=TMP_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE=TMP_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_VERSION=TMP_TELEMETRY_SDK_VERSION,SEMRESATTRS_TELEMETRY_AUTO_VERSION=TMP_TELEMETRY_AUTO_VERSION,SEMRESATTRS_WEBENGINE_NAME=TMP_WEBENGINE_NAME,SEMRESATTRS_WEBENGINE_VERSION=TMP_WEBENGINE_VERSION,SEMRESATTRS_WEBENGINE_DESCRIPTION=TMP_WEBENGINE_DESCRIPTION,SemanticResourceAttributes=createConstMap([TMP_CLOUD_PROVIDER,TMP_CLOUD_ACCOUNT_ID,TMP_CLOUD_REGION,TMP_CLOUD_AVAILABILITY_ZONE,TMP_CLOUD_PLATFORM,TMP_AWS_ECS_CONTAINER_ARN,TMP_AWS_ECS_CLUSTER_ARN,TMP_AWS_ECS_LAUNCHTYPE,TMP_AWS_ECS_TASK_ARN,TMP_AWS_ECS_TASK_FAMILY,TMP_AWS_ECS_TASK_REVISION,TMP_AWS_EKS_CLUSTER_ARN,TMP_AWS_LOG_GROUP_NAMES,TMP_AWS_LOG_GROUP_ARNS,TMP_AWS_LOG_STREAM_NAMES,TMP_AWS_LOG_STREAM_ARNS,TMP_CONTAINER_NAME,TMP_CONTAINER_ID,TMP_CONTAINER_RUNTIME,TMP_CONTAINER_IMAGE_NAME,TMP_CONTAINER_IMAGE_TAG,TMP_DEPLOYMENT_ENVIRONMENT,TMP_DEVICE_ID,TMP_DEVICE_MODEL_IDENTIFIER,TMP_DEVICE_MODEL_NAME,TMP_FAAS_NAME,TMP_FAAS_ID,TMP_FAAS_VERSION,TMP_FAAS_INSTANCE,TMP_FAAS_MAX_MEMORY,TMP_HOST_ID,TMP_HOST_NAME,TMP_HOST_TYPE,TMP_HOST_ARCH,TMP_HOST_IMAGE_NAME,TMP_HOST_IMAGE_ID,TMP_HOST_IMAGE_VERSION,TMP_K8S_CLUSTER_NAME,TMP_K8S_NODE_NAME,TMP_K8S_NODE_UID,TMP_K8S_NAMESPACE_NAME,TMP_K8S_POD_UID,TMP_K8S_POD_NAME,TMP_K8S_CONTAINER_NAME,TMP_K8S_REPLICASET_UID,TMP_K8S_REPLICASET_NAME,TMP_K8S_DEPLOYMENT_UID,TMP_K8S_DEPLOYMENT_NAME,TMP_K8S_STATEFULSET_UID,TMP_K8S_STATEFULSET_NAME,TMP_K8S_DAEMONSET_UID,TMP_K8S_DAEMONSET_NAME,TMP_K8S_JOB_UID,TMP_K8S_JOB_NAME,TMP_K8S_CRONJOB_UID,TMP_K8S_CRONJOB_NAME,TMP_OS_TYPE,TMP_OS_DESCRIPTION,TMP_OS_NAME,TMP_OS_VERSION,TMP_PROCESS_PID,TMP_PROCESS_EXECUTABLE_NAME,TMP_PROCESS_EXECUTABLE_PATH,TMP_PROCESS_COMMAND,TMP_PROCESS_COMMAND_LINE,TMP_PROCESS_COMMAND_ARGS,TMP_PROCESS_OWNER,TMP_PROCESS_RUNTIME_NAME,TMP_PROCESS_RUNTIME_VERSION,TMP_PROCESS_RUNTIME_DESCRIPTION,TMP_SERVICE_NAME,TMP_SERVICE_NAMESPACE,TMP_SERVICE_INSTANCE_ID,TMP_SERVICE_VERSION,TMP_TELEMETRY_SDK_NAME,TMP_TELEMETRY_SDK_LANGUAGE,TMP_TELEMETRY_SDK_VERSION,TMP_TELEMETRY_AUTO_VERSION,TMP_WEBENGINE_NAME,TMP_WEBENGINE_VERSION,TMP_WEBENGINE_DESCRIPTION]),TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD=`alibaba_cloud`,TMP_CLOUDPROVIDERVALUES_AWS=`aws`,TMP_CLOUDPROVIDERVALUES_AZURE=`azure`,TMP_CLOUDPROVIDERVALUES_GCP=`gcp`,CLOUDPROVIDERVALUES_ALIBABA_CLOUD=TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,CLOUDPROVIDERVALUES_AZURE=TMP_CLOUDPROVIDERVALUES_AZURE,CloudProviderValues=createConstMap([TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,TMP_CLOUDPROVIDERVALUES_AWS,TMP_CLOUDPROVIDERVALUES_AZURE,TMP_CLOUDPROVIDERVALUES_GCP]),TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS=`alibaba_cloud_ecs`,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC=`alibaba_cloud_fc`,TMP_CLOUDPLATFORMVALUES_AWS_EC2=`aws_ec2`,TMP_CLOUDPLATFORMVALUES_AWS_ECS=`aws_ecs`,TMP_CLOUDPLATFORMVALUES_AWS_EKS=`aws_eks`,TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA=`aws_lambda`,TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK=`aws_elastic_beanstalk`,TMP_CLOUDPLATFORMVALUES_AZURE_VM=`azure_vm`,TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES=`azure_container_instances`,TMP_CLOUDPLATFORMVALUES_AZURE_AKS=`azure_aks`,TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS=`azure_functions`,TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE=`azure_app_service`,TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE=`gcp_compute_engine`,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN=`gcp_cloud_run`,TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE=`gcp_kubernetes_engine`,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS=`gcp_cloud_functions`,TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE=`gcp_app_engine`,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS=TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC=TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,CLOUDPLATFORMVALUES_AWS_EC2=TMP_CLOUDPLATFORMVALUES_AWS_EC2,CLOUDPLATFORMVALUES_AWS_ECS=TMP_CLOUDPLATFORMVALUES_AWS_ECS,CLOUDPLATFORMVALUES_AWS_EKS=TMP_CLOUDPLATFORMVALUES_AWS_EKS,CLOUDPLATFORMVALUES_AWS_LAMBDA=TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK=TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,CLOUDPLATFORMVALUES_AZURE_VM=TMP_CLOUDPLATFORMVALUES_AZURE_VM,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES=TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,CLOUDPLATFORMVALUES_AZURE_AKS=TMP_CLOUDPLATFORMVALUES_AZURE_AKS,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS=TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE=TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE=TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN=TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE=TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS=TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,CLOUDPLATFORMVALUES_GCP_APP_ENGINE=TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CloudPlatformValues=createConstMap([TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,TMP_CLOUDPLATFORMVALUES_AWS_EC2,TMP_CLOUDPLATFORMVALUES_AWS_ECS,TMP_CLOUDPLATFORMVALUES_AWS_EKS,TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,TMP_CLOUDPLATFORMVALUES_AZURE_VM,TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,TMP_CLOUDPLATFORMVALUES_AZURE_AKS,TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE]),TMP_AWSECSLAUNCHTYPEVALUES_EC2=`ec2`,TMP_AWSECSLAUNCHTYPEVALUES_FARGATE=`fargate`,AWSECSLAUNCHTYPEVALUES_FARGATE=TMP_AWSECSLAUNCHTYPEVALUES_FARGATE,AwsEcsLaunchtypeValues=createConstMap([TMP_AWSECSLAUNCHTYPEVALUES_EC2,TMP_AWSECSLAUNCHTYPEVALUES_FARGATE]),TMP_HOSTARCHVALUES_AMD64=`amd64`,TMP_HOSTARCHVALUES_ARM32=`arm32`,TMP_HOSTARCHVALUES_ARM64=`arm64`,TMP_HOSTARCHVALUES_IA64=`ia64`,TMP_HOSTARCHVALUES_PPC32=`ppc32`,TMP_HOSTARCHVALUES_PPC64=`ppc64`,TMP_HOSTARCHVALUES_X86=`x86`,HOSTARCHVALUES_AMD64=TMP_HOSTARCHVALUES_AMD64,HOSTARCHVALUES_ARM32=TMP_HOSTARCHVALUES_ARM32,HOSTARCHVALUES_ARM64=TMP_HOSTARCHVALUES_ARM64,HOSTARCHVALUES_IA64=TMP_HOSTARCHVALUES_IA64,HOSTARCHVALUES_PPC32=TMP_HOSTARCHVALUES_PPC32,HOSTARCHVALUES_PPC64=TMP_HOSTARCHVALUES_PPC64,HostArchValues=createConstMap([TMP_HOSTARCHVALUES_AMD64,TMP_HOSTARCHVALUES_ARM32,TMP_HOSTARCHVALUES_ARM64,TMP_HOSTARCHVALUES_IA64,TMP_HOSTARCHVALUES_PPC32,TMP_HOSTARCHVALUES_PPC64,TMP_HOSTARCHVALUES_X86]),TMP_OSTYPEVALUES_WINDOWS=`windows`,TMP_OSTYPEVALUES_LINUX=`linux`,TMP_OSTYPEVALUES_DARWIN=`darwin`,TMP_OSTYPEVALUES_FREEBSD=`freebsd`,TMP_OSTYPEVALUES_NETBSD=`netbsd`,TMP_OSTYPEVALUES_OPENBSD=`openbsd`,TMP_OSTYPEVALUES_DRAGONFLYBSD=`dragonflybsd`,TMP_OSTYPEVALUES_HPUX=`hpux`,TMP_OSTYPEVALUES_AIX=`aix`,TMP_OSTYPEVALUES_SOLARIS=`solaris`,TMP_OSTYPEVALUES_Z_OS=`z_os`,OSTYPEVALUES_WINDOWS=TMP_OSTYPEVALUES_WINDOWS,OSTYPEVALUES_LINUX=TMP_OSTYPEVALUES_LINUX,OSTYPEVALUES_DARWIN=TMP_OSTYPEVALUES_DARWIN,OSTYPEVALUES_FREEBSD=TMP_OSTYPEVALUES_FREEBSD,OSTYPEVALUES_NETBSD=TMP_OSTYPEVALUES_NETBSD,OSTYPEVALUES_OPENBSD=TMP_OSTYPEVALUES_OPENBSD,OSTYPEVALUES_DRAGONFLYBSD=TMP_OSTYPEVALUES_DRAGONFLYBSD,OSTYPEVALUES_HPUX=TMP_OSTYPEVALUES_HPUX,OSTYPEVALUES_SOLARIS=TMP_OSTYPEVALUES_SOLARIS,OSTYPEVALUES_Z_OS=TMP_OSTYPEVALUES_Z_OS,OsTypeValues=createConstMap([TMP_OSTYPEVALUES_WINDOWS,TMP_OSTYPEVALUES_LINUX,TMP_OSTYPEVALUES_DARWIN,TMP_OSTYPEVALUES_FREEBSD,TMP_OSTYPEVALUES_NETBSD,TMP_OSTYPEVALUES_OPENBSD,TMP_OSTYPEVALUES_DRAGONFLYBSD,TMP_OSTYPEVALUES_HPUX,TMP_OSTYPEVALUES_AIX,TMP_OSTYPEVALUES_SOLARIS,TMP_OSTYPEVALUES_Z_OS]),TMP_TELEMETRYSDKLANGUAGEVALUES_CPP=`cpp`,TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET=`dotnet`,TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG=`erlang`,TMP_TELEMETRYSDKLANGUAGEVALUES_GO=`go`,TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA=`java`,TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS=`nodejs`,TMP_TELEMETRYSDKLANGUAGEVALUES_PHP=`php`,TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON=`python`,TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY=`ruby`,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS=`webjs`,TELEMETRYSDKLANGUAGEVALUES_DOTNET=TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,TELEMETRYSDKLANGUAGEVALUES_ERLANG=TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,TELEMETRYSDKLANGUAGEVALUES_JAVA=TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,TELEMETRYSDKLANGUAGEVALUES_NODEJS=TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,TELEMETRYSDKLANGUAGEVALUES_PYTHON=TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,TELEMETRYSDKLANGUAGEVALUES_RUBY=TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,TELEMETRYSDKLANGUAGEVALUES_WEBJS=TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,TelemetrySdkLanguageValues=createConstMap([TMP_TELEMETRYSDKLANGUAGEVALUES_CPP,TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,TMP_TELEMETRYSDKLANGUAGEVALUES_GO,TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,TMP_TELEMETRYSDKLANGUAGEVALUES_PHP,TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS])})),init_resource=__esmMin((()=>{init_SemanticResourceAttributes()})),ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE,ATTR_ASPNETCORE_RATE_LIMITING_POLICY,ATTR_ASPNETCORE_RATE_LIMITING_RESULT,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED,ATTR_CLIENT_ADDRESS,ATTR_CLIENT_PORT,ATTR_CODE_COLUMN_NUMBER,ATTR_CODE_FILE_PATH,ATTR_CODE_FUNCTION_NAME,ATTR_CODE_LINE_NUMBER,ATTR_CODE_STACKTRACE,ATTR_DB_COLLECTION_NAME,ATTR_DB_NAMESPACE,ATTR_DB_OPERATION_BATCH_SIZE,ATTR_DB_OPERATION_NAME,ATTR_DB_QUERY_SUMMARY,ATTR_DB_QUERY_TEXT,ATTR_DB_RESPONSE_STATUS_CODE,ATTR_DB_STORED_PROCEDURE_NAME,ATTR_DB_SYSTEM_NAME,DB_SYSTEM_NAME_VALUE_MARIADB,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER,DB_SYSTEM_NAME_VALUE_MYSQL,DB_SYSTEM_NAME_VALUE_POSTGRESQL,ATTR_DOTNET_GC_HEAP_GENERATION,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2,DOTNET_GC_HEAP_GENERATION_VALUE_LOH,DOTNET_GC_HEAP_GENERATION_VALUE_POH,ATTR_ERROR_TYPE,ERROR_TYPE_VALUE_OTHER,ATTR_EXCEPTION_ESCAPED,ATTR_EXCEPTION_MESSAGE,ATTR_EXCEPTION_STACKTRACE,ATTR_EXCEPTION_TYPE,ATTR_HTTP_REQUEST_HEADER,ATTR_HTTP_REQUEST_METHOD,HTTP_REQUEST_METHOD_VALUE_OTHER,HTTP_REQUEST_METHOD_VALUE_CONNECT,HTTP_REQUEST_METHOD_VALUE_DELETE,HTTP_REQUEST_METHOD_VALUE_GET,HTTP_REQUEST_METHOD_VALUE_HEAD,HTTP_REQUEST_METHOD_VALUE_OPTIONS,HTTP_REQUEST_METHOD_VALUE_PATCH,HTTP_REQUEST_METHOD_VALUE_POST,HTTP_REQUEST_METHOD_VALUE_PUT,HTTP_REQUEST_METHOD_VALUE_TRACE,ATTR_HTTP_REQUEST_METHOD_ORIGINAL,ATTR_HTTP_REQUEST_RESEND_COUNT,ATTR_HTTP_RESPONSE_HEADER,ATTR_HTTP_RESPONSE_STATUS_CODE,ATTR_HTTP_ROUTE,ATTR_JVM_GC_ACTION,ATTR_JVM_GC_NAME,ATTR_JVM_MEMORY_POOL_NAME,ATTR_JVM_MEMORY_TYPE,JVM_MEMORY_TYPE_VALUE_HEAP,JVM_MEMORY_TYPE_VALUE_NON_HEAP,ATTR_JVM_THREAD_DAEMON,ATTR_JVM_THREAD_STATE,JVM_THREAD_STATE_VALUE_BLOCKED,JVM_THREAD_STATE_VALUE_NEW,JVM_THREAD_STATE_VALUE_RUNNABLE,JVM_THREAD_STATE_VALUE_TERMINATED,JVM_THREAD_STATE_VALUE_TIMED_WAITING,JVM_THREAD_STATE_VALUE_WAITING,ATTR_NETWORK_LOCAL_ADDRESS,ATTR_NETWORK_LOCAL_PORT,ATTR_NETWORK_PEER_ADDRESS,ATTR_NETWORK_PEER_PORT,ATTR_NETWORK_PROTOCOL_NAME,ATTR_NETWORK_PROTOCOL_VERSION,ATTR_NETWORK_TRANSPORT,NETWORK_TRANSPORT_VALUE_PIPE,NETWORK_TRANSPORT_VALUE_QUIC,NETWORK_TRANSPORT_VALUE_TCP,NETWORK_TRANSPORT_VALUE_UDP,NETWORK_TRANSPORT_VALUE_UNIX,ATTR_NETWORK_TYPE,NETWORK_TYPE_VALUE_IPV4,NETWORK_TYPE_VALUE_IPV6,ATTR_OTEL_SCOPE_NAME,ATTR_OTEL_SCOPE_VERSION,ATTR_OTEL_STATUS_CODE,OTEL_STATUS_CODE_VALUE_ERROR,OTEL_STATUS_CODE_VALUE_OK,ATTR_OTEL_STATUS_DESCRIPTION,ATTR_SERVER_ADDRESS,ATTR_SERVER_PORT,ATTR_SERVICE_INSTANCE_ID,ATTR_SERVICE_NAME,ATTR_SERVICE_NAMESPACE,ATTR_SERVICE_VERSION,ATTR_SIGNALR_CONNECTION_STATUS,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT,ATTR_SIGNALR_TRANSPORT,SIGNALR_TRANSPORT_VALUE_LONG_POLLING,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS,ATTR_TELEMETRY_SDK_LANGUAGE,TELEMETRY_SDK_LANGUAGE_VALUE_CPP,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG,TELEMETRY_SDK_LANGUAGE_VALUE_GO,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,TELEMETRY_SDK_LANGUAGE_VALUE_PHP,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY,TELEMETRY_SDK_LANGUAGE_VALUE_RUST,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,ATTR_TELEMETRY_SDK_NAME,ATTR_TELEMETRY_SDK_VERSION,ATTR_URL_FRAGMENT,ATTR_URL_FULL,ATTR_URL_PATH,ATTR_URL_QUERY,ATTR_URL_SCHEME,ATTR_USER_AGENT_ORIGINAL,init_stable_attributes=__esmMin((()=>{ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT=`aspnetcore.diagnostics.exception.result`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED=`aborted`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED=`handled`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED=`skipped`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED=`unhandled`,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE=`aspnetcore.diagnostics.handler.type`,ATTR_ASPNETCORE_RATE_LIMITING_POLICY=`aspnetcore.rate_limiting.policy`,ATTR_ASPNETCORE_RATE_LIMITING_RESULT=`aspnetcore.rate_limiting.result`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED=`acquired`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER=`endpoint_limiter`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER=`global_limiter`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED=`request_canceled`,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED=`aspnetcore.request.is_unhandled`,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK=`aspnetcore.routing.is_fallback`,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS=`aspnetcore.routing.match_status`,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE=`failure`,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS=`success`,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED=`aspnetcore.user.is_authenticated`,ATTR_CLIENT_ADDRESS=`client.address`,ATTR_CLIENT_PORT=`client.port`,ATTR_CODE_COLUMN_NUMBER=`code.column.number`,ATTR_CODE_FILE_PATH=`code.file.path`,ATTR_CODE_FUNCTION_NAME=`code.function.name`,ATTR_CODE_LINE_NUMBER=`code.line.number`,ATTR_CODE_STACKTRACE=`code.stacktrace`,ATTR_DB_COLLECTION_NAME=`db.collection.name`,ATTR_DB_NAMESPACE=`db.namespace`,ATTR_DB_OPERATION_BATCH_SIZE=`db.operation.batch.size`,ATTR_DB_OPERATION_NAME=`db.operation.name`,ATTR_DB_QUERY_SUMMARY=`db.query.summary`,ATTR_DB_QUERY_TEXT=`db.query.text`,ATTR_DB_RESPONSE_STATUS_CODE=`db.response.status_code`,ATTR_DB_STORED_PROCEDURE_NAME=`db.stored_procedure.name`,ATTR_DB_SYSTEM_NAME=`db.system.name`,DB_SYSTEM_NAME_VALUE_MARIADB=`mariadb`,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER=`microsoft.sql_server`,DB_SYSTEM_NAME_VALUE_MYSQL=`mysql`,DB_SYSTEM_NAME_VALUE_POSTGRESQL=`postgresql`,ATTR_DOTNET_GC_HEAP_GENERATION=`dotnet.gc.heap.generation`,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0=`gen0`,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1=`gen1`,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2=`gen2`,ATTR_ERROR_TYPE=`error.type`,ERROR_TYPE_VALUE_OTHER=`_OTHER`,ATTR_EXCEPTION_ESCAPED=`exception.escaped`,ATTR_EXCEPTION_MESSAGE=`exception.message`,ATTR_EXCEPTION_STACKTRACE=`exception.stacktrace`,ATTR_EXCEPTION_TYPE=`exception.type`,ATTR_HTTP_REQUEST_HEADER=e=>`http.request.header.${e}`,ATTR_HTTP_REQUEST_METHOD=`http.request.method`,HTTP_REQUEST_METHOD_VALUE_OTHER=`_OTHER`,HTTP_REQUEST_METHOD_VALUE_CONNECT=`CONNECT`,HTTP_REQUEST_METHOD_VALUE_DELETE=`DELETE`,HTTP_REQUEST_METHOD_VALUE_HEAD=`HEAD`,HTTP_REQUEST_METHOD_VALUE_OPTIONS=`OPTIONS`,HTTP_REQUEST_METHOD_VALUE_PATCH=`PATCH`,HTTP_REQUEST_METHOD_VALUE_POST=`POST`,HTTP_REQUEST_METHOD_VALUE_TRACE=`TRACE`,ATTR_HTTP_REQUEST_METHOD_ORIGINAL=`http.request.method_original`,ATTR_HTTP_REQUEST_RESEND_COUNT=`http.request.resend_count`,ATTR_HTTP_RESPONSE_HEADER=e=>`http.response.header.${e}`,ATTR_HTTP_RESPONSE_STATUS_CODE=`http.response.status_code`,ATTR_HTTP_ROUTE=`http.route`,ATTR_JVM_GC_ACTION=`jvm.gc.action`,ATTR_JVM_GC_NAME=`jvm.gc.name`,ATTR_JVM_MEMORY_POOL_NAME=`jvm.memory.pool.name`,ATTR_JVM_MEMORY_TYPE=`jvm.memory.type`,JVM_MEMORY_TYPE_VALUE_HEAP=`heap`,JVM_MEMORY_TYPE_VALUE_NON_HEAP=`non_heap`,ATTR_JVM_THREAD_DAEMON=`jvm.thread.daemon`,ATTR_JVM_THREAD_STATE=`jvm.thread.state`,JVM_THREAD_STATE_VALUE_BLOCKED=`blocked`,JVM_THREAD_STATE_VALUE_RUNNABLE=`runnable`,JVM_THREAD_STATE_VALUE_TERMINATED=`terminated`,JVM_THREAD_STATE_VALUE_TIMED_WAITING=`timed_waiting`,JVM_THREAD_STATE_VALUE_WAITING=`waiting`,ATTR_NETWORK_LOCAL_ADDRESS=`network.local.address`,ATTR_NETWORK_LOCAL_PORT=`network.local.port`,ATTR_NETWORK_PEER_ADDRESS=`network.peer.address`,ATTR_NETWORK_PEER_PORT=`network.peer.port`,ATTR_NETWORK_PROTOCOL_NAME=`network.protocol.name`,ATTR_NETWORK_PROTOCOL_VERSION=`network.protocol.version`,ATTR_NETWORK_TRANSPORT=`network.transport`,NETWORK_TRANSPORT_VALUE_PIPE=`pipe`,NETWORK_TRANSPORT_VALUE_QUIC=`quic`,NETWORK_TRANSPORT_VALUE_UNIX=`unix`,ATTR_NETWORK_TYPE=`network.type`,NETWORK_TYPE_VALUE_IPV4=`ipv4`,NETWORK_TYPE_VALUE_IPV6=`ipv6`,ATTR_OTEL_SCOPE_NAME=`otel.scope.name`,ATTR_OTEL_SCOPE_VERSION=`otel.scope.version`,ATTR_OTEL_STATUS_CODE=`otel.status_code`,OTEL_STATUS_CODE_VALUE_ERROR=`ERROR`,ATTR_OTEL_STATUS_DESCRIPTION=`otel.status_description`,ATTR_SERVER_ADDRESS=`server.address`,ATTR_SERVER_PORT=`server.port`,ATTR_SERVICE_INSTANCE_ID=`service.instance.id`,ATTR_SERVICE_NAME=`service.name`,ATTR_SERVICE_NAMESPACE=`service.namespace`,ATTR_SERVICE_VERSION=`service.version`,ATTR_SIGNALR_CONNECTION_STATUS=`signalr.connection.status`,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN=`app_shutdown`,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE=`normal_closure`,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT=`timeout`,ATTR_SIGNALR_TRANSPORT=`signalr.transport`,SIGNALR_TRANSPORT_VALUE_LONG_POLLING=`long_polling`,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS=`server_sent_events`,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS=`web_sockets`,ATTR_TELEMETRY_SDK_LANGUAGE=`telemetry.sdk.language`,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET=`dotnet`,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG=`erlang`,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA=`java`,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS=`nodejs`,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON=`python`,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY=`ruby`,TELEMETRY_SDK_LANGUAGE_VALUE_RUST=`rust`,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT=`swift`,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS=`webjs`,ATTR_TELEMETRY_SDK_NAME=`telemetry.sdk.name`,ATTR_TELEMETRY_SDK_VERSION=`telemetry.sdk.version`,ATTR_URL_FRAGMENT=`url.fragment`,ATTR_URL_FULL=`url.full`,ATTR_URL_PATH=`url.path`,ATTR_URL_QUERY=`url.query`,ATTR_URL_SCHEME=`url.scheme`,ATTR_USER_AGENT_ORIGINAL=`user_agent.original`})),METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS,METRIC_DB_CLIENT_OPERATION_DURATION,METRIC_DOTNET_ASSEMBLY_COUNT,METRIC_DOTNET_EXCEPTIONS,METRIC_DOTNET_GC_COLLECTIONS,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE,METRIC_DOTNET_GC_PAUSE_TIME,METRIC_DOTNET_JIT_COMPILATION_TIME,METRIC_DOTNET_JIT_COMPILED_IL_SIZE,METRIC_DOTNET_JIT_COMPILED_METHODS,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS,METRIC_DOTNET_PROCESS_CPU_COUNT,METRIC_DOTNET_PROCESS_CPU_TIME,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT,METRIC_DOTNET_TIMER_COUNT,METRIC_HTTP_CLIENT_REQUEST_DURATION,METRIC_HTTP_SERVER_REQUEST_DURATION,METRIC_JVM_CLASS_COUNT,METRIC_JVM_CLASS_LOADED,METRIC_JVM_CLASS_UNLOADED,METRIC_JVM_CPU_COUNT,METRIC_JVM_CPU_RECENT_UTILIZATION,METRIC_JVM_CPU_TIME,METRIC_JVM_GC_DURATION,METRIC_JVM_MEMORY_COMMITTED,METRIC_JVM_MEMORY_LIMIT,METRIC_JVM_MEMORY_USED,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC,METRIC_JVM_THREAD_COUNT,METRIC_KESTREL_ACTIVE_CONNECTIONS,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES,METRIC_KESTREL_CONNECTION_DURATION,METRIC_KESTREL_QUEUED_CONNECTIONS,METRIC_KESTREL_QUEUED_REQUESTS,METRIC_KESTREL_REJECTED_CONNECTIONS,METRIC_KESTREL_TLS_HANDSHAKE_DURATION,METRIC_KESTREL_UPGRADED_CONNECTIONS,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS,METRIC_SIGNALR_SERVER_CONNECTION_DURATION,init_stable_metrics=__esmMin((()=>{METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS=`aspnetcore.diagnostics.exceptions`,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES=`aspnetcore.rate_limiting.active_request_leases`,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS=`aspnetcore.rate_limiting.queued_requests`,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE=`aspnetcore.rate_limiting.request.time_in_queue`,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION=`aspnetcore.rate_limiting.request_lease.duration`,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS=`aspnetcore.rate_limiting.requests`,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS=`aspnetcore.routing.match_attempts`,METRIC_DB_CLIENT_OPERATION_DURATION=`db.client.operation.duration`,METRIC_DOTNET_ASSEMBLY_COUNT=`dotnet.assembly.count`,METRIC_DOTNET_EXCEPTIONS=`dotnet.exceptions`,METRIC_DOTNET_GC_COLLECTIONS=`dotnet.gc.collections`,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED=`dotnet.gc.heap.total_allocated`,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE=`dotnet.gc.last_collection.heap.fragmentation.size`,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE=`dotnet.gc.last_collection.heap.size`,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE=`dotnet.gc.last_collection.memory.committed_size`,METRIC_DOTNET_GC_PAUSE_TIME=`dotnet.gc.pause.time`,METRIC_DOTNET_JIT_COMPILATION_TIME=`dotnet.jit.compilation.time`,METRIC_DOTNET_JIT_COMPILED_IL_SIZE=`dotnet.jit.compiled_il.size`,METRIC_DOTNET_JIT_COMPILED_METHODS=`dotnet.jit.compiled_methods`,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS=`dotnet.monitor.lock_contentions`,METRIC_DOTNET_PROCESS_CPU_COUNT=`dotnet.process.cpu.count`,METRIC_DOTNET_PROCESS_CPU_TIME=`dotnet.process.cpu.time`,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET=`dotnet.process.memory.working_set`,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH=`dotnet.thread_pool.queue.length`,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT=`dotnet.thread_pool.thread.count`,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT=`dotnet.thread_pool.work_item.count`,METRIC_DOTNET_TIMER_COUNT=`dotnet.timer.count`,METRIC_HTTP_CLIENT_REQUEST_DURATION=`http.client.request.duration`,METRIC_HTTP_SERVER_REQUEST_DURATION=`http.server.request.duration`,METRIC_JVM_CLASS_COUNT=`jvm.class.count`,METRIC_JVM_CLASS_LOADED=`jvm.class.loaded`,METRIC_JVM_CLASS_UNLOADED=`jvm.class.unloaded`,METRIC_JVM_CPU_COUNT=`jvm.cpu.count`,METRIC_JVM_CPU_RECENT_UTILIZATION=`jvm.cpu.recent_utilization`,METRIC_JVM_CPU_TIME=`jvm.cpu.time`,METRIC_JVM_GC_DURATION=`jvm.gc.duration`,METRIC_JVM_MEMORY_COMMITTED=`jvm.memory.committed`,METRIC_JVM_MEMORY_LIMIT=`jvm.memory.limit`,METRIC_JVM_MEMORY_USED=`jvm.memory.used`,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC=`jvm.memory.used_after_last_gc`,METRIC_JVM_THREAD_COUNT=`jvm.thread.count`,METRIC_KESTREL_ACTIVE_CONNECTIONS=`kestrel.active_connections`,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES=`kestrel.active_tls_handshakes`,METRIC_KESTREL_CONNECTION_DURATION=`kestrel.connection.duration`,METRIC_KESTREL_QUEUED_CONNECTIONS=`kestrel.queued_connections`,METRIC_KESTREL_QUEUED_REQUESTS=`kestrel.queued_requests`,METRIC_KESTREL_REJECTED_CONNECTIONS=`kestrel.rejected_connections`,METRIC_KESTREL_TLS_HANDSHAKE_DURATION=`kestrel.tls_handshake.duration`,METRIC_KESTREL_UPGRADED_CONNECTIONS=`kestrel.upgraded_connections`,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS=`signalr.server.active_connections`,METRIC_SIGNALR_SERVER_CONNECTION_DURATION=`signalr.server.connection.duration`})),EVENT_EXCEPTION,init_stable_events=__esmMin((()=>{EVENT_EXCEPTION=`exception`})),esm_exports$1=__exportAll({ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE:()=>ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS:()=>ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS,ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT:()=>ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE:()=>ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE,ATTR_ASPNETCORE_RATE_LIMITING_POLICY:()=>ATTR_ASPNETCORE_RATE_LIMITING_POLICY,ATTR_ASPNETCORE_RATE_LIMITING_RESULT:()=>ATTR_ASPNETCORE_RATE_LIMITING_RESULT,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED:()=>ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK:()=>ATTR_ASPNETCORE_ROUTING_IS_FALLBACK,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS:()=>ATTR_ASPNETCORE_ROUTING_MATCH_STATUS,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED:()=>ATTR_ASPNETCORE_USER_IS_AUTHENTICATED,ATTR_CLIENT_ADDRESS:()=>ATTR_CLIENT_ADDRESS,ATTR_CLIENT_PORT:()=>ATTR_CLIENT_PORT,ATTR_CODE_COLUMN_NUMBER:()=>ATTR_CODE_COLUMN_NUMBER,ATTR_CODE_FILE_PATH:()=>ATTR_CODE_FILE_PATH,ATTR_CODE_FUNCTION_NAME:()=>ATTR_CODE_FUNCTION_NAME,ATTR_CODE_LINE_NUMBER:()=>ATTR_CODE_LINE_NUMBER,ATTR_CODE_STACKTRACE:()=>ATTR_CODE_STACKTRACE,ATTR_DB_COLLECTION_NAME:()=>ATTR_DB_COLLECTION_NAME,ATTR_DB_NAMESPACE:()=>ATTR_DB_NAMESPACE,ATTR_DB_OPERATION_BATCH_SIZE:()=>ATTR_DB_OPERATION_BATCH_SIZE,ATTR_DB_OPERATION_NAME:()=>ATTR_DB_OPERATION_NAME,ATTR_DB_QUERY_SUMMARY:()=>ATTR_DB_QUERY_SUMMARY,ATTR_DB_QUERY_TEXT:()=>ATTR_DB_QUERY_TEXT,ATTR_DB_RESPONSE_STATUS_CODE:()=>ATTR_DB_RESPONSE_STATUS_CODE,ATTR_DB_STORED_PROCEDURE_NAME:()=>ATTR_DB_STORED_PROCEDURE_NAME,ATTR_DB_SYSTEM_NAME:()=>ATTR_DB_SYSTEM_NAME,ATTR_DOTNET_GC_HEAP_GENERATION:()=>ATTR_DOTNET_GC_HEAP_GENERATION,ATTR_ERROR_TYPE:()=>ATTR_ERROR_TYPE,ATTR_EXCEPTION_ESCAPED:()=>ATTR_EXCEPTION_ESCAPED,ATTR_EXCEPTION_MESSAGE:()=>ATTR_EXCEPTION_MESSAGE,ATTR_EXCEPTION_STACKTRACE:()=>ATTR_EXCEPTION_STACKTRACE,ATTR_EXCEPTION_TYPE:()=>ATTR_EXCEPTION_TYPE,ATTR_HTTP_REQUEST_HEADER:()=>ATTR_HTTP_REQUEST_HEADER,ATTR_HTTP_REQUEST_METHOD:()=>ATTR_HTTP_REQUEST_METHOD,ATTR_HTTP_REQUEST_METHOD_ORIGINAL:()=>ATTR_HTTP_REQUEST_METHOD_ORIGINAL,ATTR_HTTP_REQUEST_RESEND_COUNT:()=>ATTR_HTTP_REQUEST_RESEND_COUNT,ATTR_HTTP_RESPONSE_HEADER:()=>ATTR_HTTP_RESPONSE_HEADER,ATTR_HTTP_RESPONSE_STATUS_CODE:()=>ATTR_HTTP_RESPONSE_STATUS_CODE,ATTR_HTTP_ROUTE:()=>ATTR_HTTP_ROUTE,ATTR_JVM_GC_ACTION:()=>ATTR_JVM_GC_ACTION,ATTR_JVM_GC_NAME:()=>ATTR_JVM_GC_NAME,ATTR_JVM_MEMORY_POOL_NAME:()=>ATTR_JVM_MEMORY_POOL_NAME,ATTR_JVM_MEMORY_TYPE:()=>ATTR_JVM_MEMORY_TYPE,ATTR_JVM_THREAD_DAEMON:()=>ATTR_JVM_THREAD_DAEMON,ATTR_JVM_THREAD_STATE:()=>ATTR_JVM_THREAD_STATE,ATTR_NETWORK_LOCAL_ADDRESS:()=>ATTR_NETWORK_LOCAL_ADDRESS,ATTR_NETWORK_LOCAL_PORT:()=>ATTR_NETWORK_LOCAL_PORT,ATTR_NETWORK_PEER_ADDRESS:()=>ATTR_NETWORK_PEER_ADDRESS,ATTR_NETWORK_PEER_PORT:()=>ATTR_NETWORK_PEER_PORT,ATTR_NETWORK_PROTOCOL_NAME:()=>ATTR_NETWORK_PROTOCOL_NAME,ATTR_NETWORK_PROTOCOL_VERSION:()=>ATTR_NETWORK_PROTOCOL_VERSION,ATTR_NETWORK_TRANSPORT:()=>ATTR_NETWORK_TRANSPORT,ATTR_NETWORK_TYPE:()=>ATTR_NETWORK_TYPE,ATTR_OTEL_SCOPE_NAME:()=>ATTR_OTEL_SCOPE_NAME,ATTR_OTEL_SCOPE_VERSION:()=>ATTR_OTEL_SCOPE_VERSION,ATTR_OTEL_STATUS_CODE:()=>ATTR_OTEL_STATUS_CODE,ATTR_OTEL_STATUS_DESCRIPTION:()=>ATTR_OTEL_STATUS_DESCRIPTION,ATTR_SERVER_ADDRESS:()=>ATTR_SERVER_ADDRESS,ATTR_SERVER_PORT:()=>ATTR_SERVER_PORT,ATTR_SERVICE_INSTANCE_ID:()=>ATTR_SERVICE_INSTANCE_ID,ATTR_SERVICE_NAME:()=>ATTR_SERVICE_NAME,ATTR_SERVICE_NAMESPACE:()=>ATTR_SERVICE_NAMESPACE,ATTR_SERVICE_VERSION:()=>ATTR_SERVICE_VERSION,ATTR_SIGNALR_CONNECTION_STATUS:()=>ATTR_SIGNALR_CONNECTION_STATUS,ATTR_SIGNALR_TRANSPORT:()=>ATTR_SIGNALR_TRANSPORT,ATTR_TELEMETRY_SDK_LANGUAGE:()=>ATTR_TELEMETRY_SDK_LANGUAGE,ATTR_TELEMETRY_SDK_NAME:()=>ATTR_TELEMETRY_SDK_NAME,ATTR_TELEMETRY_SDK_VERSION:()=>ATTR_TELEMETRY_SDK_VERSION,ATTR_URL_FRAGMENT:()=>ATTR_URL_FRAGMENT,ATTR_URL_FULL:()=>ATTR_URL_FULL,ATTR_URL_PATH:()=>ATTR_URL_PATH,ATTR_URL_QUERY:()=>ATTR_URL_QUERY,ATTR_URL_SCHEME:()=>ATTR_URL_SCHEME,ATTR_USER_AGENT_ORIGINAL:()=>ATTR_USER_AGENT_ORIGINAL,AWSECSLAUNCHTYPEVALUES_EC2:()=>`ec2`,AWSECSLAUNCHTYPEVALUES_FARGATE:()=>AWSECSLAUNCHTYPEVALUES_FARGATE,AwsEcsLaunchtypeValues:()=>AwsEcsLaunchtypeValues,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS:()=>CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC:()=>CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,CLOUDPLATFORMVALUES_AWS_EC2:()=>CLOUDPLATFORMVALUES_AWS_EC2,CLOUDPLATFORMVALUES_AWS_ECS:()=>CLOUDPLATFORMVALUES_AWS_ECS,CLOUDPLATFORMVALUES_AWS_EKS:()=>CLOUDPLATFORMVALUES_AWS_EKS,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK:()=>CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,CLOUDPLATFORMVALUES_AWS_LAMBDA:()=>CLOUDPLATFORMVALUES_AWS_LAMBDA,CLOUDPLATFORMVALUES_AZURE_AKS:()=>CLOUDPLATFORMVALUES_AZURE_AKS,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE:()=>CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES:()=>CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS:()=>CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,CLOUDPLATFORMVALUES_AZURE_VM:()=>CLOUDPLATFORMVALUES_AZURE_VM,CLOUDPLATFORMVALUES_GCP_APP_ENGINE:()=>CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS:()=>CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN:()=>CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE:()=>CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE:()=>CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,CLOUDPROVIDERVALUES_ALIBABA_CLOUD:()=>CLOUDPROVIDERVALUES_ALIBABA_CLOUD,CLOUDPROVIDERVALUES_AWS:()=>`aws`,CLOUDPROVIDERVALUES_AZURE:()=>CLOUDPROVIDERVALUES_AZURE,CLOUDPROVIDERVALUES_GCP:()=>`gcp`,CloudPlatformValues:()=>CloudPlatformValues,CloudProviderValues:()=>CloudProviderValues,DBCASSANDRACONSISTENCYLEVELVALUES_ALL:()=>`all`,DBCASSANDRACONSISTENCYLEVELVALUES_ANY:()=>`any`,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM:()=>DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE:()=>DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM:()=>DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL:()=>DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_ONE:()=>`one`,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM:()=>DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL:()=>DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_THREE:()=>DBCASSANDRACONSISTENCYLEVELVALUES_THREE,DBCASSANDRACONSISTENCYLEVELVALUES_TWO:()=>`two`,DBSYSTEMVALUES_ADABAS:()=>DBSYSTEMVALUES_ADABAS,DBSYSTEMVALUES_CACHE:()=>DBSYSTEMVALUES_CACHE,DBSYSTEMVALUES_CASSANDRA:()=>DBSYSTEMVALUES_CASSANDRA,DBSYSTEMVALUES_CLOUDSCAPE:()=>DBSYSTEMVALUES_CLOUDSCAPE,DBSYSTEMVALUES_COCKROACHDB:()=>DBSYSTEMVALUES_COCKROACHDB,DBSYSTEMVALUES_COLDFUSION:()=>DBSYSTEMVALUES_COLDFUSION,DBSYSTEMVALUES_COSMOSDB:()=>DBSYSTEMVALUES_COSMOSDB,DBSYSTEMVALUES_COUCHBASE:()=>DBSYSTEMVALUES_COUCHBASE,DBSYSTEMVALUES_COUCHDB:()=>DBSYSTEMVALUES_COUCHDB,DBSYSTEMVALUES_DB2:()=>`db2`,DBSYSTEMVALUES_DERBY:()=>DBSYSTEMVALUES_DERBY,DBSYSTEMVALUES_DYNAMODB:()=>DBSYSTEMVALUES_DYNAMODB,DBSYSTEMVALUES_EDB:()=>`edb`,DBSYSTEMVALUES_ELASTICSEARCH:()=>DBSYSTEMVALUES_ELASTICSEARCH,DBSYSTEMVALUES_FILEMAKER:()=>DBSYSTEMVALUES_FILEMAKER,DBSYSTEMVALUES_FIREBIRD:()=>DBSYSTEMVALUES_FIREBIRD,DBSYSTEMVALUES_FIRSTSQL:()=>DBSYSTEMVALUES_FIRSTSQL,DBSYSTEMVALUES_GEODE:()=>DBSYSTEMVALUES_GEODE,DBSYSTEMVALUES_H2:()=>`h2`,DBSYSTEMVALUES_HANADB:()=>DBSYSTEMVALUES_HANADB,DBSYSTEMVALUES_HBASE:()=>DBSYSTEMVALUES_HBASE,DBSYSTEMVALUES_HIVE:()=>DBSYSTEMVALUES_HIVE,DBSYSTEMVALUES_HSQLDB:()=>DBSYSTEMVALUES_HSQLDB,DBSYSTEMVALUES_INFORMIX:()=>DBSYSTEMVALUES_INFORMIX,DBSYSTEMVALUES_INGRES:()=>DBSYSTEMVALUES_INGRES,DBSYSTEMVALUES_INSTANTDB:()=>DBSYSTEMVALUES_INSTANTDB,DBSYSTEMVALUES_INTERBASE:()=>DBSYSTEMVALUES_INTERBASE,DBSYSTEMVALUES_MARIADB:()=>DBSYSTEMVALUES_MARIADB,DBSYSTEMVALUES_MAXDB:()=>DBSYSTEMVALUES_MAXDB,DBSYSTEMVALUES_MEMCACHED:()=>DBSYSTEMVALUES_MEMCACHED,DBSYSTEMVALUES_MONGODB:()=>DBSYSTEMVALUES_MONGODB,DBSYSTEMVALUES_MSSQL:()=>DBSYSTEMVALUES_MSSQL,DBSYSTEMVALUES_MYSQL:()=>DBSYSTEMVALUES_MYSQL,DBSYSTEMVALUES_NEO4J:()=>DBSYSTEMVALUES_NEO4J,DBSYSTEMVALUES_NETEZZA:()=>DBSYSTEMVALUES_NETEZZA,DBSYSTEMVALUES_ORACLE:()=>DBSYSTEMVALUES_ORACLE,DBSYSTEMVALUES_OTHER_SQL:()=>DBSYSTEMVALUES_OTHER_SQL,DBSYSTEMVALUES_PERVASIVE:()=>DBSYSTEMVALUES_PERVASIVE,DBSYSTEMVALUES_POINTBASE:()=>DBSYSTEMVALUES_POINTBASE,DBSYSTEMVALUES_POSTGRESQL:()=>DBSYSTEMVALUES_POSTGRESQL,DBSYSTEMVALUES_PROGRESS:()=>DBSYSTEMVALUES_PROGRESS,DBSYSTEMVALUES_REDIS:()=>DBSYSTEMVALUES_REDIS,DBSYSTEMVALUES_REDSHIFT:()=>DBSYSTEMVALUES_REDSHIFT,DBSYSTEMVALUES_SQLITE:()=>DBSYSTEMVALUES_SQLITE,DBSYSTEMVALUES_SYBASE:()=>DBSYSTEMVALUES_SYBASE,DBSYSTEMVALUES_TERADATA:()=>DBSYSTEMVALUES_TERADATA,DBSYSTEMVALUES_VERTICA:()=>DBSYSTEMVALUES_VERTICA,DB_SYSTEM_NAME_VALUE_MARIADB:()=>DB_SYSTEM_NAME_VALUE_MARIADB,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER:()=>DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER,DB_SYSTEM_NAME_VALUE_MYSQL:()=>DB_SYSTEM_NAME_VALUE_MYSQL,DB_SYSTEM_NAME_VALUE_POSTGRESQL:()=>DB_SYSTEM_NAME_VALUE_POSTGRESQL,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0:()=>DOTNET_GC_HEAP_GENERATION_VALUE_GEN0,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1:()=>DOTNET_GC_HEAP_GENERATION_VALUE_GEN1,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2:()=>DOTNET_GC_HEAP_GENERATION_VALUE_GEN2,DOTNET_GC_HEAP_GENERATION_VALUE_LOH:()=>`loh`,DOTNET_GC_HEAP_GENERATION_VALUE_POH:()=>`poh`,DbCassandraConsistencyLevelValues:()=>DbCassandraConsistencyLevelValues,DbSystemValues:()=>DbSystemValues,ERROR_TYPE_VALUE_OTHER:()=>ERROR_TYPE_VALUE_OTHER,EVENT_EXCEPTION:()=>EVENT_EXCEPTION,FAASDOCUMENTOPERATIONVALUES_DELETE:()=>FAASDOCUMENTOPERATIONVALUES_DELETE,FAASDOCUMENTOPERATIONVALUES_EDIT:()=>FAASDOCUMENTOPERATIONVALUES_EDIT,FAASDOCUMENTOPERATIONVALUES_INSERT:()=>FAASDOCUMENTOPERATIONVALUES_INSERT,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD:()=>FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,FAASINVOKEDPROVIDERVALUES_AWS:()=>`aws`,FAASINVOKEDPROVIDERVALUES_AZURE:()=>FAASINVOKEDPROVIDERVALUES_AZURE,FAASINVOKEDPROVIDERVALUES_GCP:()=>`gcp`,FAASTRIGGERVALUES_DATASOURCE:()=>FAASTRIGGERVALUES_DATASOURCE,FAASTRIGGERVALUES_HTTP:()=>FAASTRIGGERVALUES_HTTP,FAASTRIGGERVALUES_OTHER:()=>FAASTRIGGERVALUES_OTHER,FAASTRIGGERVALUES_PUBSUB:()=>FAASTRIGGERVALUES_PUBSUB,FAASTRIGGERVALUES_TIMER:()=>FAASTRIGGERVALUES_TIMER,FaasDocumentOperationValues:()=>FaasDocumentOperationValues,FaasInvokedProviderValues:()=>FaasInvokedProviderValues,FaasTriggerValues:()=>FaasTriggerValues,HOSTARCHVALUES_AMD64:()=>HOSTARCHVALUES_AMD64,HOSTARCHVALUES_ARM32:()=>HOSTARCHVALUES_ARM32,HOSTARCHVALUES_ARM64:()=>HOSTARCHVALUES_ARM64,HOSTARCHVALUES_IA64:()=>HOSTARCHVALUES_IA64,HOSTARCHVALUES_PPC32:()=>HOSTARCHVALUES_PPC32,HOSTARCHVALUES_PPC64:()=>HOSTARCHVALUES_PPC64,HOSTARCHVALUES_X86:()=>`x86`,HTTPFLAVORVALUES_HTTP_1_0:()=>`1.0`,HTTPFLAVORVALUES_HTTP_1_1:()=>`1.1`,HTTPFLAVORVALUES_HTTP_2_0:()=>`2.0`,HTTPFLAVORVALUES_QUIC:()=>HTTPFLAVORVALUES_QUIC,HTTPFLAVORVALUES_SPDY:()=>HTTPFLAVORVALUES_SPDY,HTTP_REQUEST_METHOD_VALUE_CONNECT:()=>HTTP_REQUEST_METHOD_VALUE_CONNECT,HTTP_REQUEST_METHOD_VALUE_DELETE:()=>HTTP_REQUEST_METHOD_VALUE_DELETE,HTTP_REQUEST_METHOD_VALUE_GET:()=>`GET`,HTTP_REQUEST_METHOD_VALUE_HEAD:()=>HTTP_REQUEST_METHOD_VALUE_HEAD,HTTP_REQUEST_METHOD_VALUE_OPTIONS:()=>HTTP_REQUEST_METHOD_VALUE_OPTIONS,HTTP_REQUEST_METHOD_VALUE_OTHER:()=>HTTP_REQUEST_METHOD_VALUE_OTHER,HTTP_REQUEST_METHOD_VALUE_PATCH:()=>HTTP_REQUEST_METHOD_VALUE_PATCH,HTTP_REQUEST_METHOD_VALUE_POST:()=>HTTP_REQUEST_METHOD_VALUE_POST,HTTP_REQUEST_METHOD_VALUE_PUT:()=>`PUT`,HTTP_REQUEST_METHOD_VALUE_TRACE:()=>HTTP_REQUEST_METHOD_VALUE_TRACE,HostArchValues:()=>HostArchValues,HttpFlavorValues:()=>HttpFlavorValues,JVM_MEMORY_TYPE_VALUE_HEAP:()=>JVM_MEMORY_TYPE_VALUE_HEAP,JVM_MEMORY_TYPE_VALUE_NON_HEAP:()=>JVM_MEMORY_TYPE_VALUE_NON_HEAP,JVM_THREAD_STATE_VALUE_BLOCKED:()=>JVM_THREAD_STATE_VALUE_BLOCKED,JVM_THREAD_STATE_VALUE_NEW:()=>`new`,JVM_THREAD_STATE_VALUE_RUNNABLE:()=>JVM_THREAD_STATE_VALUE_RUNNABLE,JVM_THREAD_STATE_VALUE_TERMINATED:()=>JVM_THREAD_STATE_VALUE_TERMINATED,JVM_THREAD_STATE_VALUE_TIMED_WAITING:()=>JVM_THREAD_STATE_VALUE_TIMED_WAITING,JVM_THREAD_STATE_VALUE_WAITING:()=>JVM_THREAD_STATE_VALUE_WAITING,MESSAGETYPEVALUES_RECEIVED:()=>MESSAGETYPEVALUES_RECEIVED,MESSAGETYPEVALUES_SENT:()=>MESSAGETYPEVALUES_SENT,MESSAGINGDESTINATIONKINDVALUES_QUEUE:()=>MESSAGINGDESTINATIONKINDVALUES_QUEUE,MESSAGINGDESTINATIONKINDVALUES_TOPIC:()=>MESSAGINGDESTINATIONKINDVALUES_TOPIC,MESSAGINGOPERATIONVALUES_PROCESS:()=>MESSAGINGOPERATIONVALUES_PROCESS,MESSAGINGOPERATIONVALUES_RECEIVE:()=>MESSAGINGOPERATIONVALUES_RECEIVE,METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS:()=>METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES:()=>METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS:()=>METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS:()=>METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION:()=>METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE:()=>METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS:()=>METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS,METRIC_DB_CLIENT_OPERATION_DURATION:()=>METRIC_DB_CLIENT_OPERATION_DURATION,METRIC_DOTNET_ASSEMBLY_COUNT:()=>METRIC_DOTNET_ASSEMBLY_COUNT,METRIC_DOTNET_EXCEPTIONS:()=>METRIC_DOTNET_EXCEPTIONS,METRIC_DOTNET_GC_COLLECTIONS:()=>METRIC_DOTNET_GC_COLLECTIONS,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED:()=>METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE:()=>METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE:()=>METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE:()=>METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE,METRIC_DOTNET_GC_PAUSE_TIME:()=>METRIC_DOTNET_GC_PAUSE_TIME,METRIC_DOTNET_JIT_COMPILATION_TIME:()=>METRIC_DOTNET_JIT_COMPILATION_TIME,METRIC_DOTNET_JIT_COMPILED_IL_SIZE:()=>METRIC_DOTNET_JIT_COMPILED_IL_SIZE,METRIC_DOTNET_JIT_COMPILED_METHODS:()=>METRIC_DOTNET_JIT_COMPILED_METHODS,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS:()=>METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS,METRIC_DOTNET_PROCESS_CPU_COUNT:()=>METRIC_DOTNET_PROCESS_CPU_COUNT,METRIC_DOTNET_PROCESS_CPU_TIME:()=>METRIC_DOTNET_PROCESS_CPU_TIME,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET:()=>METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH:()=>METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT:()=>METRIC_DOTNET_THREAD_POOL_THREAD_COUNT,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT:()=>METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT,METRIC_DOTNET_TIMER_COUNT:()=>METRIC_DOTNET_TIMER_COUNT,METRIC_HTTP_CLIENT_REQUEST_DURATION:()=>METRIC_HTTP_CLIENT_REQUEST_DURATION,METRIC_HTTP_SERVER_REQUEST_DURATION:()=>METRIC_HTTP_SERVER_REQUEST_DURATION,METRIC_JVM_CLASS_COUNT:()=>METRIC_JVM_CLASS_COUNT,METRIC_JVM_CLASS_LOADED:()=>METRIC_JVM_CLASS_LOADED,METRIC_JVM_CLASS_UNLOADED:()=>METRIC_JVM_CLASS_UNLOADED,METRIC_JVM_CPU_COUNT:()=>METRIC_JVM_CPU_COUNT,METRIC_JVM_CPU_RECENT_UTILIZATION:()=>METRIC_JVM_CPU_RECENT_UTILIZATION,METRIC_JVM_CPU_TIME:()=>METRIC_JVM_CPU_TIME,METRIC_JVM_GC_DURATION:()=>METRIC_JVM_GC_DURATION,METRIC_JVM_MEMORY_COMMITTED:()=>METRIC_JVM_MEMORY_COMMITTED,METRIC_JVM_MEMORY_LIMIT:()=>METRIC_JVM_MEMORY_LIMIT,METRIC_JVM_MEMORY_USED:()=>METRIC_JVM_MEMORY_USED,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC:()=>METRIC_JVM_MEMORY_USED_AFTER_LAST_GC,METRIC_JVM_THREAD_COUNT:()=>METRIC_JVM_THREAD_COUNT,METRIC_KESTREL_ACTIVE_CONNECTIONS:()=>METRIC_KESTREL_ACTIVE_CONNECTIONS,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES:()=>METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES,METRIC_KESTREL_CONNECTION_DURATION:()=>METRIC_KESTREL_CONNECTION_DURATION,METRIC_KESTREL_QUEUED_CONNECTIONS:()=>METRIC_KESTREL_QUEUED_CONNECTIONS,METRIC_KESTREL_QUEUED_REQUESTS:()=>METRIC_KESTREL_QUEUED_REQUESTS,METRIC_KESTREL_REJECTED_CONNECTIONS:()=>METRIC_KESTREL_REJECTED_CONNECTIONS,METRIC_KESTREL_TLS_HANDSHAKE_DURATION:()=>METRIC_KESTREL_TLS_HANDSHAKE_DURATION,METRIC_KESTREL_UPGRADED_CONNECTIONS:()=>METRIC_KESTREL_UPGRADED_CONNECTIONS,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS:()=>METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS,METRIC_SIGNALR_SERVER_CONNECTION_DURATION:()=>METRIC_SIGNALR_SERVER_CONNECTION_DURATION,MessageTypeValues:()=>MessageTypeValues,MessagingDestinationKindValues:()=>MessagingDestinationKindValues,MessagingOperationValues:()=>MessagingOperationValues,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT:()=>NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS:()=>NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,NETHOSTCONNECTIONSUBTYPEVALUES_GSM:()=>`gsm`,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN:()=>NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN:()=>NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,NETHOSTCONNECTIONSUBTYPEVALUES_LTE:()=>`lte`,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NETHOSTCONNECTIONSUBTYPEVALUES_NR:()=>`nr`,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS:()=>NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,NETHOSTCONNECTIONTYPEVALUES_CELL:()=>NETHOSTCONNECTIONTYPEVALUES_CELL,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE:()=>NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN:()=>NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NETHOSTCONNECTIONTYPEVALUES_WIFI:()=>NETHOSTCONNECTIONTYPEVALUES_WIFI,NETHOSTCONNECTIONTYPEVALUES_WIRED:()=>NETHOSTCONNECTIONTYPEVALUES_WIRED,NETTRANSPORTVALUES_INPROC:()=>NETTRANSPORTVALUES_INPROC,NETTRANSPORTVALUES_IP:()=>`ip`,NETTRANSPORTVALUES_IP_TCP:()=>NETTRANSPORTVALUES_IP_TCP,NETTRANSPORTVALUES_IP_UDP:()=>NETTRANSPORTVALUES_IP_UDP,NETTRANSPORTVALUES_OTHER:()=>NETTRANSPORTVALUES_OTHER,NETTRANSPORTVALUES_PIPE:()=>NETTRANSPORTVALUES_PIPE,NETTRANSPORTVALUES_UNIX:()=>NETTRANSPORTVALUES_UNIX,NETWORK_TRANSPORT_VALUE_PIPE:()=>NETWORK_TRANSPORT_VALUE_PIPE,NETWORK_TRANSPORT_VALUE_QUIC:()=>NETWORK_TRANSPORT_VALUE_QUIC,NETWORK_TRANSPORT_VALUE_TCP:()=>`tcp`,NETWORK_TRANSPORT_VALUE_UDP:()=>`udp`,NETWORK_TRANSPORT_VALUE_UNIX:()=>NETWORK_TRANSPORT_VALUE_UNIX,NETWORK_TYPE_VALUE_IPV4:()=>NETWORK_TYPE_VALUE_IPV4,NETWORK_TYPE_VALUE_IPV6:()=>NETWORK_TYPE_VALUE_IPV6,NetHostConnectionSubtypeValues:()=>NetHostConnectionSubtypeValues,NetHostConnectionTypeValues:()=>NetHostConnectionTypeValues,NetTransportValues:()=>NetTransportValues,OSTYPEVALUES_AIX:()=>`aix`,OSTYPEVALUES_DARWIN:()=>OSTYPEVALUES_DARWIN,OSTYPEVALUES_DRAGONFLYBSD:()=>OSTYPEVALUES_DRAGONFLYBSD,OSTYPEVALUES_FREEBSD:()=>OSTYPEVALUES_FREEBSD,OSTYPEVALUES_HPUX:()=>OSTYPEVALUES_HPUX,OSTYPEVALUES_LINUX:()=>OSTYPEVALUES_LINUX,OSTYPEVALUES_NETBSD:()=>OSTYPEVALUES_NETBSD,OSTYPEVALUES_OPENBSD:()=>OSTYPEVALUES_OPENBSD,OSTYPEVALUES_SOLARIS:()=>OSTYPEVALUES_SOLARIS,OSTYPEVALUES_WINDOWS:()=>OSTYPEVALUES_WINDOWS,OSTYPEVALUES_Z_OS:()=>OSTYPEVALUES_Z_OS,OTEL_STATUS_CODE_VALUE_ERROR:()=>OTEL_STATUS_CODE_VALUE_ERROR,OTEL_STATUS_CODE_VALUE_OK:()=>`OK`,OsTypeValues:()=>OsTypeValues,RPCGRPCSTATUSCODEVALUES_ABORTED:()=>10,RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS:()=>6,RPCGRPCSTATUSCODEVALUES_CANCELLED:()=>1,RPCGRPCSTATUSCODEVALUES_DATA_LOSS:()=>15,RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED:()=>4,RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION:()=>9,RPCGRPCSTATUSCODEVALUES_INTERNAL:()=>13,RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT:()=>3,RPCGRPCSTATUSCODEVALUES_NOT_FOUND:()=>5,RPCGRPCSTATUSCODEVALUES_OK:()=>0,RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE:()=>11,RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED:()=>7,RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED:()=>8,RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED:()=>16,RPCGRPCSTATUSCODEVALUES_UNAVAILABLE:()=>14,RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED:()=>12,RPCGRPCSTATUSCODEVALUES_UNKNOWN:()=>2,RpcGrpcStatusCodeValues:()=>RpcGrpcStatusCodeValues,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET:()=>SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS:()=>SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ:()=>SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY:()=>SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY,SEMATTRS_AWS_DYNAMODB_COUNT:()=>SEMATTRS_AWS_DYNAMODB_COUNT,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE:()=>SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES:()=>SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES:()=>SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,SEMATTRS_AWS_DYNAMODB_INDEX_NAME:()=>SEMATTRS_AWS_DYNAMODB_INDEX_NAME,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS:()=>SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,SEMATTRS_AWS_DYNAMODB_LIMIT:()=>SEMATTRS_AWS_DYNAMODB_LIMIT,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES:()=>SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_PROJECTION:()=>SEMATTRS_AWS_DYNAMODB_PROJECTION,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY:()=>SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY:()=>SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT:()=>SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD:()=>SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD,SEMATTRS_AWS_DYNAMODB_SEGMENT:()=>SEMATTRS_AWS_DYNAMODB_SEGMENT,SEMATTRS_AWS_DYNAMODB_SELECT:()=>SEMATTRS_AWS_DYNAMODB_SELECT,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT:()=>SEMATTRS_AWS_DYNAMODB_TABLE_COUNT,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES:()=>SEMATTRS_AWS_DYNAMODB_TABLE_NAMES,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS:()=>SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS,SEMATTRS_AWS_LAMBDA_INVOKED_ARN:()=>SEMATTRS_AWS_LAMBDA_INVOKED_ARN,SEMATTRS_CODE_FILEPATH:()=>SEMATTRS_CODE_FILEPATH,SEMATTRS_CODE_FUNCTION:()=>SEMATTRS_CODE_FUNCTION,SEMATTRS_CODE_LINENO:()=>SEMATTRS_CODE_LINENO,SEMATTRS_CODE_NAMESPACE:()=>SEMATTRS_CODE_NAMESPACE,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL:()=>SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC:()=>SEMATTRS_DB_CASSANDRA_COORDINATOR_DC,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID:()=>SEMATTRS_DB_CASSANDRA_COORDINATOR_ID,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE:()=>SEMATTRS_DB_CASSANDRA_IDEMPOTENCE,SEMATTRS_DB_CASSANDRA_KEYSPACE:()=>SEMATTRS_DB_CASSANDRA_KEYSPACE,SEMATTRS_DB_CASSANDRA_PAGE_SIZE:()=>SEMATTRS_DB_CASSANDRA_PAGE_SIZE,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT:()=>SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,SEMATTRS_DB_CASSANDRA_TABLE:()=>SEMATTRS_DB_CASSANDRA_TABLE,SEMATTRS_DB_CONNECTION_STRING:()=>SEMATTRS_DB_CONNECTION_STRING,SEMATTRS_DB_HBASE_NAMESPACE:()=>SEMATTRS_DB_HBASE_NAMESPACE,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME:()=>SEMATTRS_DB_JDBC_DRIVER_CLASSNAME,SEMATTRS_DB_MONGODB_COLLECTION:()=>SEMATTRS_DB_MONGODB_COLLECTION,SEMATTRS_DB_MSSQL_INSTANCE_NAME:()=>SEMATTRS_DB_MSSQL_INSTANCE_NAME,SEMATTRS_DB_NAME:()=>SEMATTRS_DB_NAME,SEMATTRS_DB_OPERATION:()=>SEMATTRS_DB_OPERATION,SEMATTRS_DB_REDIS_DATABASE_INDEX:()=>SEMATTRS_DB_REDIS_DATABASE_INDEX,SEMATTRS_DB_SQL_TABLE:()=>SEMATTRS_DB_SQL_TABLE,SEMATTRS_DB_STATEMENT:()=>SEMATTRS_DB_STATEMENT,SEMATTRS_DB_SYSTEM:()=>SEMATTRS_DB_SYSTEM,SEMATTRS_DB_USER:()=>SEMATTRS_DB_USER,SEMATTRS_ENDUSER_ID:()=>SEMATTRS_ENDUSER_ID,SEMATTRS_ENDUSER_ROLE:()=>SEMATTRS_ENDUSER_ROLE,SEMATTRS_ENDUSER_SCOPE:()=>SEMATTRS_ENDUSER_SCOPE,SEMATTRS_EXCEPTION_ESCAPED:()=>SEMATTRS_EXCEPTION_ESCAPED,SEMATTRS_EXCEPTION_MESSAGE:()=>SEMATTRS_EXCEPTION_MESSAGE,SEMATTRS_EXCEPTION_STACKTRACE:()=>SEMATTRS_EXCEPTION_STACKTRACE,SEMATTRS_EXCEPTION_TYPE:()=>SEMATTRS_EXCEPTION_TYPE,SEMATTRS_FAAS_COLDSTART:()=>SEMATTRS_FAAS_COLDSTART,SEMATTRS_FAAS_CRON:()=>SEMATTRS_FAAS_CRON,SEMATTRS_FAAS_DOCUMENT_COLLECTION:()=>SEMATTRS_FAAS_DOCUMENT_COLLECTION,SEMATTRS_FAAS_DOCUMENT_NAME:()=>SEMATTRS_FAAS_DOCUMENT_NAME,SEMATTRS_FAAS_DOCUMENT_OPERATION:()=>SEMATTRS_FAAS_DOCUMENT_OPERATION,SEMATTRS_FAAS_DOCUMENT_TIME:()=>SEMATTRS_FAAS_DOCUMENT_TIME,SEMATTRS_FAAS_EXECUTION:()=>SEMATTRS_FAAS_EXECUTION,SEMATTRS_FAAS_INVOKED_NAME:()=>SEMATTRS_FAAS_INVOKED_NAME,SEMATTRS_FAAS_INVOKED_PROVIDER:()=>SEMATTRS_FAAS_INVOKED_PROVIDER,SEMATTRS_FAAS_INVOKED_REGION:()=>SEMATTRS_FAAS_INVOKED_REGION,SEMATTRS_FAAS_TIME:()=>SEMATTRS_FAAS_TIME,SEMATTRS_FAAS_TRIGGER:()=>SEMATTRS_FAAS_TRIGGER,SEMATTRS_HTTP_CLIENT_IP:()=>SEMATTRS_HTTP_CLIENT_IP,SEMATTRS_HTTP_FLAVOR:()=>SEMATTRS_HTTP_FLAVOR,SEMATTRS_HTTP_HOST:()=>SEMATTRS_HTTP_HOST,SEMATTRS_HTTP_METHOD:()=>SEMATTRS_HTTP_METHOD,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH:()=>SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED:()=>SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH:()=>SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED:()=>SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_ROUTE:()=>SEMATTRS_HTTP_ROUTE,SEMATTRS_HTTP_SCHEME:()=>SEMATTRS_HTTP_SCHEME,SEMATTRS_HTTP_SERVER_NAME:()=>SEMATTRS_HTTP_SERVER_NAME,SEMATTRS_HTTP_STATUS_CODE:()=>SEMATTRS_HTTP_STATUS_CODE,SEMATTRS_HTTP_TARGET:()=>SEMATTRS_HTTP_TARGET,SEMATTRS_HTTP_URL:()=>SEMATTRS_HTTP_URL,SEMATTRS_HTTP_USER_AGENT:()=>SEMATTRS_HTTP_USER_AGENT,SEMATTRS_MESSAGE_COMPRESSED_SIZE:()=>SEMATTRS_MESSAGE_COMPRESSED_SIZE,SEMATTRS_MESSAGE_ID:()=>SEMATTRS_MESSAGE_ID,SEMATTRS_MESSAGE_TYPE:()=>SEMATTRS_MESSAGE_TYPE,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE:()=>SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE,SEMATTRS_MESSAGING_CONSUMER_ID:()=>SEMATTRS_MESSAGING_CONSUMER_ID,SEMATTRS_MESSAGING_CONVERSATION_ID:()=>SEMATTRS_MESSAGING_CONVERSATION_ID,SEMATTRS_MESSAGING_DESTINATION:()=>SEMATTRS_MESSAGING_DESTINATION,SEMATTRS_MESSAGING_DESTINATION_KIND:()=>SEMATTRS_MESSAGING_DESTINATION_KIND,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID:()=>SEMATTRS_MESSAGING_KAFKA_CLIENT_ID,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP:()=>SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY:()=>SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY,SEMATTRS_MESSAGING_KAFKA_PARTITION:()=>SEMATTRS_MESSAGING_KAFKA_PARTITION,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE:()=>SEMATTRS_MESSAGING_KAFKA_TOMBSTONE,SEMATTRS_MESSAGING_MESSAGE_ID:()=>SEMATTRS_MESSAGING_MESSAGE_ID,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES:()=>SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES:()=>SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,SEMATTRS_MESSAGING_OPERATION:()=>SEMATTRS_MESSAGING_OPERATION,SEMATTRS_MESSAGING_PROTOCOL:()=>SEMATTRS_MESSAGING_PROTOCOL,SEMATTRS_MESSAGING_PROTOCOL_VERSION:()=>SEMATTRS_MESSAGING_PROTOCOL_VERSION,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY:()=>SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY,SEMATTRS_MESSAGING_SYSTEM:()=>SEMATTRS_MESSAGING_SYSTEM,SEMATTRS_MESSAGING_TEMP_DESTINATION:()=>SEMATTRS_MESSAGING_TEMP_DESTINATION,SEMATTRS_MESSAGING_URL:()=>SEMATTRS_MESSAGING_URL,SEMATTRS_NET_HOST_CARRIER_ICC:()=>SEMATTRS_NET_HOST_CARRIER_ICC,SEMATTRS_NET_HOST_CARRIER_MCC:()=>SEMATTRS_NET_HOST_CARRIER_MCC,SEMATTRS_NET_HOST_CARRIER_MNC:()=>SEMATTRS_NET_HOST_CARRIER_MNC,SEMATTRS_NET_HOST_CARRIER_NAME:()=>SEMATTRS_NET_HOST_CARRIER_NAME,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE:()=>SEMATTRS_NET_HOST_CONNECTION_SUBTYPE,SEMATTRS_NET_HOST_CONNECTION_TYPE:()=>SEMATTRS_NET_HOST_CONNECTION_TYPE,SEMATTRS_NET_HOST_IP:()=>SEMATTRS_NET_HOST_IP,SEMATTRS_NET_HOST_NAME:()=>SEMATTRS_NET_HOST_NAME,SEMATTRS_NET_HOST_PORT:()=>SEMATTRS_NET_HOST_PORT,SEMATTRS_NET_PEER_IP:()=>SEMATTRS_NET_PEER_IP,SEMATTRS_NET_PEER_NAME:()=>SEMATTRS_NET_PEER_NAME,SEMATTRS_NET_PEER_PORT:()=>SEMATTRS_NET_PEER_PORT,SEMATTRS_NET_TRANSPORT:()=>SEMATTRS_NET_TRANSPORT,SEMATTRS_PEER_SERVICE:()=>SEMATTRS_PEER_SERVICE,SEMATTRS_RPC_GRPC_STATUS_CODE:()=>SEMATTRS_RPC_GRPC_STATUS_CODE,SEMATTRS_RPC_JSONRPC_ERROR_CODE:()=>SEMATTRS_RPC_JSONRPC_ERROR_CODE,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE:()=>SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE,SEMATTRS_RPC_JSONRPC_REQUEST_ID:()=>SEMATTRS_RPC_JSONRPC_REQUEST_ID,SEMATTRS_RPC_JSONRPC_VERSION:()=>SEMATTRS_RPC_JSONRPC_VERSION,SEMATTRS_RPC_METHOD:()=>SEMATTRS_RPC_METHOD,SEMATTRS_RPC_SERVICE:()=>SEMATTRS_RPC_SERVICE,SEMATTRS_RPC_SYSTEM:()=>SEMATTRS_RPC_SYSTEM,SEMATTRS_THREAD_ID:()=>SEMATTRS_THREAD_ID,SEMATTRS_THREAD_NAME:()=>SEMATTRS_THREAD_NAME,SEMRESATTRS_AWS_ECS_CLUSTER_ARN:()=>SEMRESATTRS_AWS_ECS_CLUSTER_ARN,SEMRESATTRS_AWS_ECS_CONTAINER_ARN:()=>SEMRESATTRS_AWS_ECS_CONTAINER_ARN,SEMRESATTRS_AWS_ECS_LAUNCHTYPE:()=>SEMRESATTRS_AWS_ECS_LAUNCHTYPE,SEMRESATTRS_AWS_ECS_TASK_ARN:()=>SEMRESATTRS_AWS_ECS_TASK_ARN,SEMRESATTRS_AWS_ECS_TASK_FAMILY:()=>SEMRESATTRS_AWS_ECS_TASK_FAMILY,SEMRESATTRS_AWS_ECS_TASK_REVISION:()=>SEMRESATTRS_AWS_ECS_TASK_REVISION,SEMRESATTRS_AWS_EKS_CLUSTER_ARN:()=>SEMRESATTRS_AWS_EKS_CLUSTER_ARN,SEMRESATTRS_AWS_LOG_GROUP_ARNS:()=>SEMRESATTRS_AWS_LOG_GROUP_ARNS,SEMRESATTRS_AWS_LOG_GROUP_NAMES:()=>SEMRESATTRS_AWS_LOG_GROUP_NAMES,SEMRESATTRS_AWS_LOG_STREAM_ARNS:()=>SEMRESATTRS_AWS_LOG_STREAM_ARNS,SEMRESATTRS_AWS_LOG_STREAM_NAMES:()=>SEMRESATTRS_AWS_LOG_STREAM_NAMES,SEMRESATTRS_CLOUD_ACCOUNT_ID:()=>SEMRESATTRS_CLOUD_ACCOUNT_ID,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE:()=>SEMRESATTRS_CLOUD_AVAILABILITY_ZONE,SEMRESATTRS_CLOUD_PLATFORM:()=>SEMRESATTRS_CLOUD_PLATFORM,SEMRESATTRS_CLOUD_PROVIDER:()=>SEMRESATTRS_CLOUD_PROVIDER,SEMRESATTRS_CLOUD_REGION:()=>SEMRESATTRS_CLOUD_REGION,SEMRESATTRS_CONTAINER_ID:()=>SEMRESATTRS_CONTAINER_ID,SEMRESATTRS_CONTAINER_IMAGE_NAME:()=>SEMRESATTRS_CONTAINER_IMAGE_NAME,SEMRESATTRS_CONTAINER_IMAGE_TAG:()=>SEMRESATTRS_CONTAINER_IMAGE_TAG,SEMRESATTRS_CONTAINER_NAME:()=>SEMRESATTRS_CONTAINER_NAME,SEMRESATTRS_CONTAINER_RUNTIME:()=>SEMRESATTRS_CONTAINER_RUNTIME,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT:()=>SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,SEMRESATTRS_DEVICE_ID:()=>SEMRESATTRS_DEVICE_ID,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER:()=>SEMRESATTRS_DEVICE_MODEL_IDENTIFIER,SEMRESATTRS_DEVICE_MODEL_NAME:()=>SEMRESATTRS_DEVICE_MODEL_NAME,SEMRESATTRS_FAAS_ID:()=>SEMRESATTRS_FAAS_ID,SEMRESATTRS_FAAS_INSTANCE:()=>SEMRESATTRS_FAAS_INSTANCE,SEMRESATTRS_FAAS_MAX_MEMORY:()=>SEMRESATTRS_FAAS_MAX_MEMORY,SEMRESATTRS_FAAS_NAME:()=>SEMRESATTRS_FAAS_NAME,SEMRESATTRS_FAAS_VERSION:()=>SEMRESATTRS_FAAS_VERSION,SEMRESATTRS_HOST_ARCH:()=>SEMRESATTRS_HOST_ARCH,SEMRESATTRS_HOST_ID:()=>SEMRESATTRS_HOST_ID,SEMRESATTRS_HOST_IMAGE_ID:()=>SEMRESATTRS_HOST_IMAGE_ID,SEMRESATTRS_HOST_IMAGE_NAME:()=>SEMRESATTRS_HOST_IMAGE_NAME,SEMRESATTRS_HOST_IMAGE_VERSION:()=>SEMRESATTRS_HOST_IMAGE_VERSION,SEMRESATTRS_HOST_NAME:()=>SEMRESATTRS_HOST_NAME,SEMRESATTRS_HOST_TYPE:()=>SEMRESATTRS_HOST_TYPE,SEMRESATTRS_K8S_CLUSTER_NAME:()=>SEMRESATTRS_K8S_CLUSTER_NAME,SEMRESATTRS_K8S_CONTAINER_NAME:()=>SEMRESATTRS_K8S_CONTAINER_NAME,SEMRESATTRS_K8S_CRONJOB_NAME:()=>SEMRESATTRS_K8S_CRONJOB_NAME,SEMRESATTRS_K8S_CRONJOB_UID:()=>SEMRESATTRS_K8S_CRONJOB_UID,SEMRESATTRS_K8S_DAEMONSET_NAME:()=>SEMRESATTRS_K8S_DAEMONSET_NAME,SEMRESATTRS_K8S_DAEMONSET_UID:()=>SEMRESATTRS_K8S_DAEMONSET_UID,SEMRESATTRS_K8S_DEPLOYMENT_NAME:()=>SEMRESATTRS_K8S_DEPLOYMENT_NAME,SEMRESATTRS_K8S_DEPLOYMENT_UID:()=>SEMRESATTRS_K8S_DEPLOYMENT_UID,SEMRESATTRS_K8S_JOB_NAME:()=>SEMRESATTRS_K8S_JOB_NAME,SEMRESATTRS_K8S_JOB_UID:()=>SEMRESATTRS_K8S_JOB_UID,SEMRESATTRS_K8S_NAMESPACE_NAME:()=>SEMRESATTRS_K8S_NAMESPACE_NAME,SEMRESATTRS_K8S_NODE_NAME:()=>SEMRESATTRS_K8S_NODE_NAME,SEMRESATTRS_K8S_NODE_UID:()=>SEMRESATTRS_K8S_NODE_UID,SEMRESATTRS_K8S_POD_NAME:()=>SEMRESATTRS_K8S_POD_NAME,SEMRESATTRS_K8S_POD_UID:()=>SEMRESATTRS_K8S_POD_UID,SEMRESATTRS_K8S_REPLICASET_NAME:()=>SEMRESATTRS_K8S_REPLICASET_NAME,SEMRESATTRS_K8S_REPLICASET_UID:()=>SEMRESATTRS_K8S_REPLICASET_UID,SEMRESATTRS_K8S_STATEFULSET_NAME:()=>SEMRESATTRS_K8S_STATEFULSET_NAME,SEMRESATTRS_K8S_STATEFULSET_UID:()=>SEMRESATTRS_K8S_STATEFULSET_UID,SEMRESATTRS_OS_DESCRIPTION:()=>SEMRESATTRS_OS_DESCRIPTION,SEMRESATTRS_OS_NAME:()=>SEMRESATTRS_OS_NAME,SEMRESATTRS_OS_TYPE:()=>SEMRESATTRS_OS_TYPE,SEMRESATTRS_OS_VERSION:()=>SEMRESATTRS_OS_VERSION,SEMRESATTRS_PROCESS_COMMAND:()=>SEMRESATTRS_PROCESS_COMMAND,SEMRESATTRS_PROCESS_COMMAND_ARGS:()=>SEMRESATTRS_PROCESS_COMMAND_ARGS,SEMRESATTRS_PROCESS_COMMAND_LINE:()=>SEMRESATTRS_PROCESS_COMMAND_LINE,SEMRESATTRS_PROCESS_EXECUTABLE_NAME:()=>SEMRESATTRS_PROCESS_EXECUTABLE_NAME,SEMRESATTRS_PROCESS_EXECUTABLE_PATH:()=>SEMRESATTRS_PROCESS_EXECUTABLE_PATH,SEMRESATTRS_PROCESS_OWNER:()=>SEMRESATTRS_PROCESS_OWNER,SEMRESATTRS_PROCESS_PID:()=>SEMRESATTRS_PROCESS_PID,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION:()=>SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION,SEMRESATTRS_PROCESS_RUNTIME_NAME:()=>SEMRESATTRS_PROCESS_RUNTIME_NAME,SEMRESATTRS_PROCESS_RUNTIME_VERSION:()=>SEMRESATTRS_PROCESS_RUNTIME_VERSION,SEMRESATTRS_SERVICE_INSTANCE_ID:()=>SEMRESATTRS_SERVICE_INSTANCE_ID,SEMRESATTRS_SERVICE_NAME:()=>SEMRESATTRS_SERVICE_NAME,SEMRESATTRS_SERVICE_NAMESPACE:()=>SEMRESATTRS_SERVICE_NAMESPACE,SEMRESATTRS_SERVICE_VERSION:()=>SEMRESATTRS_SERVICE_VERSION,SEMRESATTRS_TELEMETRY_AUTO_VERSION:()=>SEMRESATTRS_TELEMETRY_AUTO_VERSION,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE:()=>SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_NAME:()=>SEMRESATTRS_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_VERSION:()=>SEMRESATTRS_TELEMETRY_SDK_VERSION,SEMRESATTRS_WEBENGINE_DESCRIPTION:()=>SEMRESATTRS_WEBENGINE_DESCRIPTION,SEMRESATTRS_WEBENGINE_NAME:()=>SEMRESATTRS_WEBENGINE_NAME,SEMRESATTRS_WEBENGINE_VERSION:()=>SEMRESATTRS_WEBENGINE_VERSION,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN:()=>SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE:()=>SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT:()=>SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT,SIGNALR_TRANSPORT_VALUE_LONG_POLLING:()=>SIGNALR_TRANSPORT_VALUE_LONG_POLLING,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS:()=>SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS:()=>SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS,SemanticAttributes:()=>SemanticAttributes,SemanticResourceAttributes:()=>SemanticResourceAttributes,TELEMETRYSDKLANGUAGEVALUES_CPP:()=>`cpp`,TELEMETRYSDKLANGUAGEVALUES_DOTNET:()=>TELEMETRYSDKLANGUAGEVALUES_DOTNET,TELEMETRYSDKLANGUAGEVALUES_ERLANG:()=>TELEMETRYSDKLANGUAGEVALUES_ERLANG,TELEMETRYSDKLANGUAGEVALUES_GO:()=>`go`,TELEMETRYSDKLANGUAGEVALUES_JAVA:()=>TELEMETRYSDKLANGUAGEVALUES_JAVA,TELEMETRYSDKLANGUAGEVALUES_NODEJS:()=>TELEMETRYSDKLANGUAGEVALUES_NODEJS,TELEMETRYSDKLANGUAGEVALUES_PHP:()=>`php`,TELEMETRYSDKLANGUAGEVALUES_PYTHON:()=>TELEMETRYSDKLANGUAGEVALUES_PYTHON,TELEMETRYSDKLANGUAGEVALUES_RUBY:()=>TELEMETRYSDKLANGUAGEVALUES_RUBY,TELEMETRYSDKLANGUAGEVALUES_WEBJS:()=>TELEMETRYSDKLANGUAGEVALUES_WEBJS,TELEMETRY_SDK_LANGUAGE_VALUE_CPP:()=>`cpp`,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET:()=>TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG:()=>TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG,TELEMETRY_SDK_LANGUAGE_VALUE_GO:()=>`go`,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA:()=>TELEMETRY_SDK_LANGUAGE_VALUE_JAVA,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS:()=>TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,TELEMETRY_SDK_LANGUAGE_VALUE_PHP:()=>`php`,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON:()=>TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY:()=>TELEMETRY_SDK_LANGUAGE_VALUE_RUBY,TELEMETRY_SDK_LANGUAGE_VALUE_RUST:()=>TELEMETRY_SDK_LANGUAGE_VALUE_RUST,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT:()=>TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS:()=>TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,TelemetrySdkLanguageValues:()=>TelemetrySdkLanguageValues}),init_esm$1=__esmMin((()=>{init_trace(),init_resource(),init_stable_attributes(),init_stable_metrics(),init_stable_events()})),require_semconv$7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_PROCESS_RUNTIME_NAME=void 0,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`})),require_sdk_info$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SDK_INFO=void 0;let t=require_version$6(),s=(init_esm$1(),__toCommonJS(esm_exports$1)),g=require_semconv$7();e.SDK_INFO={[s.ATTR_TELEMETRY_SDK_NAME]:`opentelemetry`,[g.ATTR_PROCESS_RUNTIME_NAME]:`node`,[s.ATTR_TELEMETRY_SDK_LANGUAGE]:s.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[s.ATTR_TELEMETRY_SDK_VERSION]:t.VERSION}})),require_node$11=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.otperformance=e.SDK_INFO=e._globalThis=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=void 0;var t=require_environment$3();Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}});var s=require_globalThis$3();Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return s._globalThis}});var g=require_sdk_info$3();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return g.SDK_INFO}}),e.otperformance=performance})),require_platform$11=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getNumberFromEnv=e.getStringFromEnv=e.getBooleanFromEnv=e.otperformance=e._globalThis=e.SDK_INFO=void 0;var t=require_node$11();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return t.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return t._globalThis}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return t.otperformance}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}})})),require_time$4=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.addHrTimes=e.isTimeInput=e.isTimeInputHrTime=e.hrTimeToMicroseconds=e.hrTimeToMilliseconds=e.hrTimeToNanoseconds=e.hrTimeToTimeStamp=e.hrTimeDuration=e.timeInputToHrTime=e.hrTime=e.getTimeOrigin=e.millisToHrTime=void 0;let t=require_platform$11(),s=9,g=10**6,S=10**9;function w(e){let t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*g)]}e.millisToHrTime=w;function E(){return t.otperformance.timeOrigin}e.getTimeOrigin=E;function D(e){return ee(w(t.otperformance.timeOrigin),w(typeof e==`number`?e:t.otperformance.now()))}e.hrTime=D;function O(e){if(H(e))return e;if(typeof e==`number`)return e<t.otperformance.timeOrigin?D(e):w(e);if(e instanceof Date)return w(e.getTime());throw TypeError(`Invalid input type`)}e.timeInputToHrTime=O;function k(e,t){let s=t[0]-e[0],g=t[1]-e[1];return g<0&&(--s,g+=S),[s,g]}e.hrTimeDuration=k;function j(e){let t=9,s=`${`0`.repeat(9)}${e[1]}Z`,g=s.substring(s.length-9-1);return new Date(e[0]*1e3).toISOString().replace(`000Z`,g)}e.hrTimeToTimeStamp=j;function F(e){return e[0]*S+e[1]}e.hrTimeToNanoseconds=F;function L(e){return e[0]*1e3+e[1]/1e6}e.hrTimeToMilliseconds=L;function B(e){return e[0]*1e6+e[1]/1e3}e.hrTimeToMicroseconds=B;function H(e){return Array.isArray(e)&&e.length===2&&typeof e[0]==`number`&&typeof e[1]==`number`}e.isTimeInputHrTime=H;function q(e){return H(e)||typeof e==`number`||e instanceof Date}e.isTimeInput=q;function ee(e,t){let s=[e[0]+t[0],e[1]+t[1]];return s[1]>=S&&(s[1]-=S,s[0]+=1),s}e.addHrTimes=ee})),require_timer_util$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=void 0;function t(e){typeof e!=`number`&&e.unref()}e.unrefTimer=t})),require_ExportResult$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExportResultCode=void 0,(function(e){e[e.SUCCESS=0]=`SUCCESS`,e[e.FAILED=1]=`FAILED`})(e.ExportResultCode||={})})),require_composite$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CompositePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));e.CompositePropagator=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>typeof e.fields==`function`?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,s,g){for(let S of this._propagators)try{S.inject(e,s,g)}catch(e){t.diag.warn(`Failed to inject with ${S.constructor.name}. Err: ${e.message}`)}}extract(e,s,g){return this._propagators.reduce((e,S)=>{try{return S.extract(e,s,g)}catch(e){t.diag.warn(`Failed to extract with ${S.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}})),require_validators$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateValue=e.validateKey=void 0;let t=`[_0-9a-z-*/]`,s=`[a-z]${t}{0,255}`,g=`[a-z0-9]${t}{0,240}@[a-z]${t}{0,13}`,S=RegExp(`^(?:${s}|${g})$`),w=/^[ -~]{0,255}[!-~]$/,E=/,|=/;function D(e){return S.test(e)}e.validateKey=D;function O(e){return w.test(e)&&!E.test(e)}e.validateValue=O})),require_TraceState$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceState=void 0;let t=require_validators$3(),s=32,g=512,S=`,`,w=`=`;e.TraceState=class e{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){let s=this._clone();return s._internalState.has(e)&&s._internalState.delete(e),s._internalState.set(e,t),s}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+`=`+this.get(t)),e),[]).join(`,`)}_parse(e){e.length>512||(this._internalState=e.split(`,`).reverse().reduce((e,s)=>{let g=s.trim(),S=g.indexOf(`=`);if(S!==-1){let w=g.slice(0,S),E=g.slice(S+1,s.length);(0,t.validateKey)(w)&&(0,t.validateValue)(E)&&e.set(w,E)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let t=new e;return t._internalState=new Map(this._internalState),t}}})),require_W3CTraceContextPropagator$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CTraceContextPropagator=e.parseTraceParent=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$3(),g=require_TraceState$3();e.TRACE_PARENT_HEADER=`traceparent`,e.TRACE_STATE_HEADER=`tracestate`;let S=`00`,w=RegExp(`^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$`);function E(e){let t=w.exec(e);return!t||t[1]===`00`&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}}e.parseTraceParent=E,e.W3CTraceContextPropagator=class{inject(g,S,w){let E=t.trace.getSpanContext(g);if(!E||(0,s.isTracingSuppressed)(g)||!(0,t.isSpanContextValid)(E))return;let D=`00-${E.traceId}-${E.spanId}-0${Number(E.traceFlags||t.TraceFlags.NONE).toString(16)}`;w.set(S,e.TRACE_PARENT_HEADER,D),E.traceState&&w.set(S,e.TRACE_STATE_HEADER,E.traceState.serialize())}extract(s,S,w){let D=w.get(S,e.TRACE_PARENT_HEADER);if(!D)return s;let O=Array.isArray(D)?D[0]:D;if(typeof O!=`string`)return s;let k=E(O);if(!k)return s;k.isRemote=!0;let j=w.get(S,e.TRACE_STATE_HEADER);if(j){let e=Array.isArray(j)?j.join(`,`):j;k.traceState=new g.TraceState(typeof e==`string`?e:void 0)}return t.trace.setSpanContext(s,k)}fields(){return[e.TRACE_PARENT_HEADER,e.TRACE_STATE_HEADER]}}})),require_rpc_metadata$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRPCMetadata=e.deleteRPCMetadata=e.setRPCMetadata=e.RPCType=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key RPC_METADATA`);(function(e){e.HTTP=`http`})(e.RPCType||={});function s(e,s){return e.setValue(t,s)}e.setRPCMetadata=s;function g(e){return e.deleteValue(t)}e.deleteRPCMetadata=g;function S(e){return e.getValue(t)}e.getRPCMetadata=S})),require_lodash_merge$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isPlainObject=void 0;let t=`[object Object]`,s=`[object Null]`,g=`[object Undefined]`,S=Function.prototype.toString,w=S.call(Object),E=Object.getPrototypeOf,D=Object.prototype,O=D.hasOwnProperty,k=Symbol?Symbol.toStringTag:void 0,j=D.toString;function F(e){if(!L(e)||B(e)!==`[object Object]`)return!1;let t=E(e);if(t===null)return!0;let s=O.call(t,`constructor`)&&t.constructor;return typeof s==`function`&&s instanceof s&&S.call(s)===w}e.isPlainObject=F;function L(e){return typeof e==`object`&&!!e}function B(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:k&&k in Object(e)?H(e):q(e)}function H(e){let t=O.call(e,k),s=e[k],g=!1;try{e[k]=void 0,g=!0}catch{}let S=j.call(e);return g&&(t?e[k]=s:delete e[k]),S}function q(e){return j.call(e)}})),require_merge$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.merge=void 0;let t=require_lodash_merge$3(),s=20;function g(...e){let t=e.shift(),s=new WeakMap;for(;e.length>0;)t=w(t,e.shift(),0,s);return t}e.merge=g;function S(e){return D(e)?e.slice():e}function w(e,t,s=0,g){let L;if(!(s>20)){if(s++,j(e)||j(t)||O(t))L=S(t);else if(D(e)){if(L=e.slice(),D(t))for(let e=0,s=t.length;e<s;e++)L.push(S(t[e]));else if(k(t)){let e=Object.keys(t);for(let s=0,g=e.length;s<g;s++){let g=e[s];g===`__proto__`||g===`constructor`||g===`prototype`||(L[g]=S(t[g]))}}}else if(k(e))if(k(t)){if(!F(e,t))return t;L=Object.assign({},e);let S=Object.keys(t);for(let D=0,O=S.length;D<O;D++){let O=S[D];if(O===`__proto__`||O===`constructor`||O===`prototype`)continue;let F=t[O];if(j(F))F===void 0?delete L[O]:L[O]=F;else{let S=L[O],D=F;if(E(e,O,g)||E(t,O,g))delete L[O];else{if(k(S)&&k(D)){let s=g.get(S)||[],w=g.get(D)||[];s.push({obj:e,key:O}),w.push({obj:t,key:O}),g.set(S,s),g.set(D,w)}L[O]=w(L[O],F,s,g)}}}}else L=t;return L}}function E(e,t,s){let g=s.get(e[t])||[];for(let s=0,S=g.length;s<S;s++){let S=g[s];if(S.key===t&&S.obj===e)return!0}return!1}function D(e){return Array.isArray(e)}function O(e){return typeof e==`function`}function k(e){return!j(e)&&!D(e)&&!O(e)&&typeof e==`object`}function j(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e===void 0||e instanceof Date||e instanceof RegExp||e===null}function F(e,s){return!(!(0,t.isPlainObject)(e)||!(0,t.isPlainObject)(s))}})),require_timeout$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callWithTimeout=e.TimeoutError=void 0;var t=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=t;function s(e,s){let g,S=new Promise(function(e,S){g=setTimeout(function(){S(new t(`Operation timed out.`))},s)});return Promise.race([e,S]).then(e=>(clearTimeout(g),e),e=>{throw clearTimeout(g),e})}e.callWithTimeout=s})),require_url$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isUrlIgnored=e.urlMatches=void 0;function t(e,t){return typeof t==`string`?e===t:!!e.match(t)}e.urlMatches=t;function s(e,s){if(!s)return!1;for(let g of s)if(t(e,g))return!0;return!1}e.isUrlIgnored=s})),require_promise$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Deferred=void 0,e.Deferred=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}})),require_callback$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BindOnceFuture=void 0;let t=require_promise$3();e.BindOnceFuture=class{_isCalled=!1;_deferred=new t.Deferred;_callback;_that;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}})),require_configuration$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.diagLogLevelFromString=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s={ALL:t.DiagLogLevel.ALL,VERBOSE:t.DiagLogLevel.VERBOSE,DEBUG:t.DiagLogLevel.DEBUG,INFO:t.DiagLogLevel.INFO,WARN:t.DiagLogLevel.WARN,ERROR:t.DiagLogLevel.ERROR,NONE:t.DiagLogLevel.NONE};function g(e){return e==null?void 0:s[e.toUpperCase()]??(t.diag.warn(`Unknown log level "${e}", expected one of ${Object.keys(s)}, using default`),t.DiagLogLevel.INFO)}e.diagLogLevelFromString=g})),require_exporter$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._export=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$3();function g(e,g){return new Promise(S=>{t.context.with((0,s.suppressTracing)(t.context.active()),()=>{e.export(g,S)})})}e._export=g})),require_src$14=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.internal=e.diagLogLevelFromString=e.BindOnceFuture=e.urlMatches=e.isUrlIgnored=e.callWithTimeout=e.TimeoutError=e.merge=e.TraceState=e.unsuppressTracing=e.suppressTracing=e.isTracingSuppressed=e.setRPCMetadata=e.getRPCMetadata=e.deleteRPCMetadata=e.RPCType=e.parseTraceParent=e.W3CTraceContextPropagator=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=e.CompositePropagator=e.otperformance=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e._globalThis=e.SDK_INFO=e.parseKeyPairsIntoRecord=e.ExportResultCode=e.unrefTimer=e.timeInputToHrTime=e.millisToHrTime=e.isTimeInputHrTime=e.isTimeInput=e.hrTimeToTimeStamp=e.hrTimeToNanoseconds=e.hrTimeToMilliseconds=e.hrTimeToMicroseconds=e.hrTimeDuration=e.hrTime=e.getTimeOrigin=e.addHrTimes=e.loggingErrorHandler=e.setGlobalErrorHandler=e.globalErrorHandler=e.sanitizeAttributes=e.isAttributeValue=e.AnchoredClock=e.W3CBaggagePropagator=void 0;var t=require_W3CBaggagePropagator$3();Object.defineProperty(e,`W3CBaggagePropagator`,{enumerable:!0,get:function(){return t.W3CBaggagePropagator}});var s=require_anchored_clock$3();Object.defineProperty(e,`AnchoredClock`,{enumerable:!0,get:function(){return s.AnchoredClock}});var g=require_attributes$3();Object.defineProperty(e,`isAttributeValue`,{enumerable:!0,get:function(){return g.isAttributeValue}}),Object.defineProperty(e,`sanitizeAttributes`,{enumerable:!0,get:function(){return g.sanitizeAttributes}});var S=require_global_error_handler$3();Object.defineProperty(e,`globalErrorHandler`,{enumerable:!0,get:function(){return S.globalErrorHandler}}),Object.defineProperty(e,`setGlobalErrorHandler`,{enumerable:!0,get:function(){return S.setGlobalErrorHandler}});var w=require_logging_error_handler$3();Object.defineProperty(e,`loggingErrorHandler`,{enumerable:!0,get:function(){return w.loggingErrorHandler}});var E=require_time$4();Object.defineProperty(e,`addHrTimes`,{enumerable:!0,get:function(){return E.addHrTimes}}),Object.defineProperty(e,`getTimeOrigin`,{enumerable:!0,get:function(){return E.getTimeOrigin}}),Object.defineProperty(e,`hrTime`,{enumerable:!0,get:function(){return E.hrTime}}),Object.defineProperty(e,`hrTimeDuration`,{enumerable:!0,get:function(){return E.hrTimeDuration}}),Object.defineProperty(e,`hrTimeToMicroseconds`,{enumerable:!0,get:function(){return E.hrTimeToMicroseconds}}),Object.defineProperty(e,`hrTimeToMilliseconds`,{enumerable:!0,get:function(){return E.hrTimeToMilliseconds}}),Object.defineProperty(e,`hrTimeToNanoseconds`,{enumerable:!0,get:function(){return E.hrTimeToNanoseconds}}),Object.defineProperty(e,`hrTimeToTimeStamp`,{enumerable:!0,get:function(){return E.hrTimeToTimeStamp}}),Object.defineProperty(e,`isTimeInput`,{enumerable:!0,get:function(){return E.isTimeInput}}),Object.defineProperty(e,`isTimeInputHrTime`,{enumerable:!0,get:function(){return E.isTimeInputHrTime}}),Object.defineProperty(e,`millisToHrTime`,{enumerable:!0,get:function(){return E.millisToHrTime}}),Object.defineProperty(e,`timeInputToHrTime`,{enumerable:!0,get:function(){return E.timeInputToHrTime}});var D=require_timer_util$3();Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return D.unrefTimer}});var O=require_ExportResult$3();Object.defineProperty(e,`ExportResultCode`,{enumerable:!0,get:function(){return O.ExportResultCode}});var k=require_utils$16();Object.defineProperty(e,`parseKeyPairsIntoRecord`,{enumerable:!0,get:function(){return k.parseKeyPairsIntoRecord}});var j=require_platform$11();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return j.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return j._globalThis}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return j.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return j.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return j.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return j.getStringListFromEnv}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return j.otperformance}});var F=require_composite$3();Object.defineProperty(e,`CompositePropagator`,{enumerable:!0,get:function(){return F.CompositePropagator}});var L=require_W3CTraceContextPropagator$3();Object.defineProperty(e,`TRACE_PARENT_HEADER`,{enumerable:!0,get:function(){return L.TRACE_PARENT_HEADER}}),Object.defineProperty(e,`TRACE_STATE_HEADER`,{enumerable:!0,get:function(){return L.TRACE_STATE_HEADER}}),Object.defineProperty(e,`W3CTraceContextPropagator`,{enumerable:!0,get:function(){return L.W3CTraceContextPropagator}}),Object.defineProperty(e,`parseTraceParent`,{enumerable:!0,get:function(){return L.parseTraceParent}});var B=require_rpc_metadata$3();Object.defineProperty(e,`RPCType`,{enumerable:!0,get:function(){return B.RPCType}}),Object.defineProperty(e,`deleteRPCMetadata`,{enumerable:!0,get:function(){return B.deleteRPCMetadata}}),Object.defineProperty(e,`getRPCMetadata`,{enumerable:!0,get:function(){return B.getRPCMetadata}}),Object.defineProperty(e,`setRPCMetadata`,{enumerable:!0,get:function(){return B.setRPCMetadata}});var H=require_suppress_tracing$3();Object.defineProperty(e,`isTracingSuppressed`,{enumerable:!0,get:function(){return H.isTracingSuppressed}}),Object.defineProperty(e,`suppressTracing`,{enumerable:!0,get:function(){return H.suppressTracing}}),Object.defineProperty(e,`unsuppressTracing`,{enumerable:!0,get:function(){return H.unsuppressTracing}});var q=require_TraceState$3();Object.defineProperty(e,`TraceState`,{enumerable:!0,get:function(){return q.TraceState}});var ee=require_merge$3();Object.defineProperty(e,`merge`,{enumerable:!0,get:function(){return ee.merge}});var J=require_timeout$3();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return J.TimeoutError}}),Object.defineProperty(e,`callWithTimeout`,{enumerable:!0,get:function(){return J.callWithTimeout}});var Y=require_url$3();Object.defineProperty(e,`isUrlIgnored`,{enumerable:!0,get:function(){return Y.isUrlIgnored}}),Object.defineProperty(e,`urlMatches`,{enumerable:!0,get:function(){return Y.urlMatches}});var te=require_callback$3();Object.defineProperty(e,`BindOnceFuture`,{enumerable:!0,get:function(){return te.BindOnceFuture}});var ne=require_configuration$3();Object.defineProperty(e,`diagLogLevelFromString`,{enumerable:!0,get:function(){return ne.diagLogLevelFromString}}),e.internal={_export:require_exporter$3()._export}})),require_aspromise=__commonJSMin$2(((e,t)=>{t.exports=s;function s(e,t){for(var s=Array(arguments.length-1),g=0,S=2,w=!0;S<arguments.length;)s[g++]=arguments[S++];return new Promise(function(S,E){s[g]=function(e){if(w)if(w=!1,e)E(e);else{for(var t=Array(arguments.length-1),s=0;s<t.length;)t[s++]=arguments[s];S.apply(null,t)}};try{e.apply(t||null,s)}catch(e){w&&(w=!1,E(e))}})}})),require_base64=__commonJSMin$2((e=>{var t=e;t.length=function(e){var t=e.length;if(!t)return 0;for(var s=0;--t%4>1&&e.charAt(t)===`=`;)++s;return Math.ceil(e.length*3)/4-s};for(var s=Array(64),g=Array(123),S=0;S<64;)g[s[S]=S<26?S+65:S<52?S+71:S<62?S-4:S-59|43]=S++;t.encode=function(e,t,g){for(var S=null,w=[],E=0,D=0,O;t<g;){var k=e[t++];switch(D){case 0:w[E++]=s[k>>2],O=(k&3)<<4,D=1;break;case 1:w[E++]=s[O|k>>4],O=(k&15)<<2,D=2;break;case 2:w[E++]=s[O|k>>6],w[E++]=s[k&63],D=0;break}E>8191&&((S||=[]).push(String.fromCharCode.apply(String,w)),E=0)}return D&&(w[E++]=s[O],w[E++]=61,D===1&&(w[E++]=61)),S?(E&&S.push(String.fromCharCode.apply(String,w.slice(0,E))),S.join(``)):String.fromCharCode.apply(String,w.slice(0,E))};var w=`invalid encoding`;t.decode=function(e,t,s){for(var S=s,E=0,D,O=0;O<e.length;){var k=e.charCodeAt(O++);if(k===61&&E>1)break;if((k=g[k])===void 0)throw Error(w);switch(E){case 0:D=k,E=1;break;case 1:t[s++]=D<<2|(k&48)>>4,D=k,E=2;break;case 2:t[s++]=(D&15)<<4|(k&60)>>2,D=k,E=3;break;case 3:t[s++]=(D&3)<<6|k,E=0;break}}if(E===1)throw Error(w);return s-S},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}})),require_eventemitter=__commonJSMin$2(((e,t)=>{t.exports=s;function s(){this._listeners={}}s.prototype.on=function(e,t,s){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:s||this}),this},s.prototype.off=function(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=[];else for(var s=this._listeners[e],g=0;g<s.length;)s[g].fn===t?s.splice(g,1):++g;return this},s.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var s=[],g=1;g<arguments.length;)s.push(arguments[g++]);for(g=0;g<t.length;)t[g].fn.apply(t[g++].ctx,s)}return this}})),require_float=__commonJSMin$2(((e,t)=>{t.exports=s(s);function s(e){return typeof Float32Array<`u`?(function(){var t=new Float32Array([-0]),s=new Uint8Array(t.buffer),g=s[3]===128;function S(e,g,S){t[0]=e,g[S]=s[0],g[S+1]=s[1],g[S+2]=s[2],g[S+3]=s[3]}function w(e,g,S){t[0]=e,g[S]=s[3],g[S+1]=s[2],g[S+2]=s[1],g[S+3]=s[0]}e.writeFloatLE=g?S:w,e.writeFloatBE=g?w:S;function E(e,g){return s[0]=e[g],s[1]=e[g+1],s[2]=e[g+2],s[3]=e[g+3],t[0]}function D(e,g){return s[3]=e[g],s[2]=e[g+1],s[1]=e[g+2],s[0]=e[g+3],t[0]}e.readFloatLE=g?E:D,e.readFloatBE=g?D:E})():(function(){function t(e,t,s,g){var S=t<0?1:0;if(S&&(t=-t),t===0)e(1/t>0?0:2147483648,s,g);else if(isNaN(t))e(2143289344,s,g);else if(t>34028234663852886e22)e((S<<31|2139095040)>>>0,s,g);else if(t<11754943508222875e-54)e((S<<31|Math.round(t/1401298464324817e-60))>>>0,s,g);else{var w=Math.floor(Math.log(t)/Math.LN2),E=Math.round(t*2**-w*8388608)&8388607;e((S<<31|w+127<<23|E)>>>0,s,g)}}e.writeFloatLE=t.bind(null,g),e.writeFloatBE=t.bind(null,S);function s(e,t,s){var g=e(t,s),S=(g>>31)*2+1,w=g>>>23&255,E=g&8388607;return w===255?E?NaN:S*(1/0):w===0?S*1401298464324817e-60*E:S*2**(w-150)*(E+8388608)}e.readFloatLE=s.bind(null,w),e.readFloatBE=s.bind(null,E)})(),typeof Float64Array<`u`?(function(){var t=new Float64Array([-0]),s=new Uint8Array(t.buffer),g=s[7]===128;function S(e,g,S){t[0]=e,g[S]=s[0],g[S+1]=s[1],g[S+2]=s[2],g[S+3]=s[3],g[S+4]=s[4],g[S+5]=s[5],g[S+6]=s[6],g[S+7]=s[7]}function w(e,g,S){t[0]=e,g[S]=s[7],g[S+1]=s[6],g[S+2]=s[5],g[S+3]=s[4],g[S+4]=s[3],g[S+5]=s[2],g[S+6]=s[1],g[S+7]=s[0]}e.writeDoubleLE=g?S:w,e.writeDoubleBE=g?w:S;function E(e,g){return s[0]=e[g],s[1]=e[g+1],s[2]=e[g+2],s[3]=e[g+3],s[4]=e[g+4],s[5]=e[g+5],s[6]=e[g+6],s[7]=e[g+7],t[0]}function D(e,g){return s[7]=e[g],s[6]=e[g+1],s[5]=e[g+2],s[4]=e[g+3],s[3]=e[g+4],s[2]=e[g+5],s[1]=e[g+6],s[0]=e[g+7],t[0]}e.readDoubleLE=g?E:D,e.readDoubleBE=g?D:E})():(function(){function t(e,t,s,g,S,w){var E=g<0?1:0;if(E&&(g=-g),g===0)e(0,S,w+t),e(1/g>0?0:2147483648,S,w+s);else if(isNaN(g))e(0,S,w+t),e(2146959360,S,w+s);else if(g>17976931348623157e292)e(0,S,w+t),e((E<<31|2146435072)>>>0,S,w+s);else{var D;if(g<22250738585072014e-324)D=g/5e-324,e(D>>>0,S,w+t),e((E<<31|D/4294967296)>>>0,S,w+s);else{var O=Math.floor(Math.log(g)/Math.LN2);O===1024&&(O=1023),D=g*2**-O,e(D*4503599627370496>>>0,S,w+t),e((E<<31|O+1023<<20|D*1048576&1048575)>>>0,S,w+s)}}}e.writeDoubleLE=t.bind(null,g,0,4),e.writeDoubleBE=t.bind(null,S,4,0);function s(e,t,s,g,S){var w=e(g,S+t),E=e(g,S+s),D=(E>>31)*2+1,O=E>>>20&2047,k=4294967296*(E&1048575)+w;return O===2047?k?NaN:D*(1/0):O===0?D*5e-324*k:D*2**(O-1075)*(k+4503599627370496)}e.readDoubleLE=s.bind(null,w,0,4),e.readDoubleBE=s.bind(null,E,4,0)})(),e}function g(e,t,s){t[s]=e&255,t[s+1]=e>>>8&255,t[s+2]=e>>>16&255,t[s+3]=e>>>24}function S(e,t,s){t[s]=e>>>24,t[s+1]=e>>>16&255,t[s+2]=e>>>8&255,t[s+3]=e&255}function w(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function E(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}})),require_inquire=__commonJSMin$2(((exports,module)=>{module.exports=inquire;function inquire(moduleName){try{var mod=eval(`quire`.replace(/^/,`re`))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch{}return null}})),require_utf8=__commonJSMin$2((e=>{var t=e;t.length=function(e){for(var t=0,s=0,g=0;g<e.length;++g)s=e.charCodeAt(g),s<128?t+=1:s<2048?t+=2:(s&64512)==55296&&(e.charCodeAt(g+1)&64512)==56320?(++g,t+=4):t+=3;return t},t.read=function(e,t,s){if(s-t<1)return``;for(var g=null,S=[],w=0,E;t<s;)E=e[t++],E<128?S[w++]=E:E>191&&E<224?S[w++]=(E&31)<<6|e[t++]&63:E>239&&E<365?(E=((E&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,S[w++]=55296+(E>>10),S[w++]=56320+(E&1023)):S[w++]=(E&15)<<12|(e[t++]&63)<<6|e[t++]&63,w>8191&&((g||=[]).push(String.fromCharCode.apply(String,S)),w=0);return g?(w&&g.push(String.fromCharCode.apply(String,S.slice(0,w))),g.join(``)):String.fromCharCode.apply(String,S.slice(0,w))},t.write=function(e,t,s){for(var g=s,S,w,E=0;E<e.length;++E)S=e.charCodeAt(E),S<128?t[s++]=S:S<2048?(t[s++]=S>>6|192,t[s++]=S&63|128):(S&64512)==55296&&((w=e.charCodeAt(E+1))&64512)==56320?(S=65536+((S&1023)<<10)+(w&1023),++E,t[s++]=S>>18|240,t[s++]=S>>12&63|128,t[s++]=S>>6&63|128,t[s++]=S&63|128):(t[s++]=S>>12|224,t[s++]=S>>6&63|128,t[s++]=S&63|128);return s-g}})),require_pool=__commonJSMin$2(((e,t)=>{t.exports=s;function s(e,t,s){var g=s||8192,S=g>>>1,w=null,E=g;return function(s){if(s<1||s>S)return e(s);E+s>g&&(w=e(g),E=0);var D=t.call(w,E,E+=s);return E&7&&(E=(E|7)+1),D}}})),require_longbits=__commonJSMin$2(((e,t)=>{t.exports=g;var s=require_minimal$1();function g(e,t){this.lo=e>>>0,this.hi=t>>>0}var S=g.zero=new g(0,0);S.toNumber=function(){return 0},S.zzEncode=S.zzDecode=function(){return this},S.length=function(){return 1};var w=g.zeroHash=`\0\0\0\0\0\0\0\0`;g.fromNumber=function(e){if(e===0)return S;var t=e<0;t&&(e=-e);var s=e>>>0,w=(e-s)/4294967296>>>0;return t&&(w=~w>>>0,s=~s>>>0,++s>4294967295&&(s=0,++w>4294967295&&(w=0))),new g(s,w)},g.from=function(e){if(typeof e==`number`)return g.fromNumber(e);if(s.isString(e))if(s.Long)e=s.Long.fromString(e);else return g.fromNumber(parseInt(e,10));return e.low||e.high?new g(e.low>>>0,e.high>>>0):S},g.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,s=~this.hi>>>0;return t||(s=s+1>>>0),-(t+s*4294967296)}return this.lo+this.hi*4294967296},g.prototype.toLong=function(e){return s.Long?new s.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var E=String.prototype.charCodeAt;g.fromHash=function(e){return e===w?S:new g((E.call(e,0)|E.call(e,1)<<8|E.call(e,2)<<16|E.call(e,3)<<24)>>>0,(E.call(e,4)|E.call(e,5)<<8|E.call(e,6)<<16|E.call(e,7)<<24)>>>0)},g.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},g.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},g.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},g.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,s=this.hi>>>24;return s===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:s<128?9:10}})),require_minimal$1=__commonJSMin$2((e=>{var t=e;t.asPromise=require_aspromise(),t.base64=require_base64(),t.EventEmitter=require_eventemitter(),t.float=require_float(),t.inquire=require_inquire(),t.utf8=require_utf8(),t.pool=require_pool(),t.LongBits=require_longbits(),t.isNode=!!(typeof global<`u`&&global&&global.process&&global.process.versions&&global.process.versions.node),t.global=t.isNode&&global||typeof window<`u`&&window||typeof self<`u`&&self||e,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e},t.isString=function(e){return typeof e==`string`||e instanceof String},t.isObject=function(e){return e&&typeof e==`object`},t.isset=t.isSet=function(e,t){var s=e[t];return s!=null&&e.hasOwnProperty(t)?typeof s!=`object`||(Array.isArray(s)?s.length:Object.keys(s).length)>0:!1},t.Buffer=(function(){try{var e=t.inquire(`buffer`).Buffer;return e.prototype.utf8Write?e:null}catch{return null}})(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(e){return typeof e==`number`?t.Buffer?t._Buffer_allocUnsafe(e):new t.Array(e):t.Buffer?t._Buffer_from(e):typeof Uint8Array>`u`?e:new Uint8Array(e)},t.Array=typeof Uint8Array<`u`?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||t.inquire(`long`),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(e){return e?t.LongBits.from(e).toHash():t.LongBits.zeroHash},t.longFromHash=function(e,s){var g=t.LongBits.fromHash(e);return t.Long?t.Long.fromBits(g.lo,g.hi,s):g.toNumber(!!s)};function s(e,t,s){for(var g=Object.keys(t),S=0;S<g.length;++S)(e[g[S]]===void 0||!s)&&(e[g[S]]=t[g[S]]);return e}t.merge=s,t.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function g(e){function t(e,g){if(!(this instanceof t))return new t(e,g);Object.defineProperty(this,`message`,{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,`stack`,{value:Error().stack||``}),g&&s(this,g)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+`: `+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}t.newError=g,t.ProtocolError=g(`ProtocolError`),t.oneOfGetter=function(e){for(var t={},s=0;s<e.length;++s)t[e[s]]=1;return function(){for(var e=Object.keys(this),s=e.length-1;s>-1;--s)if(t[e[s]]===1&&this[e[s]]!==void 0&&this[e[s]]!==null)return e[s]}},t.oneOfSetter=function(e){return function(t){for(var s=0;s<e.length;++s)e[s]!==t&&delete this[e[s]]}},t.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},t._configure=function(){var e=t.Buffer;if(!e){t._Buffer_from=t._Buffer_allocUnsafe=null;return}t._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,s){return new e(t,s)},t._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}}})),require_writer=__commonJSMin$2(((e,t)=>{t.exports=j;var s=require_minimal$1(),g,S=s.LongBits,w=s.base64,E=s.utf8;function D(e,t,s){this.fn=e,this.len=t,this.next=void 0,this.val=s}function O(){}function k(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function j(){this.len=0,this.head=new D(O,0,0),this.tail=this.head,this.states=null}var F=function(){return s.Buffer?function(){return(j.create=function(){return new g})()}:function(){return new j}};j.create=F(),j.alloc=function(e){return new s.Array(e)},s.Array!==Array&&(j.alloc=s.pool(j.alloc,s.Array.prototype.subarray)),j.prototype._push=function(e,t,s){return this.tail=this.tail.next=new D(e,t,s),this.len+=t,this};function L(e,t,s){t[s]=e&255}function B(e,t,s){for(;e>127;)t[s++]=e&127|128,e>>>=7;t[s]=e}function H(e,t){this.len=e,this.next=void 0,this.val=t}H.prototype=Object.create(D.prototype),H.prototype.fn=B,j.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new H((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},j.prototype.int32=function(e){return e<0?this._push(q,10,S.fromNumber(e)):this.uint32(e)},j.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function q(e,t,s){for(;e.hi;)t[s++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[s++]=e.lo&127|128,e.lo>>>=7;t[s++]=e.lo}j.prototype.uint64=function(e){var t=S.from(e);return this._push(q,t.length(),t)},j.prototype.int64=j.prototype.uint64,j.prototype.sint64=function(e){var t=S.from(e).zzEncode();return this._push(q,t.length(),t)},j.prototype.bool=function(e){return this._push(L,1,e?1:0)};function ee(e,t,s){t[s]=e&255,t[s+1]=e>>>8&255,t[s+2]=e>>>16&255,t[s+3]=e>>>24}j.prototype.fixed32=function(e){return this._push(ee,4,e>>>0)},j.prototype.sfixed32=j.prototype.fixed32,j.prototype.fixed64=function(e){var t=S.from(e);return this._push(ee,4,t.lo)._push(ee,4,t.hi)},j.prototype.sfixed64=j.prototype.fixed64,j.prototype.float=function(e){return this._push(s.float.writeFloatLE,4,e)},j.prototype.double=function(e){return this._push(s.float.writeDoubleLE,8,e)};var J=s.Array.prototype.set?function(e,t,s){t.set(e,s)}:function(e,t,s){for(var g=0;g<e.length;++g)t[s+g]=e[g]};j.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(L,1,0);if(s.isString(e)){var g=j.alloc(t=w.length(e));w.decode(e,g,0),e=g}return this.uint32(t)._push(J,t,e)},j.prototype.string=function(e){var t=E.length(e);return t?this.uint32(t)._push(E.write,t,e):this._push(L,1,0)},j.prototype.fork=function(){return this.states=new k(this),this.head=this.tail=new D(O,0,0),this.len=0,this},j.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new D(O,0,0),this.len=0),this},j.prototype.ldelim=function(){var e=this.head,t=this.tail,s=this.len;return this.reset().uint32(s),s&&(this.tail.next=e.next,this.tail=t,this.len+=s),this},j.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),s=0;e;)e.fn(e.val,t,s),s+=e.len,e=e.next;return t},j._configure=function(e){g=e,j.create=F(),g._configure()}})),require_writer_buffer=__commonJSMin$2(((e,t)=>{t.exports=S;var s=require_writer();(S.prototype=Object.create(s.prototype)).constructor=S;var g=require_minimal$1();function S(){s.call(this)}S._configure=function(){S.alloc=g._Buffer_allocUnsafe,S.writeBytesBuffer=g.Buffer&&g.Buffer.prototype instanceof Uint8Array&&g.Buffer.prototype.set.name===`set`?function(e,t,s){t.set(e,s)}:function(e,t,s){if(e.copy)e.copy(t,s,0,e.length);else for(var g=0;g<e.length;)t[s++]=e[g++]}},S.prototype.bytes=function(e){g.isString(e)&&(e=g._Buffer_from(e,`base64`));var t=e.length>>>0;return this.uint32(t),t&&this._push(S.writeBytesBuffer,t,e),this};function w(e,t,s){e.length<40?g.utf8.write(e,t,s):t.utf8Write?t.utf8Write(e,s):t.write(e,s)}S.prototype.string=function(e){var t=g.Buffer.byteLength(e);return this.uint32(t),t&&this._push(w,t,e),this},S._configure()})),require_reader=__commonJSMin$2(((e,t)=>{t.exports=D;var s=require_minimal$1(),g,S=s.LongBits,w=s.utf8;function E(e,t){return RangeError(`index out of range: `+e.pos+` + `+(t||1)+` > `+e.len)}function D(e){this.buf=e,this.pos=0,this.len=e.length}var O=typeof Uint8Array<`u`?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new D(e);throw Error(`illegal buffer`)}:function(e){if(Array.isArray(e))return new D(e);throw Error(`illegal buffer`)},k=function(){return s.Buffer?function(e){return(D.create=function(e){return s.Buffer.isBuffer(e)?new g(e):O(e)})(e)}:O};D.create=k(),D.prototype._slice=s.Array.prototype.subarray||s.Array.prototype.slice,D.prototype.uint32=(function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,E(this,10);return e}})(),D.prototype.int32=function(){return this.uint32()|0},D.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function j(){var e=new S(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw E(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw E(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error(`invalid varint encoding`)}D.prototype.bool=function(){return this.uint32()!==0};function F(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}D.prototype.fixed32=function(){if(this.pos+4>this.len)throw E(this,4);return F(this.buf,this.pos+=4)},D.prototype.sfixed32=function(){if(this.pos+4>this.len)throw E(this,4);return F(this.buf,this.pos+=4)|0};function L(){if(this.pos+8>this.len)throw E(this,8);return new S(F(this.buf,this.pos+=4),F(this.buf,this.pos+=4))}D.prototype.float=function(){if(this.pos+4>this.len)throw E(this,4);var e=s.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},D.prototype.double=function(){if(this.pos+8>this.len)throw E(this,4);var e=s.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},D.prototype.bytes=function(){var e=this.uint32(),t=this.pos,g=this.pos+e;if(g>this.len)throw E(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,g);if(t===g){var S=s.Buffer;return S?S.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,g)},D.prototype.string=function(){var e=this.bytes();return w.read(e,0,e.length)},D.prototype.skip=function(e){if(typeof e==`number`){if(this.pos+e>this.len)throw E(this,e);this.pos+=e}else do if(this.pos>=this.len)throw E(this);while(this.buf[this.pos++]&128);return this},D.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!=4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type `+e+` at offset `+this.pos)}return this},D._configure=function(e){g=e,D.create=k(),g._configure();var t=s.Long?`toLong`:`toNumber`;s.merge(D.prototype,{int64:function(){return j.call(this)[t](!1)},uint64:function(){return j.call(this)[t](!0)},sint64:function(){return j.call(this).zzDecode()[t](!1)},fixed64:function(){return L.call(this)[t](!0)},sfixed64:function(){return L.call(this)[t](!1)}})}})),require_reader_buffer=__commonJSMin$2(((e,t)=>{t.exports=S;var s=require_reader();(S.prototype=Object.create(s.prototype)).constructor=S;var g=require_minimal$1();function S(e){s.call(this,e)}S._configure=function(){g.Buffer&&(S.prototype._slice=g.Buffer.prototype.slice)},S.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString(`utf-8`,this.pos,this.pos=Math.min(this.pos+e,this.len))},S._configure()})),require_service=__commonJSMin$2(((e,t)=>{t.exports=g;var s=require_minimal$1();(g.prototype=Object.create(s.EventEmitter.prototype)).constructor=g;function g(e,t,g){if(typeof e!=`function`)throw TypeError(`rpcImpl must be a function`);s.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=!!t,this.responseDelimited=!!g}g.prototype.rpcCall=function e(t,g,S,w,E){if(!w)throw TypeError(`request must be specified`);var D=this;if(!E)return s.asPromise(e,D,t,g,S,w);if(!D.rpcImpl){setTimeout(function(){E(Error(`already ended`))},0);return}try{return D.rpcImpl(t,g[D.requestDelimited?`encodeDelimited`:`encode`](w).finish(),function(e,s){if(e)return D.emit(`error`,e,t),E(e);if(s===null){D.end(!0);return}if(!(s instanceof S))try{s=S[D.responseDelimited?`decodeDelimited`:`decode`](s)}catch(e){return D.emit(`error`,e,t),E(e)}return D.emit(`data`,s,t),E(null,s)})}catch(e){D.emit(`error`,e,t),setTimeout(function(){E(e)},0);return}},g.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit(`end`).off()),this}})),require_rpc=__commonJSMin$2((e=>{var t=e;t.Service=require_service()})),require_roots=__commonJSMin$2(((e,t)=>{t.exports={}})),require_index_minimal=__commonJSMin$2((e=>{var t=e;t.build=`minimal`,t.Writer=require_writer(),t.BufferWriter=require_writer_buffer(),t.Reader=require_reader(),t.BufferReader=require_reader_buffer(),t.util=require_minimal$1(),t.rpc=require_rpc(),t.roots=require_roots(),t.configure=s;function s(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}s()})),require_minimal=__commonJSMin$2(((e,t)=>{t.exports=require_index_minimal()})),require_root=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});var s=require_minimal(),g=s.Reader,S=s.Writer,w=s.util,E=s.roots.default||(s.roots.default={});E.opentelemetry=(function(){var e={};return e.proto=(function(){var e={};return e.common=(function(){var e={};return e.v1=(function(){var e={};return e.AnyValue=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}e.prototype.stringValue=null,e.prototype.boolValue=null,e.prototype.intValue=null,e.prototype.doubleValue=null,e.prototype.arrayValue=null,e.prototype.kvlistValue=null,e.prototype.bytesValue=null;var t;return Object.defineProperty(e.prototype,`value`,{get:w.oneOfGetter(t=[`stringValue`,`boolValue`,`intValue`,`doubleValue`,`arrayValue`,`kvlistValue`,`bytesValue`]),set:w.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.stringValue!=null&&Object.hasOwnProperty.call(e,`stringValue`)&&t.uint32(10).string(e.stringValue),e.boolValue!=null&&Object.hasOwnProperty.call(e,`boolValue`)&&t.uint32(16).bool(e.boolValue),e.intValue!=null&&Object.hasOwnProperty.call(e,`intValue`)&&t.uint32(24).int64(e.intValue),e.doubleValue!=null&&Object.hasOwnProperty.call(e,`doubleValue`)&&t.uint32(33).double(e.doubleValue),e.arrayValue!=null&&Object.hasOwnProperty.call(e,`arrayValue`)&&E.opentelemetry.proto.common.v1.ArrayValue.encode(e.arrayValue,t.uint32(42).fork()).ldelim(),e.kvlistValue!=null&&Object.hasOwnProperty.call(e,`kvlistValue`)&&E.opentelemetry.proto.common.v1.KeyValueList.encode(e.kvlistValue,t.uint32(50).fork()).ldelim(),e.bytesValue!=null&&Object.hasOwnProperty.call(e,`bytesValue`)&&t.uint32(58).bytes(e.bytesValue),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.common.v1.AnyValue;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.stringValue=e.string();break;case 2:w.boolValue=e.bool();break;case 3:w.intValue=e.int64();break;case 4:w.doubleValue=e.double();break;case 5:w.arrayValue=E.opentelemetry.proto.common.v1.ArrayValue.decode(e,e.uint32());break;case 6:w.kvlistValue=E.opentelemetry.proto.common.v1.KeyValueList.decode(e,e.uint32());break;case 7:w.bytesValue=e.bytes();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;var t={};if(e.stringValue!=null&&e.hasOwnProperty(`stringValue`)&&(t.value=1,!w.isString(e.stringValue)))return`stringValue: string expected`;if(e.boolValue!=null&&e.hasOwnProperty(`boolValue`)){if(t.value===1)return`value: multiple values`;if(t.value=1,typeof e.boolValue!=`boolean`)return`boolValue: boolean expected`}if(e.intValue!=null&&e.hasOwnProperty(`intValue`)){if(t.value===1)return`value: multiple values`;if(t.value=1,!w.isInteger(e.intValue)&&!(e.intValue&&w.isInteger(e.intValue.low)&&w.isInteger(e.intValue.high)))return`intValue: integer|Long expected`}if(e.doubleValue!=null&&e.hasOwnProperty(`doubleValue`)){if(t.value===1)return`value: multiple values`;if(t.value=1,typeof e.doubleValue!=`number`)return`doubleValue: number expected`}if(e.arrayValue!=null&&e.hasOwnProperty(`arrayValue`)){if(t.value===1)return`value: multiple values`;t.value=1;var s=E.opentelemetry.proto.common.v1.ArrayValue.verify(e.arrayValue);if(s)return`arrayValue.`+s}if(e.kvlistValue!=null&&e.hasOwnProperty(`kvlistValue`)){if(t.value===1)return`value: multiple values`;t.value=1;var s=E.opentelemetry.proto.common.v1.KeyValueList.verify(e.kvlistValue);if(s)return`kvlistValue.`+s}if(e.bytesValue!=null&&e.hasOwnProperty(`bytesValue`)){if(t.value===1)return`value: multiple values`;if(t.value=1,!(e.bytesValue&&typeof e.bytesValue.length==`number`||w.isString(e.bytesValue)))return`bytesValue: buffer expected`}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.common.v1.AnyValue)return e;var t=new E.opentelemetry.proto.common.v1.AnyValue;if(e.stringValue!=null&&(t.stringValue=String(e.stringValue)),e.boolValue!=null&&(t.boolValue=!!e.boolValue),e.intValue!=null&&(w.Long?(t.intValue=w.Long.fromValue(e.intValue)).unsigned=!1:typeof e.intValue==`string`?t.intValue=parseInt(e.intValue,10):typeof e.intValue==`number`?t.intValue=e.intValue:typeof e.intValue==`object`&&(t.intValue=new w.LongBits(e.intValue.low>>>0,e.intValue.high>>>0).toNumber())),e.doubleValue!=null&&(t.doubleValue=Number(e.doubleValue)),e.arrayValue!=null){if(typeof e.arrayValue!=`object`)throw TypeError(`.opentelemetry.proto.common.v1.AnyValue.arrayValue: object expected`);t.arrayValue=E.opentelemetry.proto.common.v1.ArrayValue.fromObject(e.arrayValue)}if(e.kvlistValue!=null){if(typeof e.kvlistValue!=`object`)throw TypeError(`.opentelemetry.proto.common.v1.AnyValue.kvlistValue: object expected`);t.kvlistValue=E.opentelemetry.proto.common.v1.KeyValueList.fromObject(e.kvlistValue)}return e.bytesValue!=null&&(typeof e.bytesValue==`string`?w.base64.decode(e.bytesValue,t.bytesValue=w.newBuffer(w.base64.length(e.bytesValue)),0):e.bytesValue.length>=0&&(t.bytesValue=e.bytesValue)),t},e.toObject=function(e,t){t||={};var s={};return e.stringValue!=null&&e.hasOwnProperty(`stringValue`)&&(s.stringValue=e.stringValue,t.oneofs&&(s.value=`stringValue`)),e.boolValue!=null&&e.hasOwnProperty(`boolValue`)&&(s.boolValue=e.boolValue,t.oneofs&&(s.value=`boolValue`)),e.intValue!=null&&e.hasOwnProperty(`intValue`)&&(typeof e.intValue==`number`?s.intValue=t.longs===String?String(e.intValue):e.intValue:s.intValue=t.longs===String?w.Long.prototype.toString.call(e.intValue):t.longs===Number?new w.LongBits(e.intValue.low>>>0,e.intValue.high>>>0).toNumber():e.intValue,t.oneofs&&(s.value=`intValue`)),e.doubleValue!=null&&e.hasOwnProperty(`doubleValue`)&&(s.doubleValue=t.json&&!isFinite(e.doubleValue)?String(e.doubleValue):e.doubleValue,t.oneofs&&(s.value=`doubleValue`)),e.arrayValue!=null&&e.hasOwnProperty(`arrayValue`)&&(s.arrayValue=E.opentelemetry.proto.common.v1.ArrayValue.toObject(e.arrayValue,t),t.oneofs&&(s.value=`arrayValue`)),e.kvlistValue!=null&&e.hasOwnProperty(`kvlistValue`)&&(s.kvlistValue=E.opentelemetry.proto.common.v1.KeyValueList.toObject(e.kvlistValue,t),t.oneofs&&(s.value=`kvlistValue`)),e.bytesValue!=null&&e.hasOwnProperty(`bytesValue`)&&(s.bytesValue=t.bytes===String?w.base64.encode(e.bytesValue,0,e.bytesValue.length):t.bytes===Array?Array.prototype.slice.call(e.bytesValue):e.bytesValue,t.oneofs&&(s.value=`bytesValue`)),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.common.v1.AnyValue`},e})(),e.ArrayValue=(function(){function e(e){if(this.values=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.values=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.values!=null&&e.values.length)for(var s=0;s<e.values.length;++s)E.opentelemetry.proto.common.v1.AnyValue.encode(e.values[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.common.v1.ArrayValue;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.values&&w.values.length||(w.values=[]),w.values.push(E.opentelemetry.proto.common.v1.AnyValue.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.values!=null&&e.hasOwnProperty(`values`)){if(!Array.isArray(e.values))return`values: array expected`;for(var t=0;t<e.values.length;++t){var s=E.opentelemetry.proto.common.v1.AnyValue.verify(e.values[t]);if(s)return`values.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.common.v1.ArrayValue)return e;var t=new E.opentelemetry.proto.common.v1.ArrayValue;if(e.values){if(!Array.isArray(e.values))throw TypeError(`.opentelemetry.proto.common.v1.ArrayValue.values: array expected`);t.values=[];for(var s=0;s<e.values.length;++s){if(typeof e.values[s]!=`object`)throw TypeError(`.opentelemetry.proto.common.v1.ArrayValue.values: object expected`);t.values[s]=E.opentelemetry.proto.common.v1.AnyValue.fromObject(e.values[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.values=[]),e.values&&e.values.length){s.values=[];for(var g=0;g<e.values.length;++g)s.values[g]=E.opentelemetry.proto.common.v1.AnyValue.toObject(e.values[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.common.v1.ArrayValue`},e})(),e.KeyValueList=(function(){function e(e){if(this.values=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.values=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.values!=null&&e.values.length)for(var s=0;s<e.values.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.values[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.common.v1.KeyValueList;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.values&&w.values.length||(w.values=[]),w.values.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.values!=null&&e.hasOwnProperty(`values`)){if(!Array.isArray(e.values))return`values: array expected`;for(var t=0;t<e.values.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.values[t]);if(s)return`values.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.common.v1.KeyValueList)return e;var t=new E.opentelemetry.proto.common.v1.KeyValueList;if(e.values){if(!Array.isArray(e.values))throw TypeError(`.opentelemetry.proto.common.v1.KeyValueList.values: array expected`);t.values=[];for(var s=0;s<e.values.length;++s){if(typeof e.values[s]!=`object`)throw TypeError(`.opentelemetry.proto.common.v1.KeyValueList.values: object expected`);t.values[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.values[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.values=[]),e.values&&e.values.length){s.values=[];for(var g=0;g<e.values.length;++g)s.values[g]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.values[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.common.v1.KeyValueList`},e})(),e.KeyValue=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.key=null,e.prototype.value=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.key!=null&&Object.hasOwnProperty.call(e,`key`)&&t.uint32(10).string(e.key),e.value!=null&&Object.hasOwnProperty.call(e,`value`)&&E.opentelemetry.proto.common.v1.AnyValue.encode(e.value,t.uint32(18).fork()).ldelim(),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.common.v1.KeyValue;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.key=e.string();break;case 2:w.value=E.opentelemetry.proto.common.v1.AnyValue.decode(e,e.uint32());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.key!=null&&e.hasOwnProperty(`key`)&&!w.isString(e.key))return`key: string expected`;if(e.value!=null&&e.hasOwnProperty(`value`)){var t=E.opentelemetry.proto.common.v1.AnyValue.verify(e.value);if(t)return`value.`+t}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.common.v1.KeyValue)return e;var t=new E.opentelemetry.proto.common.v1.KeyValue;if(e.key!=null&&(t.key=String(e.key)),e.value!=null){if(typeof e.value!=`object`)throw TypeError(`.opentelemetry.proto.common.v1.KeyValue.value: object expected`);t.value=E.opentelemetry.proto.common.v1.AnyValue.fromObject(e.value)}return t},e.toObject=function(e,t){t||={};var s={};return t.defaults&&(s.key=``,s.value=null),e.key!=null&&e.hasOwnProperty(`key`)&&(s.key=e.key),e.value!=null&&e.hasOwnProperty(`value`)&&(s.value=E.opentelemetry.proto.common.v1.AnyValue.toObject(e.value,t)),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.common.v1.KeyValue`},e})(),e.InstrumentationScope=(function(){function e(e){if(this.attributes=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.name=null,e.prototype.version=null,e.prototype.attributes=w.emptyArray,e.prototype.droppedAttributesCount=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.name!=null&&Object.hasOwnProperty.call(e,`name`)&&t.uint32(10).string(e.name),e.version!=null&&Object.hasOwnProperty.call(e,`version`)&&t.uint32(18).string(e.version),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(26).fork()).ldelim();return e.droppedAttributesCount!=null&&Object.hasOwnProperty.call(e,`droppedAttributesCount`)&&t.uint32(32).uint32(e.droppedAttributesCount),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.common.v1.InstrumentationScope;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.name=e.string();break;case 2:w.version=e.string();break;case 3:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 4:w.droppedAttributesCount=e.uint32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.name!=null&&e.hasOwnProperty(`name`)&&!w.isString(e.name))return`name: string expected`;if(e.version!=null&&e.hasOwnProperty(`version`)&&!w.isString(e.version))return`version: string expected`;if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var t=0;t<e.attributes.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[t]);if(s)return`attributes.`+s}}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&!w.isInteger(e.droppedAttributesCount)?`droppedAttributesCount: integer expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.common.v1.InstrumentationScope)return e;var t=new E.opentelemetry.proto.common.v1.InstrumentationScope;if(e.name!=null&&(t.name=String(e.name)),e.version!=null&&(t.version=String(e.version)),e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.common.v1.InstrumentationScope.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.common.v1.InstrumentationScope.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}return e.droppedAttributesCount!=null&&(t.droppedAttributesCount=e.droppedAttributesCount>>>0),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[]),t.defaults&&(s.name=``,s.version=``,s.droppedAttributesCount=0),e.name!=null&&e.hasOwnProperty(`name`)&&(s.name=e.name),e.version!=null&&e.hasOwnProperty(`version`)&&(s.version=e.version),e.attributes&&e.attributes.length){s.attributes=[];for(var g=0;g<e.attributes.length;++g)s.attributes[g]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[g],t)}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&(s.droppedAttributesCount=e.droppedAttributesCount),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.common.v1.InstrumentationScope`},e})(),e.EntityRef=(function(){function e(e){if(this.idKeys=[],this.descriptionKeys=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.schemaUrl=null,e.prototype.type=null,e.prototype.idKeys=w.emptyArray,e.prototype.descriptionKeys=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(10).string(e.schemaUrl),e.type!=null&&Object.hasOwnProperty.call(e,`type`)&&t.uint32(18).string(e.type),e.idKeys!=null&&e.idKeys.length)for(var s=0;s<e.idKeys.length;++s)t.uint32(26).string(e.idKeys[s]);if(e.descriptionKeys!=null&&e.descriptionKeys.length)for(var s=0;s<e.descriptionKeys.length;++s)t.uint32(34).string(e.descriptionKeys[s]);return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.common.v1.EntityRef;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.schemaUrl=e.string();break;case 2:w.type=e.string();break;case 3:w.idKeys&&w.idKeys.length||(w.idKeys=[]),w.idKeys.push(e.string());break;case 4:w.descriptionKeys&&w.descriptionKeys.length||(w.descriptionKeys=[]),w.descriptionKeys.push(e.string());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl))return`schemaUrl: string expected`;if(e.type!=null&&e.hasOwnProperty(`type`)&&!w.isString(e.type))return`type: string expected`;if(e.idKeys!=null&&e.hasOwnProperty(`idKeys`)){if(!Array.isArray(e.idKeys))return`idKeys: array expected`;for(var t=0;t<e.idKeys.length;++t)if(!w.isString(e.idKeys[t]))return`idKeys: string[] expected`}if(e.descriptionKeys!=null&&e.hasOwnProperty(`descriptionKeys`)){if(!Array.isArray(e.descriptionKeys))return`descriptionKeys: array expected`;for(var t=0;t<e.descriptionKeys.length;++t)if(!w.isString(e.descriptionKeys[t]))return`descriptionKeys: string[] expected`}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.common.v1.EntityRef)return e;var t=new E.opentelemetry.proto.common.v1.EntityRef;if(e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),e.type!=null&&(t.type=String(e.type)),e.idKeys){if(!Array.isArray(e.idKeys))throw TypeError(`.opentelemetry.proto.common.v1.EntityRef.idKeys: array expected`);t.idKeys=[];for(var s=0;s<e.idKeys.length;++s)t.idKeys[s]=String(e.idKeys[s])}if(e.descriptionKeys){if(!Array.isArray(e.descriptionKeys))throw TypeError(`.opentelemetry.proto.common.v1.EntityRef.descriptionKeys: array expected`);t.descriptionKeys=[];for(var s=0;s<e.descriptionKeys.length;++s)t.descriptionKeys[s]=String(e.descriptionKeys[s])}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.idKeys=[],s.descriptionKeys=[]),t.defaults&&(s.schemaUrl=``,s.type=``),e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),e.type!=null&&e.hasOwnProperty(`type`)&&(s.type=e.type),e.idKeys&&e.idKeys.length){s.idKeys=[];for(var g=0;g<e.idKeys.length;++g)s.idKeys[g]=e.idKeys[g]}if(e.descriptionKeys&&e.descriptionKeys.length){s.descriptionKeys=[];for(var g=0;g<e.descriptionKeys.length;++g)s.descriptionKeys[g]=e.descriptionKeys[g]}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.common.v1.EntityRef`},e})(),e})(),e})(),e.resource=(function(){var e={};return e.v1=(function(){var e={};return e.Resource=(function(){function e(e){if(this.attributes=[],this.entityRefs=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.attributes=w.emptyArray,e.prototype.droppedAttributesCount=null,e.prototype.entityRefs=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(10).fork()).ldelim();if(e.droppedAttributesCount!=null&&Object.hasOwnProperty.call(e,`droppedAttributesCount`)&&t.uint32(16).uint32(e.droppedAttributesCount),e.entityRefs!=null&&e.entityRefs.length)for(var s=0;s<e.entityRefs.length;++s)E.opentelemetry.proto.common.v1.EntityRef.encode(e.entityRefs[s],t.uint32(26).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.resource.v1.Resource;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 2:w.droppedAttributesCount=e.uint32();break;case 3:w.entityRefs&&w.entityRefs.length||(w.entityRefs=[]),w.entityRefs.push(E.opentelemetry.proto.common.v1.EntityRef.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var t=0;t<e.attributes.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[t]);if(s)return`attributes.`+s}}if(e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&!w.isInteger(e.droppedAttributesCount))return`droppedAttributesCount: integer expected`;if(e.entityRefs!=null&&e.hasOwnProperty(`entityRefs`)){if(!Array.isArray(e.entityRefs))return`entityRefs: array expected`;for(var t=0;t<e.entityRefs.length;++t){var s=E.opentelemetry.proto.common.v1.EntityRef.verify(e.entityRefs[t]);if(s)return`entityRefs.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.resource.v1.Resource)return e;var t=new E.opentelemetry.proto.resource.v1.Resource;if(e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.resource.v1.Resource.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.resource.v1.Resource.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}if(e.droppedAttributesCount!=null&&(t.droppedAttributesCount=e.droppedAttributesCount>>>0),e.entityRefs){if(!Array.isArray(e.entityRefs))throw TypeError(`.opentelemetry.proto.resource.v1.Resource.entityRefs: array expected`);t.entityRefs=[];for(var s=0;s<e.entityRefs.length;++s){if(typeof e.entityRefs[s]!=`object`)throw TypeError(`.opentelemetry.proto.resource.v1.Resource.entityRefs: object expected`);t.entityRefs[s]=E.opentelemetry.proto.common.v1.EntityRef.fromObject(e.entityRefs[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[],s.entityRefs=[]),t.defaults&&(s.droppedAttributesCount=0),e.attributes&&e.attributes.length){s.attributes=[];for(var g=0;g<e.attributes.length;++g)s.attributes[g]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[g],t)}if(e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&(s.droppedAttributesCount=e.droppedAttributesCount),e.entityRefs&&e.entityRefs.length){s.entityRefs=[];for(var g=0;g<e.entityRefs.length;++g)s.entityRefs[g]=E.opentelemetry.proto.common.v1.EntityRef.toObject(e.entityRefs[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.resource.v1.Resource`},e})(),e})(),e})(),e.trace=(function(){var e={};return e.v1=(function(){var e={};return e.TracesData=(function(){function e(e){if(this.resourceSpans=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resourceSpans=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resourceSpans!=null&&e.resourceSpans.length)for(var s=0;s<e.resourceSpans.length;++s)E.opentelemetry.proto.trace.v1.ResourceSpans.encode(e.resourceSpans[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.TracesData;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resourceSpans&&w.resourceSpans.length||(w.resourceSpans=[]),w.resourceSpans.push(E.opentelemetry.proto.trace.v1.ResourceSpans.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resourceSpans!=null&&e.hasOwnProperty(`resourceSpans`)){if(!Array.isArray(e.resourceSpans))return`resourceSpans: array expected`;for(var t=0;t<e.resourceSpans.length;++t){var s=E.opentelemetry.proto.trace.v1.ResourceSpans.verify(e.resourceSpans[t]);if(s)return`resourceSpans.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.TracesData)return e;var t=new E.opentelemetry.proto.trace.v1.TracesData;if(e.resourceSpans){if(!Array.isArray(e.resourceSpans))throw TypeError(`.opentelemetry.proto.trace.v1.TracesData.resourceSpans: array expected`);t.resourceSpans=[];for(var s=0;s<e.resourceSpans.length;++s){if(typeof e.resourceSpans[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.TracesData.resourceSpans: object expected`);t.resourceSpans[s]=E.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(e.resourceSpans[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.resourceSpans=[]),e.resourceSpans&&e.resourceSpans.length){s.resourceSpans=[];for(var g=0;g<e.resourceSpans.length;++g)s.resourceSpans[g]=E.opentelemetry.proto.trace.v1.ResourceSpans.toObject(e.resourceSpans[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.TracesData`},e})(),e.ResourceSpans=(function(){function e(e){if(this.scopeSpans=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resource=null,e.prototype.scopeSpans=w.emptyArray,e.prototype.schemaUrl=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resource!=null&&Object.hasOwnProperty.call(e,`resource`)&&E.opentelemetry.proto.resource.v1.Resource.encode(e.resource,t.uint32(10).fork()).ldelim(),e.scopeSpans!=null&&e.scopeSpans.length)for(var s=0;s<e.scopeSpans.length;++s)E.opentelemetry.proto.trace.v1.ScopeSpans.encode(e.scopeSpans[s],t.uint32(18).fork()).ldelim();return e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(26).string(e.schemaUrl),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.ResourceSpans;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resource=E.opentelemetry.proto.resource.v1.Resource.decode(e,e.uint32());break;case 2:w.scopeSpans&&w.scopeSpans.length||(w.scopeSpans=[]),w.scopeSpans.push(E.opentelemetry.proto.trace.v1.ScopeSpans.decode(e,e.uint32()));break;case 3:w.schemaUrl=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resource!=null&&e.hasOwnProperty(`resource`)){var t=E.opentelemetry.proto.resource.v1.Resource.verify(e.resource);if(t)return`resource.`+t}if(e.scopeSpans!=null&&e.hasOwnProperty(`scopeSpans`)){if(!Array.isArray(e.scopeSpans))return`scopeSpans: array expected`;for(var s=0;s<e.scopeSpans.length;++s){var t=E.opentelemetry.proto.trace.v1.ScopeSpans.verify(e.scopeSpans[s]);if(t)return`scopeSpans.`+t}}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl)?`schemaUrl: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.ResourceSpans)return e;var t=new E.opentelemetry.proto.trace.v1.ResourceSpans;if(e.resource!=null){if(typeof e.resource!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.ResourceSpans.resource: object expected`);t.resource=E.opentelemetry.proto.resource.v1.Resource.fromObject(e.resource)}if(e.scopeSpans){if(!Array.isArray(e.scopeSpans))throw TypeError(`.opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: array expected`);t.scopeSpans=[];for(var s=0;s<e.scopeSpans.length;++s){if(typeof e.scopeSpans[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: object expected`);t.scopeSpans[s]=E.opentelemetry.proto.trace.v1.ScopeSpans.fromObject(e.scopeSpans[s])}}return e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.scopeSpans=[]),t.defaults&&(s.resource=null,s.schemaUrl=``),e.resource!=null&&e.hasOwnProperty(`resource`)&&(s.resource=E.opentelemetry.proto.resource.v1.Resource.toObject(e.resource,t)),e.scopeSpans&&e.scopeSpans.length){s.scopeSpans=[];for(var g=0;g<e.scopeSpans.length;++g)s.scopeSpans[g]=E.opentelemetry.proto.trace.v1.ScopeSpans.toObject(e.scopeSpans[g],t)}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.ResourceSpans`},e})(),e.ScopeSpans=(function(){function e(e){if(this.spans=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.scope=null,e.prototype.spans=w.emptyArray,e.prototype.schemaUrl=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.scope!=null&&Object.hasOwnProperty.call(e,`scope`)&&E.opentelemetry.proto.common.v1.InstrumentationScope.encode(e.scope,t.uint32(10).fork()).ldelim(),e.spans!=null&&e.spans.length)for(var s=0;s<e.spans.length;++s)E.opentelemetry.proto.trace.v1.Span.encode(e.spans[s],t.uint32(18).fork()).ldelim();return e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(26).string(e.schemaUrl),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.ScopeSpans;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.decode(e,e.uint32());break;case 2:w.spans&&w.spans.length||(w.spans=[]),w.spans.push(E.opentelemetry.proto.trace.v1.Span.decode(e,e.uint32()));break;case 3:w.schemaUrl=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.scope!=null&&e.hasOwnProperty(`scope`)){var t=E.opentelemetry.proto.common.v1.InstrumentationScope.verify(e.scope);if(t)return`scope.`+t}if(e.spans!=null&&e.hasOwnProperty(`spans`)){if(!Array.isArray(e.spans))return`spans: array expected`;for(var s=0;s<e.spans.length;++s){var t=E.opentelemetry.proto.trace.v1.Span.verify(e.spans[s]);if(t)return`spans.`+t}}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl)?`schemaUrl: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.ScopeSpans)return e;var t=new E.opentelemetry.proto.trace.v1.ScopeSpans;if(e.scope!=null){if(typeof e.scope!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.ScopeSpans.scope: object expected`);t.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(e.scope)}if(e.spans){if(!Array.isArray(e.spans))throw TypeError(`.opentelemetry.proto.trace.v1.ScopeSpans.spans: array expected`);t.spans=[];for(var s=0;s<e.spans.length;++s){if(typeof e.spans[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.ScopeSpans.spans: object expected`);t.spans[s]=E.opentelemetry.proto.trace.v1.Span.fromObject(e.spans[s])}}return e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.spans=[]),t.defaults&&(s.scope=null,s.schemaUrl=``),e.scope!=null&&e.hasOwnProperty(`scope`)&&(s.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.toObject(e.scope,t)),e.spans&&e.spans.length){s.spans=[];for(var g=0;g<e.spans.length;++g)s.spans[g]=E.opentelemetry.proto.trace.v1.Span.toObject(e.spans[g],t)}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.ScopeSpans`},e})(),e.Span=(function(){function e(e){if(this.attributes=[],this.events=[],this.links=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.traceId=null,e.prototype.spanId=null,e.prototype.traceState=null,e.prototype.parentSpanId=null,e.prototype.flags=null,e.prototype.name=null,e.prototype.kind=null,e.prototype.startTimeUnixNano=null,e.prototype.endTimeUnixNano=null,e.prototype.attributes=w.emptyArray,e.prototype.droppedAttributesCount=null,e.prototype.events=w.emptyArray,e.prototype.droppedEventsCount=null,e.prototype.links=w.emptyArray,e.prototype.droppedLinksCount=null,e.prototype.status=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.traceId!=null&&Object.hasOwnProperty.call(e,`traceId`)&&t.uint32(10).bytes(e.traceId),e.spanId!=null&&Object.hasOwnProperty.call(e,`spanId`)&&t.uint32(18).bytes(e.spanId),e.traceState!=null&&Object.hasOwnProperty.call(e,`traceState`)&&t.uint32(26).string(e.traceState),e.parentSpanId!=null&&Object.hasOwnProperty.call(e,`parentSpanId`)&&t.uint32(34).bytes(e.parentSpanId),e.name!=null&&Object.hasOwnProperty.call(e,`name`)&&t.uint32(42).string(e.name),e.kind!=null&&Object.hasOwnProperty.call(e,`kind`)&&t.uint32(48).int32(e.kind),e.startTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`startTimeUnixNano`)&&t.uint32(57).fixed64(e.startTimeUnixNano),e.endTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`endTimeUnixNano`)&&t.uint32(65).fixed64(e.endTimeUnixNano),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(74).fork()).ldelim();if(e.droppedAttributesCount!=null&&Object.hasOwnProperty.call(e,`droppedAttributesCount`)&&t.uint32(80).uint32(e.droppedAttributesCount),e.events!=null&&e.events.length)for(var s=0;s<e.events.length;++s)E.opentelemetry.proto.trace.v1.Span.Event.encode(e.events[s],t.uint32(90).fork()).ldelim();if(e.droppedEventsCount!=null&&Object.hasOwnProperty.call(e,`droppedEventsCount`)&&t.uint32(96).uint32(e.droppedEventsCount),e.links!=null&&e.links.length)for(var s=0;s<e.links.length;++s)E.opentelemetry.proto.trace.v1.Span.Link.encode(e.links[s],t.uint32(106).fork()).ldelim();return e.droppedLinksCount!=null&&Object.hasOwnProperty.call(e,`droppedLinksCount`)&&t.uint32(112).uint32(e.droppedLinksCount),e.status!=null&&Object.hasOwnProperty.call(e,`status`)&&E.opentelemetry.proto.trace.v1.Status.encode(e.status,t.uint32(122).fork()).ldelim(),e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(133).fixed32(e.flags),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.Span;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.traceId=e.bytes();break;case 2:w.spanId=e.bytes();break;case 3:w.traceState=e.string();break;case 4:w.parentSpanId=e.bytes();break;case 16:w.flags=e.fixed32();break;case 5:w.name=e.string();break;case 6:w.kind=e.int32();break;case 7:w.startTimeUnixNano=e.fixed64();break;case 8:w.endTimeUnixNano=e.fixed64();break;case 9:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 10:w.droppedAttributesCount=e.uint32();break;case 11:w.events&&w.events.length||(w.events=[]),w.events.push(E.opentelemetry.proto.trace.v1.Span.Event.decode(e,e.uint32()));break;case 12:w.droppedEventsCount=e.uint32();break;case 13:w.links&&w.links.length||(w.links=[]),w.links.push(E.opentelemetry.proto.trace.v1.Span.Link.decode(e,e.uint32()));break;case 14:w.droppedLinksCount=e.uint32();break;case 15:w.status=E.opentelemetry.proto.trace.v1.Status.decode(e,e.uint32());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.traceId!=null&&e.hasOwnProperty(`traceId`)&&!(e.traceId&&typeof e.traceId.length==`number`||w.isString(e.traceId)))return`traceId: buffer expected`;if(e.spanId!=null&&e.hasOwnProperty(`spanId`)&&!(e.spanId&&typeof e.spanId.length==`number`||w.isString(e.spanId)))return`spanId: buffer expected`;if(e.traceState!=null&&e.hasOwnProperty(`traceState`)&&!w.isString(e.traceState))return`traceState: string expected`;if(e.parentSpanId!=null&&e.hasOwnProperty(`parentSpanId`)&&!(e.parentSpanId&&typeof e.parentSpanId.length==`number`||w.isString(e.parentSpanId)))return`parentSpanId: buffer expected`;if(e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags))return`flags: integer expected`;if(e.name!=null&&e.hasOwnProperty(`name`)&&!w.isString(e.name))return`name: string expected`;if(e.kind!=null&&e.hasOwnProperty(`kind`))switch(e.kind){default:return`kind: enum value expected`;case 0:case 1:case 2:case 3:case 4:case 5:break}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&!w.isInteger(e.startTimeUnixNano)&&!(e.startTimeUnixNano&&w.isInteger(e.startTimeUnixNano.low)&&w.isInteger(e.startTimeUnixNano.high)))return`startTimeUnixNano: integer|Long expected`;if(e.endTimeUnixNano!=null&&e.hasOwnProperty(`endTimeUnixNano`)&&!w.isInteger(e.endTimeUnixNano)&&!(e.endTimeUnixNano&&w.isInteger(e.endTimeUnixNano.low)&&w.isInteger(e.endTimeUnixNano.high)))return`endTimeUnixNano: integer|Long expected`;if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var t=0;t<e.attributes.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[t]);if(s)return`attributes.`+s}}if(e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&!w.isInteger(e.droppedAttributesCount))return`droppedAttributesCount: integer expected`;if(e.events!=null&&e.hasOwnProperty(`events`)){if(!Array.isArray(e.events))return`events: array expected`;for(var t=0;t<e.events.length;++t){var s=E.opentelemetry.proto.trace.v1.Span.Event.verify(e.events[t]);if(s)return`events.`+s}}if(e.droppedEventsCount!=null&&e.hasOwnProperty(`droppedEventsCount`)&&!w.isInteger(e.droppedEventsCount))return`droppedEventsCount: integer expected`;if(e.links!=null&&e.hasOwnProperty(`links`)){if(!Array.isArray(e.links))return`links: array expected`;for(var t=0;t<e.links.length;++t){var s=E.opentelemetry.proto.trace.v1.Span.Link.verify(e.links[t]);if(s)return`links.`+s}}if(e.droppedLinksCount!=null&&e.hasOwnProperty(`droppedLinksCount`)&&!w.isInteger(e.droppedLinksCount))return`droppedLinksCount: integer expected`;if(e.status!=null&&e.hasOwnProperty(`status`)){var s=E.opentelemetry.proto.trace.v1.Status.verify(e.status);if(s)return`status.`+s}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.Span)return e;var t=new E.opentelemetry.proto.trace.v1.Span;switch(e.traceId!=null&&(typeof e.traceId==`string`?w.base64.decode(e.traceId,t.traceId=w.newBuffer(w.base64.length(e.traceId)),0):e.traceId.length>=0&&(t.traceId=e.traceId)),e.spanId!=null&&(typeof e.spanId==`string`?w.base64.decode(e.spanId,t.spanId=w.newBuffer(w.base64.length(e.spanId)),0):e.spanId.length>=0&&(t.spanId=e.spanId)),e.traceState!=null&&(t.traceState=String(e.traceState)),e.parentSpanId!=null&&(typeof e.parentSpanId==`string`?w.base64.decode(e.parentSpanId,t.parentSpanId=w.newBuffer(w.base64.length(e.parentSpanId)),0):e.parentSpanId.length>=0&&(t.parentSpanId=e.parentSpanId)),e.flags!=null&&(t.flags=e.flags>>>0),e.name!=null&&(t.name=String(e.name)),e.kind){default:if(typeof e.kind==`number`){t.kind=e.kind;break}break;case`SPAN_KIND_UNSPECIFIED`:case 0:t.kind=0;break;case`SPAN_KIND_INTERNAL`:case 1:t.kind=1;break;case`SPAN_KIND_SERVER`:case 2:t.kind=2;break;case`SPAN_KIND_CLIENT`:case 3:t.kind=3;break;case`SPAN_KIND_PRODUCER`:case 4:t.kind=4;break;case`SPAN_KIND_CONSUMER`:case 5:t.kind=5;break}if(e.startTimeUnixNano!=null&&(w.Long?(t.startTimeUnixNano=w.Long.fromValue(e.startTimeUnixNano)).unsigned=!1:typeof e.startTimeUnixNano==`string`?t.startTimeUnixNano=parseInt(e.startTimeUnixNano,10):typeof e.startTimeUnixNano==`number`?t.startTimeUnixNano=e.startTimeUnixNano:typeof e.startTimeUnixNano==`object`&&(t.startTimeUnixNano=new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber())),e.endTimeUnixNano!=null&&(w.Long?(t.endTimeUnixNano=w.Long.fromValue(e.endTimeUnixNano)).unsigned=!1:typeof e.endTimeUnixNano==`string`?t.endTimeUnixNano=parseInt(e.endTimeUnixNano,10):typeof e.endTimeUnixNano==`number`?t.endTimeUnixNano=e.endTimeUnixNano:typeof e.endTimeUnixNano==`object`&&(t.endTimeUnixNano=new w.LongBits(e.endTimeUnixNano.low>>>0,e.endTimeUnixNano.high>>>0).toNumber())),e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.trace.v1.Span.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.Span.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}if(e.droppedAttributesCount!=null&&(t.droppedAttributesCount=e.droppedAttributesCount>>>0),e.events){if(!Array.isArray(e.events))throw TypeError(`.opentelemetry.proto.trace.v1.Span.events: array expected`);t.events=[];for(var s=0;s<e.events.length;++s){if(typeof e.events[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.Span.events: object expected`);t.events[s]=E.opentelemetry.proto.trace.v1.Span.Event.fromObject(e.events[s])}}if(e.droppedEventsCount!=null&&(t.droppedEventsCount=e.droppedEventsCount>>>0),e.links){if(!Array.isArray(e.links))throw TypeError(`.opentelemetry.proto.trace.v1.Span.links: array expected`);t.links=[];for(var s=0;s<e.links.length;++s){if(typeof e.links[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.Span.links: object expected`);t.links[s]=E.opentelemetry.proto.trace.v1.Span.Link.fromObject(e.links[s])}}if(e.droppedLinksCount!=null&&(t.droppedLinksCount=e.droppedLinksCount>>>0),e.status!=null){if(typeof e.status!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.Span.status: object expected`);t.status=E.opentelemetry.proto.trace.v1.Status.fromObject(e.status)}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[],s.events=[],s.links=[]),t.defaults){if(t.bytes===String?s.traceId=``:(s.traceId=[],t.bytes!==Array&&(s.traceId=w.newBuffer(s.traceId))),t.bytes===String?s.spanId=``:(s.spanId=[],t.bytes!==Array&&(s.spanId=w.newBuffer(s.spanId))),s.traceState=``,t.bytes===String?s.parentSpanId=``:(s.parentSpanId=[],t.bytes!==Array&&(s.parentSpanId=w.newBuffer(s.parentSpanId))),s.name=``,s.kind=t.enums===String?`SPAN_KIND_UNSPECIFIED`:0,w.Long){var g=new w.Long(0,0,!1);s.startTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.startTimeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.endTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.endTimeUnixNano=t.longs===String?`0`:0;s.droppedAttributesCount=0,s.droppedEventsCount=0,s.droppedLinksCount=0,s.status=null,s.flags=0}if(e.traceId!=null&&e.hasOwnProperty(`traceId`)&&(s.traceId=t.bytes===String?w.base64.encode(e.traceId,0,e.traceId.length):t.bytes===Array?Array.prototype.slice.call(e.traceId):e.traceId),e.spanId!=null&&e.hasOwnProperty(`spanId`)&&(s.spanId=t.bytes===String?w.base64.encode(e.spanId,0,e.spanId.length):t.bytes===Array?Array.prototype.slice.call(e.spanId):e.spanId),e.traceState!=null&&e.hasOwnProperty(`traceState`)&&(s.traceState=e.traceState),e.parentSpanId!=null&&e.hasOwnProperty(`parentSpanId`)&&(s.parentSpanId=t.bytes===String?w.base64.encode(e.parentSpanId,0,e.parentSpanId.length):t.bytes===Array?Array.prototype.slice.call(e.parentSpanId):e.parentSpanId),e.name!=null&&e.hasOwnProperty(`name`)&&(s.name=e.name),e.kind!=null&&e.hasOwnProperty(`kind`)&&(s.kind=t.enums===String?E.opentelemetry.proto.trace.v1.Span.SpanKind[e.kind]===void 0?e.kind:E.opentelemetry.proto.trace.v1.Span.SpanKind[e.kind]:e.kind),e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&(typeof e.startTimeUnixNano==`number`?s.startTimeUnixNano=t.longs===String?String(e.startTimeUnixNano):e.startTimeUnixNano:s.startTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.startTimeUnixNano):t.longs===Number?new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber():e.startTimeUnixNano),e.endTimeUnixNano!=null&&e.hasOwnProperty(`endTimeUnixNano`)&&(typeof e.endTimeUnixNano==`number`?s.endTimeUnixNano=t.longs===String?String(e.endTimeUnixNano):e.endTimeUnixNano:s.endTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.endTimeUnixNano):t.longs===Number?new w.LongBits(e.endTimeUnixNano.low>>>0,e.endTimeUnixNano.high>>>0).toNumber():e.endTimeUnixNano),e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}if(e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&(s.droppedAttributesCount=e.droppedAttributesCount),e.events&&e.events.length){s.events=[];for(var S=0;S<e.events.length;++S)s.events[S]=E.opentelemetry.proto.trace.v1.Span.Event.toObject(e.events[S],t)}if(e.droppedEventsCount!=null&&e.hasOwnProperty(`droppedEventsCount`)&&(s.droppedEventsCount=e.droppedEventsCount),e.links&&e.links.length){s.links=[];for(var S=0;S<e.links.length;++S)s.links[S]=E.opentelemetry.proto.trace.v1.Span.Link.toObject(e.links[S],t)}return e.droppedLinksCount!=null&&e.hasOwnProperty(`droppedLinksCount`)&&(s.droppedLinksCount=e.droppedLinksCount),e.status!=null&&e.hasOwnProperty(`status`)&&(s.status=E.opentelemetry.proto.trace.v1.Status.toObject(e.status,t)),e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.Span`},e.SpanKind=(function(){var e={},t=Object.create(e);return t[e[0]=`SPAN_KIND_UNSPECIFIED`]=0,t[e[1]=`SPAN_KIND_INTERNAL`]=1,t[e[2]=`SPAN_KIND_SERVER`]=2,t[e[3]=`SPAN_KIND_CLIENT`]=3,t[e[4]=`SPAN_KIND_PRODUCER`]=4,t[e[5]=`SPAN_KIND_CONSUMER`]=5,t})(),e.Event=(function(){function e(e){if(this.attributes=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.timeUnixNano=null,e.prototype.name=null,e.prototype.attributes=w.emptyArray,e.prototype.droppedAttributesCount=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(9).fixed64(e.timeUnixNano),e.name!=null&&Object.hasOwnProperty.call(e,`name`)&&t.uint32(18).string(e.name),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(26).fork()).ldelim();return e.droppedAttributesCount!=null&&Object.hasOwnProperty.call(e,`droppedAttributesCount`)&&t.uint32(32).uint32(e.droppedAttributesCount),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.Span.Event;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.timeUnixNano=e.fixed64();break;case 2:w.name=e.string();break;case 3:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 4:w.droppedAttributesCount=e.uint32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.name!=null&&e.hasOwnProperty(`name`)&&!w.isString(e.name))return`name: string expected`;if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var t=0;t<e.attributes.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[t]);if(s)return`attributes.`+s}}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&!w.isInteger(e.droppedAttributesCount)?`droppedAttributesCount: integer expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.Span.Event)return e;var t=new E.opentelemetry.proto.trace.v1.Span.Event;if(e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.name!=null&&(t.name=String(e.name)),e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.trace.v1.Span.Event.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.Span.Event.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}return e.droppedAttributesCount!=null&&(t.droppedAttributesCount=e.droppedAttributesCount>>>0),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;s.name=``,s.droppedAttributesCount=0}if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.name!=null&&e.hasOwnProperty(`name`)&&(s.name=e.name),e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&(s.droppedAttributesCount=e.droppedAttributesCount),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.Span.Event`},e})(),e.Link=(function(){function e(e){if(this.attributes=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.traceId=null,e.prototype.spanId=null,e.prototype.traceState=null,e.prototype.attributes=w.emptyArray,e.prototype.droppedAttributesCount=null,e.prototype.flags=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.traceId!=null&&Object.hasOwnProperty.call(e,`traceId`)&&t.uint32(10).bytes(e.traceId),e.spanId!=null&&Object.hasOwnProperty.call(e,`spanId`)&&t.uint32(18).bytes(e.spanId),e.traceState!=null&&Object.hasOwnProperty.call(e,`traceState`)&&t.uint32(26).string(e.traceState),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(34).fork()).ldelim();return e.droppedAttributesCount!=null&&Object.hasOwnProperty.call(e,`droppedAttributesCount`)&&t.uint32(40).uint32(e.droppedAttributesCount),e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(53).fixed32(e.flags),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.Span.Link;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.traceId=e.bytes();break;case 2:w.spanId=e.bytes();break;case 3:w.traceState=e.string();break;case 4:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 5:w.droppedAttributesCount=e.uint32();break;case 6:w.flags=e.fixed32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.traceId!=null&&e.hasOwnProperty(`traceId`)&&!(e.traceId&&typeof e.traceId.length==`number`||w.isString(e.traceId)))return`traceId: buffer expected`;if(e.spanId!=null&&e.hasOwnProperty(`spanId`)&&!(e.spanId&&typeof e.spanId.length==`number`||w.isString(e.spanId)))return`spanId: buffer expected`;if(e.traceState!=null&&e.hasOwnProperty(`traceState`)&&!w.isString(e.traceState))return`traceState: string expected`;if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var t=0;t<e.attributes.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[t]);if(s)return`attributes.`+s}}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&!w.isInteger(e.droppedAttributesCount)?`droppedAttributesCount: integer expected`:e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags)?`flags: integer expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.Span.Link)return e;var t=new E.opentelemetry.proto.trace.v1.Span.Link;if(e.traceId!=null&&(typeof e.traceId==`string`?w.base64.decode(e.traceId,t.traceId=w.newBuffer(w.base64.length(e.traceId)),0):e.traceId.length>=0&&(t.traceId=e.traceId)),e.spanId!=null&&(typeof e.spanId==`string`?w.base64.decode(e.spanId,t.spanId=w.newBuffer(w.base64.length(e.spanId)),0):e.spanId.length>=0&&(t.spanId=e.spanId)),e.traceState!=null&&(t.traceState=String(e.traceState)),e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.trace.v1.Span.Link.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.Span.Link.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}return e.droppedAttributesCount!=null&&(t.droppedAttributesCount=e.droppedAttributesCount>>>0),e.flags!=null&&(t.flags=e.flags>>>0),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[]),t.defaults&&(t.bytes===String?s.traceId=``:(s.traceId=[],t.bytes!==Array&&(s.traceId=w.newBuffer(s.traceId))),t.bytes===String?s.spanId=``:(s.spanId=[],t.bytes!==Array&&(s.spanId=w.newBuffer(s.spanId))),s.traceState=``,s.droppedAttributesCount=0,s.flags=0),e.traceId!=null&&e.hasOwnProperty(`traceId`)&&(s.traceId=t.bytes===String?w.base64.encode(e.traceId,0,e.traceId.length):t.bytes===Array?Array.prototype.slice.call(e.traceId):e.traceId),e.spanId!=null&&e.hasOwnProperty(`spanId`)&&(s.spanId=t.bytes===String?w.base64.encode(e.spanId,0,e.spanId.length):t.bytes===Array?Array.prototype.slice.call(e.spanId):e.spanId),e.traceState!=null&&e.hasOwnProperty(`traceState`)&&(s.traceState=e.traceState),e.attributes&&e.attributes.length){s.attributes=[];for(var g=0;g<e.attributes.length;++g)s.attributes[g]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[g],t)}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&(s.droppedAttributesCount=e.droppedAttributesCount),e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.Span.Link`},e})(),e})(),e.Status=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.message=null,e.prototype.code=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.message!=null&&Object.hasOwnProperty.call(e,`message`)&&t.uint32(18).string(e.message),e.code!=null&&Object.hasOwnProperty.call(e,`code`)&&t.uint32(24).int32(e.code),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.Status;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 2:w.message=e.string();break;case 3:w.code=e.int32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.message!=null&&e.hasOwnProperty(`message`)&&!w.isString(e.message))return`message: string expected`;if(e.code!=null&&e.hasOwnProperty(`code`))switch(e.code){default:return`code: enum value expected`;case 0:case 1:case 2:break}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.Status)return e;var t=new E.opentelemetry.proto.trace.v1.Status;switch(e.message!=null&&(t.message=String(e.message)),e.code){default:if(typeof e.code==`number`){t.code=e.code;break}break;case`STATUS_CODE_UNSET`:case 0:t.code=0;break;case`STATUS_CODE_OK`:case 1:t.code=1;break;case`STATUS_CODE_ERROR`:case 2:t.code=2;break}return t},e.toObject=function(e,t){t||={};var s={};return t.defaults&&(s.message=``,s.code=t.enums===String?`STATUS_CODE_UNSET`:0),e.message!=null&&e.hasOwnProperty(`message`)&&(s.message=e.message),e.code!=null&&e.hasOwnProperty(`code`)&&(s.code=t.enums===String?E.opentelemetry.proto.trace.v1.Status.StatusCode[e.code]===void 0?e.code:E.opentelemetry.proto.trace.v1.Status.StatusCode[e.code]:e.code),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.Status`},e.StatusCode=(function(){var e={},t=Object.create(e);return t[e[0]=`STATUS_CODE_UNSET`]=0,t[e[1]=`STATUS_CODE_OK`]=1,t[e[2]=`STATUS_CODE_ERROR`]=2,t})(),e})(),e.SpanFlags=(function(){var e={},t=Object.create(e);return t[e[0]=`SPAN_FLAGS_DO_NOT_USE`]=0,t[e[255]=`SPAN_FLAGS_TRACE_FLAGS_MASK`]=255,t[e[256]=`SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK`]=256,t[e[512]=`SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK`]=512,t})(),e})(),e})(),e.collector=(function(){var e={};return e.trace=(function(){var e={};return e.v1=(function(){var e={};return e.TraceService=(function(){function e(e,t,g){s.rpc.Service.call(this,e,t,g)}return(e.prototype=Object.create(s.rpc.Service.prototype)).constructor=e,e.create=function(e,t,s){return new this(e,t,s)},Object.defineProperty(e.prototype.export=function e(t,s){return this.rpcCall(e,E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest,E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse,t,s)},`name`,{value:`Export`}),e})(),e.ExportTraceServiceRequest=(function(){function e(e){if(this.resourceSpans=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resourceSpans=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resourceSpans!=null&&e.resourceSpans.length)for(var s=0;s<e.resourceSpans.length;++s)E.opentelemetry.proto.trace.v1.ResourceSpans.encode(e.resourceSpans[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resourceSpans&&w.resourceSpans.length||(w.resourceSpans=[]),w.resourceSpans.push(E.opentelemetry.proto.trace.v1.ResourceSpans.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resourceSpans!=null&&e.hasOwnProperty(`resourceSpans`)){if(!Array.isArray(e.resourceSpans))return`resourceSpans: array expected`;for(var t=0;t<e.resourceSpans.length;++t){var s=E.opentelemetry.proto.trace.v1.ResourceSpans.verify(e.resourceSpans[t]);if(s)return`resourceSpans.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest)return e;var t=new E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest;if(e.resourceSpans){if(!Array.isArray(e.resourceSpans))throw TypeError(`.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: array expected`);t.resourceSpans=[];for(var s=0;s<e.resourceSpans.length;++s){if(typeof e.resourceSpans[s]!=`object`)throw TypeError(`.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: object expected`);t.resourceSpans[s]=E.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(e.resourceSpans[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.resourceSpans=[]),e.resourceSpans&&e.resourceSpans.length){s.resourceSpans=[];for(var g=0;g<e.resourceSpans.length;++g)s.resourceSpans[g]=E.opentelemetry.proto.trace.v1.ResourceSpans.toObject(e.resourceSpans[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest`},e})(),e.ExportTraceServiceResponse=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.partialSuccess=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.partialSuccess!=null&&Object.hasOwnProperty.call(e,`partialSuccess`)&&E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.encode(e.partialSuccess,t.uint32(10).fork()).ldelim(),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.partialSuccess=E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.decode(e,e.uint32());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.partialSuccess!=null&&e.hasOwnProperty(`partialSuccess`)){var t=E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.verify(e.partialSuccess);if(t)return`partialSuccess.`+t}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse)return e;var t=new E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse;if(e.partialSuccess!=null){if(typeof e.partialSuccess!=`object`)throw TypeError(`.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse.partialSuccess: object expected`);t.partialSuccess=E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.fromObject(e.partialSuccess)}return t},e.toObject=function(e,t){t||={};var s={};return t.defaults&&(s.partialSuccess=null),e.partialSuccess!=null&&e.hasOwnProperty(`partialSuccess`)&&(s.partialSuccess=E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.toObject(e.partialSuccess,t)),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse`},e})(),e.ExportTracePartialSuccess=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.rejectedSpans=null,e.prototype.errorMessage=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.rejectedSpans!=null&&Object.hasOwnProperty.call(e,`rejectedSpans`)&&t.uint32(8).int64(e.rejectedSpans),e.errorMessage!=null&&Object.hasOwnProperty.call(e,`errorMessage`)&&t.uint32(18).string(e.errorMessage),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.rejectedSpans=e.int64();break;case 2:w.errorMessage=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){return typeof e!=`object`||!e?`object expected`:e.rejectedSpans!=null&&e.hasOwnProperty(`rejectedSpans`)&&!w.isInteger(e.rejectedSpans)&&!(e.rejectedSpans&&w.isInteger(e.rejectedSpans.low)&&w.isInteger(e.rejectedSpans.high))?`rejectedSpans: integer|Long expected`:e.errorMessage!=null&&e.hasOwnProperty(`errorMessage`)&&!w.isString(e.errorMessage)?`errorMessage: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess)return e;var t=new E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess;return e.rejectedSpans!=null&&(w.Long?(t.rejectedSpans=w.Long.fromValue(e.rejectedSpans)).unsigned=!1:typeof e.rejectedSpans==`string`?t.rejectedSpans=parseInt(e.rejectedSpans,10):typeof e.rejectedSpans==`number`?t.rejectedSpans=e.rejectedSpans:typeof e.rejectedSpans==`object`&&(t.rejectedSpans=new w.LongBits(e.rejectedSpans.low>>>0,e.rejectedSpans.high>>>0).toNumber())),e.errorMessage!=null&&(t.errorMessage=String(e.errorMessage)),t},e.toObject=function(e,t){t||={};var s={};if(t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.rejectedSpans=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.rejectedSpans=t.longs===String?`0`:0;s.errorMessage=``}return e.rejectedSpans!=null&&e.hasOwnProperty(`rejectedSpans`)&&(typeof e.rejectedSpans==`number`?s.rejectedSpans=t.longs===String?String(e.rejectedSpans):e.rejectedSpans:s.rejectedSpans=t.longs===String?w.Long.prototype.toString.call(e.rejectedSpans):t.longs===Number?new w.LongBits(e.rejectedSpans.low>>>0,e.rejectedSpans.high>>>0).toNumber():e.rejectedSpans),e.errorMessage!=null&&e.hasOwnProperty(`errorMessage`)&&(s.errorMessage=e.errorMessage),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess`},e})(),e})(),e})(),e.metrics=(function(){var e={};return e.v1=(function(){var e={};return e.MetricsService=(function(){function e(e,t,g){s.rpc.Service.call(this,e,t,g)}return(e.prototype=Object.create(s.rpc.Service.prototype)).constructor=e,e.create=function(e,t,s){return new this(e,t,s)},Object.defineProperty(e.prototype.export=function e(t,s){return this.rpcCall(e,E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest,E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse,t,s)},`name`,{value:`Export`}),e})(),e.ExportMetricsServiceRequest=(function(){function e(e){if(this.resourceMetrics=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resourceMetrics=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resourceMetrics!=null&&e.resourceMetrics.length)for(var s=0;s<e.resourceMetrics.length;++s)E.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(e.resourceMetrics[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resourceMetrics&&w.resourceMetrics.length||(w.resourceMetrics=[]),w.resourceMetrics.push(E.opentelemetry.proto.metrics.v1.ResourceMetrics.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resourceMetrics!=null&&e.hasOwnProperty(`resourceMetrics`)){if(!Array.isArray(e.resourceMetrics))return`resourceMetrics: array expected`;for(var t=0;t<e.resourceMetrics.length;++t){var s=E.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(e.resourceMetrics[t]);if(s)return`resourceMetrics.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest)return e;var t=new E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest;if(e.resourceMetrics){if(!Array.isArray(e.resourceMetrics))throw TypeError(`.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: array expected`);t.resourceMetrics=[];for(var s=0;s<e.resourceMetrics.length;++s){if(typeof e.resourceMetrics[s]!=`object`)throw TypeError(`.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: object expected`);t.resourceMetrics[s]=E.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(e.resourceMetrics[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.resourceMetrics=[]),e.resourceMetrics&&e.resourceMetrics.length){s.resourceMetrics=[];for(var g=0;g<e.resourceMetrics.length;++g)s.resourceMetrics[g]=E.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(e.resourceMetrics[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest`},e})(),e.ExportMetricsServiceResponse=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.partialSuccess=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.partialSuccess!=null&&Object.hasOwnProperty.call(e,`partialSuccess`)&&E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.encode(e.partialSuccess,t.uint32(10).fork()).ldelim(),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.partialSuccess=E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.decode(e,e.uint32());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.partialSuccess!=null&&e.hasOwnProperty(`partialSuccess`)){var t=E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.verify(e.partialSuccess);if(t)return`partialSuccess.`+t}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse)return e;var t=new E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse;if(e.partialSuccess!=null){if(typeof e.partialSuccess!=`object`)throw TypeError(`.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse.partialSuccess: object expected`);t.partialSuccess=E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.fromObject(e.partialSuccess)}return t},e.toObject=function(e,t){t||={};var s={};return t.defaults&&(s.partialSuccess=null),e.partialSuccess!=null&&e.hasOwnProperty(`partialSuccess`)&&(s.partialSuccess=E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.toObject(e.partialSuccess,t)),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse`},e})(),e.ExportMetricsPartialSuccess=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.rejectedDataPoints=null,e.prototype.errorMessage=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.rejectedDataPoints!=null&&Object.hasOwnProperty.call(e,`rejectedDataPoints`)&&t.uint32(8).int64(e.rejectedDataPoints),e.errorMessage!=null&&Object.hasOwnProperty.call(e,`errorMessage`)&&t.uint32(18).string(e.errorMessage),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.rejectedDataPoints=e.int64();break;case 2:w.errorMessage=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){return typeof e!=`object`||!e?`object expected`:e.rejectedDataPoints!=null&&e.hasOwnProperty(`rejectedDataPoints`)&&!w.isInteger(e.rejectedDataPoints)&&!(e.rejectedDataPoints&&w.isInteger(e.rejectedDataPoints.low)&&w.isInteger(e.rejectedDataPoints.high))?`rejectedDataPoints: integer|Long expected`:e.errorMessage!=null&&e.hasOwnProperty(`errorMessage`)&&!w.isString(e.errorMessage)?`errorMessage: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess)return e;var t=new E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess;return e.rejectedDataPoints!=null&&(w.Long?(t.rejectedDataPoints=w.Long.fromValue(e.rejectedDataPoints)).unsigned=!1:typeof e.rejectedDataPoints==`string`?t.rejectedDataPoints=parseInt(e.rejectedDataPoints,10):typeof e.rejectedDataPoints==`number`?t.rejectedDataPoints=e.rejectedDataPoints:typeof e.rejectedDataPoints==`object`&&(t.rejectedDataPoints=new w.LongBits(e.rejectedDataPoints.low>>>0,e.rejectedDataPoints.high>>>0).toNumber())),e.errorMessage!=null&&(t.errorMessage=String(e.errorMessage)),t},e.toObject=function(e,t){t||={};var s={};if(t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.rejectedDataPoints=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.rejectedDataPoints=t.longs===String?`0`:0;s.errorMessage=``}return e.rejectedDataPoints!=null&&e.hasOwnProperty(`rejectedDataPoints`)&&(typeof e.rejectedDataPoints==`number`?s.rejectedDataPoints=t.longs===String?String(e.rejectedDataPoints):e.rejectedDataPoints:s.rejectedDataPoints=t.longs===String?w.Long.prototype.toString.call(e.rejectedDataPoints):t.longs===Number?new w.LongBits(e.rejectedDataPoints.low>>>0,e.rejectedDataPoints.high>>>0).toNumber():e.rejectedDataPoints),e.errorMessage!=null&&e.hasOwnProperty(`errorMessage`)&&(s.errorMessage=e.errorMessage),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess`},e})(),e})(),e})(),e.logs=(function(){var e={};return e.v1=(function(){var e={};return e.LogsService=(function(){function e(e,t,g){s.rpc.Service.call(this,e,t,g)}return(e.prototype=Object.create(s.rpc.Service.prototype)).constructor=e,e.create=function(e,t,s){return new this(e,t,s)},Object.defineProperty(e.prototype.export=function e(t,s){return this.rpcCall(e,E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest,E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse,t,s)},`name`,{value:`Export`}),e})(),e.ExportLogsServiceRequest=(function(){function e(e){if(this.resourceLogs=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resourceLogs=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resourceLogs!=null&&e.resourceLogs.length)for(var s=0;s<e.resourceLogs.length;++s)E.opentelemetry.proto.logs.v1.ResourceLogs.encode(e.resourceLogs[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resourceLogs&&w.resourceLogs.length||(w.resourceLogs=[]),w.resourceLogs.push(E.opentelemetry.proto.logs.v1.ResourceLogs.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resourceLogs!=null&&e.hasOwnProperty(`resourceLogs`)){if(!Array.isArray(e.resourceLogs))return`resourceLogs: array expected`;for(var t=0;t<e.resourceLogs.length;++t){var s=E.opentelemetry.proto.logs.v1.ResourceLogs.verify(e.resourceLogs[t]);if(s)return`resourceLogs.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest)return e;var t=new E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest;if(e.resourceLogs){if(!Array.isArray(e.resourceLogs))throw TypeError(`.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: array expected`);t.resourceLogs=[];for(var s=0;s<e.resourceLogs.length;++s){if(typeof e.resourceLogs[s]!=`object`)throw TypeError(`.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: object expected`);t.resourceLogs[s]=E.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(e.resourceLogs[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.resourceLogs=[]),e.resourceLogs&&e.resourceLogs.length){s.resourceLogs=[];for(var g=0;g<e.resourceLogs.length;++g)s.resourceLogs[g]=E.opentelemetry.proto.logs.v1.ResourceLogs.toObject(e.resourceLogs[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest`},e})(),e.ExportLogsServiceResponse=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.partialSuccess=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.partialSuccess!=null&&Object.hasOwnProperty.call(e,`partialSuccess`)&&E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.encode(e.partialSuccess,t.uint32(10).fork()).ldelim(),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.partialSuccess=E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.decode(e,e.uint32());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.partialSuccess!=null&&e.hasOwnProperty(`partialSuccess`)){var t=E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.verify(e.partialSuccess);if(t)return`partialSuccess.`+t}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse)return e;var t=new E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse;if(e.partialSuccess!=null){if(typeof e.partialSuccess!=`object`)throw TypeError(`.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse.partialSuccess: object expected`);t.partialSuccess=E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.fromObject(e.partialSuccess)}return t},e.toObject=function(e,t){t||={};var s={};return t.defaults&&(s.partialSuccess=null),e.partialSuccess!=null&&e.hasOwnProperty(`partialSuccess`)&&(s.partialSuccess=E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.toObject(e.partialSuccess,t)),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse`},e})(),e.ExportLogsPartialSuccess=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.rejectedLogRecords=null,e.prototype.errorMessage=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.rejectedLogRecords!=null&&Object.hasOwnProperty.call(e,`rejectedLogRecords`)&&t.uint32(8).int64(e.rejectedLogRecords),e.errorMessage!=null&&Object.hasOwnProperty.call(e,`errorMessage`)&&t.uint32(18).string(e.errorMessage),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.rejectedLogRecords=e.int64();break;case 2:w.errorMessage=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){return typeof e!=`object`||!e?`object expected`:e.rejectedLogRecords!=null&&e.hasOwnProperty(`rejectedLogRecords`)&&!w.isInteger(e.rejectedLogRecords)&&!(e.rejectedLogRecords&&w.isInteger(e.rejectedLogRecords.low)&&w.isInteger(e.rejectedLogRecords.high))?`rejectedLogRecords: integer|Long expected`:e.errorMessage!=null&&e.hasOwnProperty(`errorMessage`)&&!w.isString(e.errorMessage)?`errorMessage: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess)return e;var t=new E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess;return e.rejectedLogRecords!=null&&(w.Long?(t.rejectedLogRecords=w.Long.fromValue(e.rejectedLogRecords)).unsigned=!1:typeof e.rejectedLogRecords==`string`?t.rejectedLogRecords=parseInt(e.rejectedLogRecords,10):typeof e.rejectedLogRecords==`number`?t.rejectedLogRecords=e.rejectedLogRecords:typeof e.rejectedLogRecords==`object`&&(t.rejectedLogRecords=new w.LongBits(e.rejectedLogRecords.low>>>0,e.rejectedLogRecords.high>>>0).toNumber())),e.errorMessage!=null&&(t.errorMessage=String(e.errorMessage)),t},e.toObject=function(e,t){t||={};var s={};if(t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.rejectedLogRecords=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.rejectedLogRecords=t.longs===String?`0`:0;s.errorMessage=``}return e.rejectedLogRecords!=null&&e.hasOwnProperty(`rejectedLogRecords`)&&(typeof e.rejectedLogRecords==`number`?s.rejectedLogRecords=t.longs===String?String(e.rejectedLogRecords):e.rejectedLogRecords:s.rejectedLogRecords=t.longs===String?w.Long.prototype.toString.call(e.rejectedLogRecords):t.longs===Number?new w.LongBits(e.rejectedLogRecords.low>>>0,e.rejectedLogRecords.high>>>0).toNumber():e.rejectedLogRecords),e.errorMessage!=null&&e.hasOwnProperty(`errorMessage`)&&(s.errorMessage=e.errorMessage),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess`},e})(),e})(),e})(),e})(),e.metrics=(function(){var e={};return e.v1=(function(){var e={};return e.MetricsData=(function(){function e(e){if(this.resourceMetrics=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resourceMetrics=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resourceMetrics!=null&&e.resourceMetrics.length)for(var s=0;s<e.resourceMetrics.length;++s)E.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(e.resourceMetrics[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.MetricsData;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resourceMetrics&&w.resourceMetrics.length||(w.resourceMetrics=[]),w.resourceMetrics.push(E.opentelemetry.proto.metrics.v1.ResourceMetrics.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resourceMetrics!=null&&e.hasOwnProperty(`resourceMetrics`)){if(!Array.isArray(e.resourceMetrics))return`resourceMetrics: array expected`;for(var t=0;t<e.resourceMetrics.length;++t){var s=E.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(e.resourceMetrics[t]);if(s)return`resourceMetrics.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.MetricsData)return e;var t=new E.opentelemetry.proto.metrics.v1.MetricsData;if(e.resourceMetrics){if(!Array.isArray(e.resourceMetrics))throw TypeError(`.opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: array expected`);t.resourceMetrics=[];for(var s=0;s<e.resourceMetrics.length;++s){if(typeof e.resourceMetrics[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: object expected`);t.resourceMetrics[s]=E.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(e.resourceMetrics[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.resourceMetrics=[]),e.resourceMetrics&&e.resourceMetrics.length){s.resourceMetrics=[];for(var g=0;g<e.resourceMetrics.length;++g)s.resourceMetrics[g]=E.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(e.resourceMetrics[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.MetricsData`},e})(),e.ResourceMetrics=(function(){function e(e){if(this.scopeMetrics=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resource=null,e.prototype.scopeMetrics=w.emptyArray,e.prototype.schemaUrl=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resource!=null&&Object.hasOwnProperty.call(e,`resource`)&&E.opentelemetry.proto.resource.v1.Resource.encode(e.resource,t.uint32(10).fork()).ldelim(),e.scopeMetrics!=null&&e.scopeMetrics.length)for(var s=0;s<e.scopeMetrics.length;++s)E.opentelemetry.proto.metrics.v1.ScopeMetrics.encode(e.scopeMetrics[s],t.uint32(18).fork()).ldelim();return e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(26).string(e.schemaUrl),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.ResourceMetrics;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resource=E.opentelemetry.proto.resource.v1.Resource.decode(e,e.uint32());break;case 2:w.scopeMetrics&&w.scopeMetrics.length||(w.scopeMetrics=[]),w.scopeMetrics.push(E.opentelemetry.proto.metrics.v1.ScopeMetrics.decode(e,e.uint32()));break;case 3:w.schemaUrl=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resource!=null&&e.hasOwnProperty(`resource`)){var t=E.opentelemetry.proto.resource.v1.Resource.verify(e.resource);if(t)return`resource.`+t}if(e.scopeMetrics!=null&&e.hasOwnProperty(`scopeMetrics`)){if(!Array.isArray(e.scopeMetrics))return`scopeMetrics: array expected`;for(var s=0;s<e.scopeMetrics.length;++s){var t=E.opentelemetry.proto.metrics.v1.ScopeMetrics.verify(e.scopeMetrics[s]);if(t)return`scopeMetrics.`+t}}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl)?`schemaUrl: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.ResourceMetrics)return e;var t=new E.opentelemetry.proto.metrics.v1.ResourceMetrics;if(e.resource!=null){if(typeof e.resource!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ResourceMetrics.resource: object expected`);t.resource=E.opentelemetry.proto.resource.v1.Resource.fromObject(e.resource)}if(e.scopeMetrics){if(!Array.isArray(e.scopeMetrics))throw TypeError(`.opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: array expected`);t.scopeMetrics=[];for(var s=0;s<e.scopeMetrics.length;++s){if(typeof e.scopeMetrics[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: object expected`);t.scopeMetrics[s]=E.opentelemetry.proto.metrics.v1.ScopeMetrics.fromObject(e.scopeMetrics[s])}}return e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.scopeMetrics=[]),t.defaults&&(s.resource=null,s.schemaUrl=``),e.resource!=null&&e.hasOwnProperty(`resource`)&&(s.resource=E.opentelemetry.proto.resource.v1.Resource.toObject(e.resource,t)),e.scopeMetrics&&e.scopeMetrics.length){s.scopeMetrics=[];for(var g=0;g<e.scopeMetrics.length;++g)s.scopeMetrics[g]=E.opentelemetry.proto.metrics.v1.ScopeMetrics.toObject(e.scopeMetrics[g],t)}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.ResourceMetrics`},e})(),e.ScopeMetrics=(function(){function e(e){if(this.metrics=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.scope=null,e.prototype.metrics=w.emptyArray,e.prototype.schemaUrl=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.scope!=null&&Object.hasOwnProperty.call(e,`scope`)&&E.opentelemetry.proto.common.v1.InstrumentationScope.encode(e.scope,t.uint32(10).fork()).ldelim(),e.metrics!=null&&e.metrics.length)for(var s=0;s<e.metrics.length;++s)E.opentelemetry.proto.metrics.v1.Metric.encode(e.metrics[s],t.uint32(18).fork()).ldelim();return e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(26).string(e.schemaUrl),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.ScopeMetrics;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.decode(e,e.uint32());break;case 2:w.metrics&&w.metrics.length||(w.metrics=[]),w.metrics.push(E.opentelemetry.proto.metrics.v1.Metric.decode(e,e.uint32()));break;case 3:w.schemaUrl=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.scope!=null&&e.hasOwnProperty(`scope`)){var t=E.opentelemetry.proto.common.v1.InstrumentationScope.verify(e.scope);if(t)return`scope.`+t}if(e.metrics!=null&&e.hasOwnProperty(`metrics`)){if(!Array.isArray(e.metrics))return`metrics: array expected`;for(var s=0;s<e.metrics.length;++s){var t=E.opentelemetry.proto.metrics.v1.Metric.verify(e.metrics[s]);if(t)return`metrics.`+t}}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl)?`schemaUrl: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.ScopeMetrics)return e;var t=new E.opentelemetry.proto.metrics.v1.ScopeMetrics;if(e.scope!=null){if(typeof e.scope!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ScopeMetrics.scope: object expected`);t.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(e.scope)}if(e.metrics){if(!Array.isArray(e.metrics))throw TypeError(`.opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: array expected`);t.metrics=[];for(var s=0;s<e.metrics.length;++s){if(typeof e.metrics[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: object expected`);t.metrics[s]=E.opentelemetry.proto.metrics.v1.Metric.fromObject(e.metrics[s])}}return e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.metrics=[]),t.defaults&&(s.scope=null,s.schemaUrl=``),e.scope!=null&&e.hasOwnProperty(`scope`)&&(s.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.toObject(e.scope,t)),e.metrics&&e.metrics.length){s.metrics=[];for(var g=0;g<e.metrics.length;++g)s.metrics[g]=E.opentelemetry.proto.metrics.v1.Metric.toObject(e.metrics[g],t)}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.ScopeMetrics`},e})(),e.Metric=(function(){function e(e){if(this.metadata=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}e.prototype.name=null,e.prototype.description=null,e.prototype.unit=null,e.prototype.gauge=null,e.prototype.sum=null,e.prototype.histogram=null,e.prototype.exponentialHistogram=null,e.prototype.summary=null,e.prototype.metadata=w.emptyArray;var t;return Object.defineProperty(e.prototype,`data`,{get:w.oneOfGetter(t=[`gauge`,`sum`,`histogram`,`exponentialHistogram`,`summary`]),set:w.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.name!=null&&Object.hasOwnProperty.call(e,`name`)&&t.uint32(10).string(e.name),e.description!=null&&Object.hasOwnProperty.call(e,`description`)&&t.uint32(18).string(e.description),e.unit!=null&&Object.hasOwnProperty.call(e,`unit`)&&t.uint32(26).string(e.unit),e.gauge!=null&&Object.hasOwnProperty.call(e,`gauge`)&&E.opentelemetry.proto.metrics.v1.Gauge.encode(e.gauge,t.uint32(42).fork()).ldelim(),e.sum!=null&&Object.hasOwnProperty.call(e,`sum`)&&E.opentelemetry.proto.metrics.v1.Sum.encode(e.sum,t.uint32(58).fork()).ldelim(),e.histogram!=null&&Object.hasOwnProperty.call(e,`histogram`)&&E.opentelemetry.proto.metrics.v1.Histogram.encode(e.histogram,t.uint32(74).fork()).ldelim(),e.exponentialHistogram!=null&&Object.hasOwnProperty.call(e,`exponentialHistogram`)&&E.opentelemetry.proto.metrics.v1.ExponentialHistogram.encode(e.exponentialHistogram,t.uint32(82).fork()).ldelim(),e.summary!=null&&Object.hasOwnProperty.call(e,`summary`)&&E.opentelemetry.proto.metrics.v1.Summary.encode(e.summary,t.uint32(90).fork()).ldelim(),e.metadata!=null&&e.metadata.length)for(var s=0;s<e.metadata.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.metadata[s],t.uint32(98).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.Metric;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.name=e.string();break;case 2:w.description=e.string();break;case 3:w.unit=e.string();break;case 5:w.gauge=E.opentelemetry.proto.metrics.v1.Gauge.decode(e,e.uint32());break;case 7:w.sum=E.opentelemetry.proto.metrics.v1.Sum.decode(e,e.uint32());break;case 9:w.histogram=E.opentelemetry.proto.metrics.v1.Histogram.decode(e,e.uint32());break;case 10:w.exponentialHistogram=E.opentelemetry.proto.metrics.v1.ExponentialHistogram.decode(e,e.uint32());break;case 11:w.summary=E.opentelemetry.proto.metrics.v1.Summary.decode(e,e.uint32());break;case 12:w.metadata&&w.metadata.length||(w.metadata=[]),w.metadata.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;var t={};if(e.name!=null&&e.hasOwnProperty(`name`)&&!w.isString(e.name))return`name: string expected`;if(e.description!=null&&e.hasOwnProperty(`description`)&&!w.isString(e.description))return`description: string expected`;if(e.unit!=null&&e.hasOwnProperty(`unit`)&&!w.isString(e.unit))return`unit: string expected`;if(e.gauge!=null&&e.hasOwnProperty(`gauge`)){t.data=1;var s=E.opentelemetry.proto.metrics.v1.Gauge.verify(e.gauge);if(s)return`gauge.`+s}if(e.sum!=null&&e.hasOwnProperty(`sum`)){if(t.data===1)return`data: multiple values`;t.data=1;var s=E.opentelemetry.proto.metrics.v1.Sum.verify(e.sum);if(s)return`sum.`+s}if(e.histogram!=null&&e.hasOwnProperty(`histogram`)){if(t.data===1)return`data: multiple values`;t.data=1;var s=E.opentelemetry.proto.metrics.v1.Histogram.verify(e.histogram);if(s)return`histogram.`+s}if(e.exponentialHistogram!=null&&e.hasOwnProperty(`exponentialHistogram`)){if(t.data===1)return`data: multiple values`;t.data=1;var s=E.opentelemetry.proto.metrics.v1.ExponentialHistogram.verify(e.exponentialHistogram);if(s)return`exponentialHistogram.`+s}if(e.summary!=null&&e.hasOwnProperty(`summary`)){if(t.data===1)return`data: multiple values`;t.data=1;var s=E.opentelemetry.proto.metrics.v1.Summary.verify(e.summary);if(s)return`summary.`+s}if(e.metadata!=null&&e.hasOwnProperty(`metadata`)){if(!Array.isArray(e.metadata))return`metadata: array expected`;for(var g=0;g<e.metadata.length;++g){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.metadata[g]);if(s)return`metadata.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.Metric)return e;var t=new E.opentelemetry.proto.metrics.v1.Metric;if(e.name!=null&&(t.name=String(e.name)),e.description!=null&&(t.description=String(e.description)),e.unit!=null&&(t.unit=String(e.unit)),e.gauge!=null){if(typeof e.gauge!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.gauge: object expected`);t.gauge=E.opentelemetry.proto.metrics.v1.Gauge.fromObject(e.gauge)}if(e.sum!=null){if(typeof e.sum!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.sum: object expected`);t.sum=E.opentelemetry.proto.metrics.v1.Sum.fromObject(e.sum)}if(e.histogram!=null){if(typeof e.histogram!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.histogram: object expected`);t.histogram=E.opentelemetry.proto.metrics.v1.Histogram.fromObject(e.histogram)}if(e.exponentialHistogram!=null){if(typeof e.exponentialHistogram!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.exponentialHistogram: object expected`);t.exponentialHistogram=E.opentelemetry.proto.metrics.v1.ExponentialHistogram.fromObject(e.exponentialHistogram)}if(e.summary!=null){if(typeof e.summary!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.summary: object expected`);t.summary=E.opentelemetry.proto.metrics.v1.Summary.fromObject(e.summary)}if(e.metadata){if(!Array.isArray(e.metadata))throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.metadata: array expected`);t.metadata=[];for(var s=0;s<e.metadata.length;++s){if(typeof e.metadata[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.metadata: object expected`);t.metadata[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.metadata[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.metadata=[]),t.defaults&&(s.name=``,s.description=``,s.unit=``),e.name!=null&&e.hasOwnProperty(`name`)&&(s.name=e.name),e.description!=null&&e.hasOwnProperty(`description`)&&(s.description=e.description),e.unit!=null&&e.hasOwnProperty(`unit`)&&(s.unit=e.unit),e.gauge!=null&&e.hasOwnProperty(`gauge`)&&(s.gauge=E.opentelemetry.proto.metrics.v1.Gauge.toObject(e.gauge,t),t.oneofs&&(s.data=`gauge`)),e.sum!=null&&e.hasOwnProperty(`sum`)&&(s.sum=E.opentelemetry.proto.metrics.v1.Sum.toObject(e.sum,t),t.oneofs&&(s.data=`sum`)),e.histogram!=null&&e.hasOwnProperty(`histogram`)&&(s.histogram=E.opentelemetry.proto.metrics.v1.Histogram.toObject(e.histogram,t),t.oneofs&&(s.data=`histogram`)),e.exponentialHistogram!=null&&e.hasOwnProperty(`exponentialHistogram`)&&(s.exponentialHistogram=E.opentelemetry.proto.metrics.v1.ExponentialHistogram.toObject(e.exponentialHistogram,t),t.oneofs&&(s.data=`exponentialHistogram`)),e.summary!=null&&e.hasOwnProperty(`summary`)&&(s.summary=E.opentelemetry.proto.metrics.v1.Summary.toObject(e.summary,t),t.oneofs&&(s.data=`summary`)),e.metadata&&e.metadata.length){s.metadata=[];for(var g=0;g<e.metadata.length;++g)s.metadata[g]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.metadata[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.Metric`},e})(),e.Gauge=(function(){function e(e){if(this.dataPoints=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.dataPoints=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.dataPoints!=null&&e.dataPoints.length)for(var s=0;s<e.dataPoints.length;++s)E.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(e.dataPoints[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.Gauge;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.dataPoints&&w.dataPoints.length||(w.dataPoints=[]),w.dataPoints.push(E.opentelemetry.proto.metrics.v1.NumberDataPoint.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.dataPoints!=null&&e.hasOwnProperty(`dataPoints`)){if(!Array.isArray(e.dataPoints))return`dataPoints: array expected`;for(var t=0;t<e.dataPoints.length;++t){var s=E.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(e.dataPoints[t]);if(s)return`dataPoints.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.Gauge)return e;var t=new E.opentelemetry.proto.metrics.v1.Gauge;if(e.dataPoints){if(!Array.isArray(e.dataPoints))throw TypeError(`.opentelemetry.proto.metrics.v1.Gauge.dataPoints: array expected`);t.dataPoints=[];for(var s=0;s<e.dataPoints.length;++s){if(typeof e.dataPoints[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Gauge.dataPoints: object expected`);t.dataPoints[s]=E.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(e.dataPoints[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.dataPoints=[]),e.dataPoints&&e.dataPoints.length){s.dataPoints=[];for(var g=0;g<e.dataPoints.length;++g)s.dataPoints[g]=E.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(e.dataPoints[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.Gauge`},e})(),e.Sum=(function(){function e(e){if(this.dataPoints=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.dataPoints=w.emptyArray,e.prototype.aggregationTemporality=null,e.prototype.isMonotonic=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.dataPoints!=null&&e.dataPoints.length)for(var s=0;s<e.dataPoints.length;++s)E.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(e.dataPoints[s],t.uint32(10).fork()).ldelim();return e.aggregationTemporality!=null&&Object.hasOwnProperty.call(e,`aggregationTemporality`)&&t.uint32(16).int32(e.aggregationTemporality),e.isMonotonic!=null&&Object.hasOwnProperty.call(e,`isMonotonic`)&&t.uint32(24).bool(e.isMonotonic),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.Sum;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.dataPoints&&w.dataPoints.length||(w.dataPoints=[]),w.dataPoints.push(E.opentelemetry.proto.metrics.v1.NumberDataPoint.decode(e,e.uint32()));break;case 2:w.aggregationTemporality=e.int32();break;case 3:w.isMonotonic=e.bool();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.dataPoints!=null&&e.hasOwnProperty(`dataPoints`)){if(!Array.isArray(e.dataPoints))return`dataPoints: array expected`;for(var t=0;t<e.dataPoints.length;++t){var s=E.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(e.dataPoints[t]);if(s)return`dataPoints.`+s}}if(e.aggregationTemporality!=null&&e.hasOwnProperty(`aggregationTemporality`))switch(e.aggregationTemporality){default:return`aggregationTemporality: enum value expected`;case 0:case 1:case 2:break}return e.isMonotonic!=null&&e.hasOwnProperty(`isMonotonic`)&&typeof e.isMonotonic!=`boolean`?`isMonotonic: boolean expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.Sum)return e;var t=new E.opentelemetry.proto.metrics.v1.Sum;if(e.dataPoints){if(!Array.isArray(e.dataPoints))throw TypeError(`.opentelemetry.proto.metrics.v1.Sum.dataPoints: array expected`);t.dataPoints=[];for(var s=0;s<e.dataPoints.length;++s){if(typeof e.dataPoints[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Sum.dataPoints: object expected`);t.dataPoints[s]=E.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(e.dataPoints[s])}}switch(e.aggregationTemporality){default:if(typeof e.aggregationTemporality==`number`){t.aggregationTemporality=e.aggregationTemporality;break}break;case`AGGREGATION_TEMPORALITY_UNSPECIFIED`:case 0:t.aggregationTemporality=0;break;case`AGGREGATION_TEMPORALITY_DELTA`:case 1:t.aggregationTemporality=1;break;case`AGGREGATION_TEMPORALITY_CUMULATIVE`:case 2:t.aggregationTemporality=2;break}return e.isMonotonic!=null&&(t.isMonotonic=!!e.isMonotonic),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.dataPoints=[]),t.defaults&&(s.aggregationTemporality=t.enums===String?`AGGREGATION_TEMPORALITY_UNSPECIFIED`:0,s.isMonotonic=!1),e.dataPoints&&e.dataPoints.length){s.dataPoints=[];for(var g=0;g<e.dataPoints.length;++g)s.dataPoints[g]=E.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(e.dataPoints[g],t)}return e.aggregationTemporality!=null&&e.hasOwnProperty(`aggregationTemporality`)&&(s.aggregationTemporality=t.enums===String?E.opentelemetry.proto.metrics.v1.AggregationTemporality[e.aggregationTemporality]===void 0?e.aggregationTemporality:E.opentelemetry.proto.metrics.v1.AggregationTemporality[e.aggregationTemporality]:e.aggregationTemporality),e.isMonotonic!=null&&e.hasOwnProperty(`isMonotonic`)&&(s.isMonotonic=e.isMonotonic),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.Sum`},e})(),e.Histogram=(function(){function e(e){if(this.dataPoints=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.dataPoints=w.emptyArray,e.prototype.aggregationTemporality=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.dataPoints!=null&&e.dataPoints.length)for(var s=0;s<e.dataPoints.length;++s)E.opentelemetry.proto.metrics.v1.HistogramDataPoint.encode(e.dataPoints[s],t.uint32(10).fork()).ldelim();return e.aggregationTemporality!=null&&Object.hasOwnProperty.call(e,`aggregationTemporality`)&&t.uint32(16).int32(e.aggregationTemporality),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.Histogram;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.dataPoints&&w.dataPoints.length||(w.dataPoints=[]),w.dataPoints.push(E.opentelemetry.proto.metrics.v1.HistogramDataPoint.decode(e,e.uint32()));break;case 2:w.aggregationTemporality=e.int32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.dataPoints!=null&&e.hasOwnProperty(`dataPoints`)){if(!Array.isArray(e.dataPoints))return`dataPoints: array expected`;for(var t=0;t<e.dataPoints.length;++t){var s=E.opentelemetry.proto.metrics.v1.HistogramDataPoint.verify(e.dataPoints[t]);if(s)return`dataPoints.`+s}}if(e.aggregationTemporality!=null&&e.hasOwnProperty(`aggregationTemporality`))switch(e.aggregationTemporality){default:return`aggregationTemporality: enum value expected`;case 0:case 1:case 2:break}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.Histogram)return e;var t=new E.opentelemetry.proto.metrics.v1.Histogram;if(e.dataPoints){if(!Array.isArray(e.dataPoints))throw TypeError(`.opentelemetry.proto.metrics.v1.Histogram.dataPoints: array expected`);t.dataPoints=[];for(var s=0;s<e.dataPoints.length;++s){if(typeof e.dataPoints[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Histogram.dataPoints: object expected`);t.dataPoints[s]=E.opentelemetry.proto.metrics.v1.HistogramDataPoint.fromObject(e.dataPoints[s])}}switch(e.aggregationTemporality){default:if(typeof e.aggregationTemporality==`number`){t.aggregationTemporality=e.aggregationTemporality;break}break;case`AGGREGATION_TEMPORALITY_UNSPECIFIED`:case 0:t.aggregationTemporality=0;break;case`AGGREGATION_TEMPORALITY_DELTA`:case 1:t.aggregationTemporality=1;break;case`AGGREGATION_TEMPORALITY_CUMULATIVE`:case 2:t.aggregationTemporality=2;break}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.dataPoints=[]),t.defaults&&(s.aggregationTemporality=t.enums===String?`AGGREGATION_TEMPORALITY_UNSPECIFIED`:0),e.dataPoints&&e.dataPoints.length){s.dataPoints=[];for(var g=0;g<e.dataPoints.length;++g)s.dataPoints[g]=E.opentelemetry.proto.metrics.v1.HistogramDataPoint.toObject(e.dataPoints[g],t)}return e.aggregationTemporality!=null&&e.hasOwnProperty(`aggregationTemporality`)&&(s.aggregationTemporality=t.enums===String?E.opentelemetry.proto.metrics.v1.AggregationTemporality[e.aggregationTemporality]===void 0?e.aggregationTemporality:E.opentelemetry.proto.metrics.v1.AggregationTemporality[e.aggregationTemporality]:e.aggregationTemporality),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.Histogram`},e})(),e.ExponentialHistogram=(function(){function e(e){if(this.dataPoints=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.dataPoints=w.emptyArray,e.prototype.aggregationTemporality=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.dataPoints!=null&&e.dataPoints.length)for(var s=0;s<e.dataPoints.length;++s)E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.encode(e.dataPoints[s],t.uint32(10).fork()).ldelim();return e.aggregationTemporality!=null&&Object.hasOwnProperty.call(e,`aggregationTemporality`)&&t.uint32(16).int32(e.aggregationTemporality),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.ExponentialHistogram;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.dataPoints&&w.dataPoints.length||(w.dataPoints=[]),w.dataPoints.push(E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.decode(e,e.uint32()));break;case 2:w.aggregationTemporality=e.int32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.dataPoints!=null&&e.hasOwnProperty(`dataPoints`)){if(!Array.isArray(e.dataPoints))return`dataPoints: array expected`;for(var t=0;t<e.dataPoints.length;++t){var s=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.verify(e.dataPoints[t]);if(s)return`dataPoints.`+s}}if(e.aggregationTemporality!=null&&e.hasOwnProperty(`aggregationTemporality`))switch(e.aggregationTemporality){default:return`aggregationTemporality: enum value expected`;case 0:case 1:case 2:break}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.ExponentialHistogram)return e;var t=new E.opentelemetry.proto.metrics.v1.ExponentialHistogram;if(e.dataPoints){if(!Array.isArray(e.dataPoints))throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: array expected`);t.dataPoints=[];for(var s=0;s<e.dataPoints.length;++s){if(typeof e.dataPoints[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: object expected`);t.dataPoints[s]=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.fromObject(e.dataPoints[s])}}switch(e.aggregationTemporality){default:if(typeof e.aggregationTemporality==`number`){t.aggregationTemporality=e.aggregationTemporality;break}break;case`AGGREGATION_TEMPORALITY_UNSPECIFIED`:case 0:t.aggregationTemporality=0;break;case`AGGREGATION_TEMPORALITY_DELTA`:case 1:t.aggregationTemporality=1;break;case`AGGREGATION_TEMPORALITY_CUMULATIVE`:case 2:t.aggregationTemporality=2;break}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.dataPoints=[]),t.defaults&&(s.aggregationTemporality=t.enums===String?`AGGREGATION_TEMPORALITY_UNSPECIFIED`:0),e.dataPoints&&e.dataPoints.length){s.dataPoints=[];for(var g=0;g<e.dataPoints.length;++g)s.dataPoints[g]=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.toObject(e.dataPoints[g],t)}return e.aggregationTemporality!=null&&e.hasOwnProperty(`aggregationTemporality`)&&(s.aggregationTemporality=t.enums===String?E.opentelemetry.proto.metrics.v1.AggregationTemporality[e.aggregationTemporality]===void 0?e.aggregationTemporality:E.opentelemetry.proto.metrics.v1.AggregationTemporality[e.aggregationTemporality]:e.aggregationTemporality),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.ExponentialHistogram`},e})(),e.Summary=(function(){function e(e){if(this.dataPoints=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.dataPoints=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.dataPoints!=null&&e.dataPoints.length)for(var s=0;s<e.dataPoints.length;++s)E.opentelemetry.proto.metrics.v1.SummaryDataPoint.encode(e.dataPoints[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.Summary;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.dataPoints&&w.dataPoints.length||(w.dataPoints=[]),w.dataPoints.push(E.opentelemetry.proto.metrics.v1.SummaryDataPoint.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.dataPoints!=null&&e.hasOwnProperty(`dataPoints`)){if(!Array.isArray(e.dataPoints))return`dataPoints: array expected`;for(var t=0;t<e.dataPoints.length;++t){var s=E.opentelemetry.proto.metrics.v1.SummaryDataPoint.verify(e.dataPoints[t]);if(s)return`dataPoints.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.Summary)return e;var t=new E.opentelemetry.proto.metrics.v1.Summary;if(e.dataPoints){if(!Array.isArray(e.dataPoints))throw TypeError(`.opentelemetry.proto.metrics.v1.Summary.dataPoints: array expected`);t.dataPoints=[];for(var s=0;s<e.dataPoints.length;++s){if(typeof e.dataPoints[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Summary.dataPoints: object expected`);t.dataPoints[s]=E.opentelemetry.proto.metrics.v1.SummaryDataPoint.fromObject(e.dataPoints[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.dataPoints=[]),e.dataPoints&&e.dataPoints.length){s.dataPoints=[];for(var g=0;g<e.dataPoints.length;++g)s.dataPoints[g]=E.opentelemetry.proto.metrics.v1.SummaryDataPoint.toObject(e.dataPoints[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.Summary`},e})(),e.AggregationTemporality=(function(){var e={},t=Object.create(e);return t[e[0]=`AGGREGATION_TEMPORALITY_UNSPECIFIED`]=0,t[e[1]=`AGGREGATION_TEMPORALITY_DELTA`]=1,t[e[2]=`AGGREGATION_TEMPORALITY_CUMULATIVE`]=2,t})(),e.DataPointFlags=(function(){var e={},t=Object.create(e);return t[e[0]=`DATA_POINT_FLAGS_DO_NOT_USE`]=0,t[e[1]=`DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK`]=1,t})(),e.NumberDataPoint=(function(){function e(e){if(this.attributes=[],this.exemplars=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}e.prototype.attributes=w.emptyArray,e.prototype.startTimeUnixNano=null,e.prototype.timeUnixNano=null,e.prototype.asDouble=null,e.prototype.asInt=null,e.prototype.exemplars=w.emptyArray,e.prototype.flags=null;var t;return Object.defineProperty(e.prototype,`value`,{get:w.oneOfGetter(t=[`asDouble`,`asInt`]),set:w.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.startTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`startTimeUnixNano`)&&t.uint32(17).fixed64(e.startTimeUnixNano),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(25).fixed64(e.timeUnixNano),e.asDouble!=null&&Object.hasOwnProperty.call(e,`asDouble`)&&t.uint32(33).double(e.asDouble),e.exemplars!=null&&e.exemplars.length)for(var s=0;s<e.exemplars.length;++s)E.opentelemetry.proto.metrics.v1.Exemplar.encode(e.exemplars[s],t.uint32(42).fork()).ldelim();if(e.asInt!=null&&Object.hasOwnProperty.call(e,`asInt`)&&t.uint32(49).sfixed64(e.asInt),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(58).fork()).ldelim();return e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(64).uint32(e.flags),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.NumberDataPoint;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 7:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 2:w.startTimeUnixNano=e.fixed64();break;case 3:w.timeUnixNano=e.fixed64();break;case 4:w.asDouble=e.double();break;case 6:w.asInt=e.sfixed64();break;case 5:w.exemplars&&w.exemplars.length||(w.exemplars=[]),w.exemplars.push(E.opentelemetry.proto.metrics.v1.Exemplar.decode(e,e.uint32()));break;case 8:w.flags=e.uint32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;var t={};if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var s=0;s<e.attributes.length;++s){var g=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[s]);if(g)return`attributes.`+g}}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&!w.isInteger(e.startTimeUnixNano)&&!(e.startTimeUnixNano&&w.isInteger(e.startTimeUnixNano.low)&&w.isInteger(e.startTimeUnixNano.high)))return`startTimeUnixNano: integer|Long expected`;if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.asDouble!=null&&e.hasOwnProperty(`asDouble`)&&(t.value=1,typeof e.asDouble!=`number`))return`asDouble: number expected`;if(e.asInt!=null&&e.hasOwnProperty(`asInt`)){if(t.value===1)return`value: multiple values`;if(t.value=1,!w.isInteger(e.asInt)&&!(e.asInt&&w.isInteger(e.asInt.low)&&w.isInteger(e.asInt.high)))return`asInt: integer|Long expected`}if(e.exemplars!=null&&e.hasOwnProperty(`exemplars`)){if(!Array.isArray(e.exemplars))return`exemplars: array expected`;for(var s=0;s<e.exemplars.length;++s){var g=E.opentelemetry.proto.metrics.v1.Exemplar.verify(e.exemplars[s]);if(g)return`exemplars.`+g}}return e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags)?`flags: integer expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.NumberDataPoint)return e;var t=new E.opentelemetry.proto.metrics.v1.NumberDataPoint;if(e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}if(e.startTimeUnixNano!=null&&(w.Long?(t.startTimeUnixNano=w.Long.fromValue(e.startTimeUnixNano)).unsigned=!1:typeof e.startTimeUnixNano==`string`?t.startTimeUnixNano=parseInt(e.startTimeUnixNano,10):typeof e.startTimeUnixNano==`number`?t.startTimeUnixNano=e.startTimeUnixNano:typeof e.startTimeUnixNano==`object`&&(t.startTimeUnixNano=new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber())),e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.asDouble!=null&&(t.asDouble=Number(e.asDouble)),e.asInt!=null&&(w.Long?(t.asInt=w.Long.fromValue(e.asInt)).unsigned=!1:typeof e.asInt==`string`?t.asInt=parseInt(e.asInt,10):typeof e.asInt==`number`?t.asInt=e.asInt:typeof e.asInt==`object`&&(t.asInt=new w.LongBits(e.asInt.low>>>0,e.asInt.high>>>0).toNumber())),e.exemplars){if(!Array.isArray(e.exemplars))throw TypeError(`.opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: array expected`);t.exemplars=[];for(var s=0;s<e.exemplars.length;++s){if(typeof e.exemplars[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: object expected`);t.exemplars[s]=E.opentelemetry.proto.metrics.v1.Exemplar.fromObject(e.exemplars[s])}}return e.flags!=null&&(t.flags=e.flags>>>0),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.exemplars=[],s.attributes=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.startTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.startTimeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;s.flags=0}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&(typeof e.startTimeUnixNano==`number`?s.startTimeUnixNano=t.longs===String?String(e.startTimeUnixNano):e.startTimeUnixNano:s.startTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.startTimeUnixNano):t.longs===Number?new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber():e.startTimeUnixNano),e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.asDouble!=null&&e.hasOwnProperty(`asDouble`)&&(s.asDouble=t.json&&!isFinite(e.asDouble)?String(e.asDouble):e.asDouble,t.oneofs&&(s.value=`asDouble`)),e.exemplars&&e.exemplars.length){s.exemplars=[];for(var S=0;S<e.exemplars.length;++S)s.exemplars[S]=E.opentelemetry.proto.metrics.v1.Exemplar.toObject(e.exemplars[S],t)}if(e.asInt!=null&&e.hasOwnProperty(`asInt`)&&(typeof e.asInt==`number`?s.asInt=t.longs===String?String(e.asInt):e.asInt:s.asInt=t.longs===String?w.Long.prototype.toString.call(e.asInt):t.longs===Number?new w.LongBits(e.asInt.low>>>0,e.asInt.high>>>0).toNumber():e.asInt,t.oneofs&&(s.value=`asInt`)),e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}return e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.NumberDataPoint`},e})(),e.HistogramDataPoint=(function(){function e(e){if(this.attributes=[],this.bucketCounts=[],this.explicitBounds=[],this.exemplars=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}e.prototype.attributes=w.emptyArray,e.prototype.startTimeUnixNano=null,e.prototype.timeUnixNano=null,e.prototype.count=null,e.prototype.sum=null,e.prototype.bucketCounts=w.emptyArray,e.prototype.explicitBounds=w.emptyArray,e.prototype.exemplars=w.emptyArray,e.prototype.flags=null,e.prototype.min=null,e.prototype.max=null;var t;return Object.defineProperty(e.prototype,`_sum`,{get:w.oneOfGetter(t=[`sum`]),set:w.oneOfSetter(t)}),Object.defineProperty(e.prototype,`_min`,{get:w.oneOfGetter(t=[`min`]),set:w.oneOfSetter(t)}),Object.defineProperty(e.prototype,`_max`,{get:w.oneOfGetter(t=[`max`]),set:w.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.startTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`startTimeUnixNano`)&&t.uint32(17).fixed64(e.startTimeUnixNano),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(25).fixed64(e.timeUnixNano),e.count!=null&&Object.hasOwnProperty.call(e,`count`)&&t.uint32(33).fixed64(e.count),e.sum!=null&&Object.hasOwnProperty.call(e,`sum`)&&t.uint32(41).double(e.sum),e.bucketCounts!=null&&e.bucketCounts.length){t.uint32(50).fork();for(var s=0;s<e.bucketCounts.length;++s)t.fixed64(e.bucketCounts[s]);t.ldelim()}if(e.explicitBounds!=null&&e.explicitBounds.length){t.uint32(58).fork();for(var s=0;s<e.explicitBounds.length;++s)t.double(e.explicitBounds[s]);t.ldelim()}if(e.exemplars!=null&&e.exemplars.length)for(var s=0;s<e.exemplars.length;++s)E.opentelemetry.proto.metrics.v1.Exemplar.encode(e.exemplars[s],t.uint32(66).fork()).ldelim();if(e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(74).fork()).ldelim();return e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(80).uint32(e.flags),e.min!=null&&Object.hasOwnProperty.call(e,`min`)&&t.uint32(89).double(e.min),e.max!=null&&Object.hasOwnProperty.call(e,`max`)&&t.uint32(97).double(e.max),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.HistogramDataPoint;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 9:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 2:w.startTimeUnixNano=e.fixed64();break;case 3:w.timeUnixNano=e.fixed64();break;case 4:w.count=e.fixed64();break;case 5:w.sum=e.double();break;case 6:if(w.bucketCounts&&w.bucketCounts.length||(w.bucketCounts=[]),(D&7)==2)for(var O=e.uint32()+e.pos;e.pos<O;)w.bucketCounts.push(e.fixed64());else w.bucketCounts.push(e.fixed64());break;case 7:if(w.explicitBounds&&w.explicitBounds.length||(w.explicitBounds=[]),(D&7)==2)for(var O=e.uint32()+e.pos;e.pos<O;)w.explicitBounds.push(e.double());else w.explicitBounds.push(e.double());break;case 8:w.exemplars&&w.exemplars.length||(w.exemplars=[]),w.exemplars.push(E.opentelemetry.proto.metrics.v1.Exemplar.decode(e,e.uint32()));break;case 10:w.flags=e.uint32();break;case 11:w.min=e.double();break;case 12:w.max=e.double();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;var t={};if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var s=0;s<e.attributes.length;++s){var g=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[s]);if(g)return`attributes.`+g}}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&!w.isInteger(e.startTimeUnixNano)&&!(e.startTimeUnixNano&&w.isInteger(e.startTimeUnixNano.low)&&w.isInteger(e.startTimeUnixNano.high)))return`startTimeUnixNano: integer|Long expected`;if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.count!=null&&e.hasOwnProperty(`count`)&&!w.isInteger(e.count)&&!(e.count&&w.isInteger(e.count.low)&&w.isInteger(e.count.high)))return`count: integer|Long expected`;if(e.sum!=null&&e.hasOwnProperty(`sum`)&&(t._sum=1,typeof e.sum!=`number`))return`sum: number expected`;if(e.bucketCounts!=null&&e.hasOwnProperty(`bucketCounts`)){if(!Array.isArray(e.bucketCounts))return`bucketCounts: array expected`;for(var s=0;s<e.bucketCounts.length;++s)if(!w.isInteger(e.bucketCounts[s])&&!(e.bucketCounts[s]&&w.isInteger(e.bucketCounts[s].low)&&w.isInteger(e.bucketCounts[s].high)))return`bucketCounts: integer|Long[] expected`}if(e.explicitBounds!=null&&e.hasOwnProperty(`explicitBounds`)){if(!Array.isArray(e.explicitBounds))return`explicitBounds: array expected`;for(var s=0;s<e.explicitBounds.length;++s)if(typeof e.explicitBounds[s]!=`number`)return`explicitBounds: number[] expected`}if(e.exemplars!=null&&e.hasOwnProperty(`exemplars`)){if(!Array.isArray(e.exemplars))return`exemplars: array expected`;for(var s=0;s<e.exemplars.length;++s){var g=E.opentelemetry.proto.metrics.v1.Exemplar.verify(e.exemplars[s]);if(g)return`exemplars.`+g}}return e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags)?`flags: integer expected`:e.min!=null&&e.hasOwnProperty(`min`)&&(t._min=1,typeof e.min!=`number`)?`min: number expected`:e.max!=null&&e.hasOwnProperty(`max`)&&(t._max=1,typeof e.max!=`number`)?`max: number expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.HistogramDataPoint)return e;var t=new E.opentelemetry.proto.metrics.v1.HistogramDataPoint;if(e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}if(e.startTimeUnixNano!=null&&(w.Long?(t.startTimeUnixNano=w.Long.fromValue(e.startTimeUnixNano)).unsigned=!1:typeof e.startTimeUnixNano==`string`?t.startTimeUnixNano=parseInt(e.startTimeUnixNano,10):typeof e.startTimeUnixNano==`number`?t.startTimeUnixNano=e.startTimeUnixNano:typeof e.startTimeUnixNano==`object`&&(t.startTimeUnixNano=new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber())),e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.count!=null&&(w.Long?(t.count=w.Long.fromValue(e.count)).unsigned=!1:typeof e.count==`string`?t.count=parseInt(e.count,10):typeof e.count==`number`?t.count=e.count:typeof e.count==`object`&&(t.count=new w.LongBits(e.count.low>>>0,e.count.high>>>0).toNumber())),e.sum!=null&&(t.sum=Number(e.sum)),e.bucketCounts){if(!Array.isArray(e.bucketCounts))throw TypeError(`.opentelemetry.proto.metrics.v1.HistogramDataPoint.bucketCounts: array expected`);t.bucketCounts=[];for(var s=0;s<e.bucketCounts.length;++s)w.Long?(t.bucketCounts[s]=w.Long.fromValue(e.bucketCounts[s])).unsigned=!1:typeof e.bucketCounts[s]==`string`?t.bucketCounts[s]=parseInt(e.bucketCounts[s],10):typeof e.bucketCounts[s]==`number`?t.bucketCounts[s]=e.bucketCounts[s]:typeof e.bucketCounts[s]==`object`&&(t.bucketCounts[s]=new w.LongBits(e.bucketCounts[s].low>>>0,e.bucketCounts[s].high>>>0).toNumber())}if(e.explicitBounds){if(!Array.isArray(e.explicitBounds))throw TypeError(`.opentelemetry.proto.metrics.v1.HistogramDataPoint.explicitBounds: array expected`);t.explicitBounds=[];for(var s=0;s<e.explicitBounds.length;++s)t.explicitBounds[s]=Number(e.explicitBounds[s])}if(e.exemplars){if(!Array.isArray(e.exemplars))throw TypeError(`.opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: array expected`);t.exemplars=[];for(var s=0;s<e.exemplars.length;++s){if(typeof e.exemplars[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: object expected`);t.exemplars[s]=E.opentelemetry.proto.metrics.v1.Exemplar.fromObject(e.exemplars[s])}}return e.flags!=null&&(t.flags=e.flags>>>0),e.min!=null&&(t.min=Number(e.min)),e.max!=null&&(t.max=Number(e.max)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.bucketCounts=[],s.explicitBounds=[],s.exemplars=[],s.attributes=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.startTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.startTimeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.count=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.count=t.longs===String?`0`:0;s.flags=0}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&(typeof e.startTimeUnixNano==`number`?s.startTimeUnixNano=t.longs===String?String(e.startTimeUnixNano):e.startTimeUnixNano:s.startTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.startTimeUnixNano):t.longs===Number?new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber():e.startTimeUnixNano),e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.count!=null&&e.hasOwnProperty(`count`)&&(typeof e.count==`number`?s.count=t.longs===String?String(e.count):e.count:s.count=t.longs===String?w.Long.prototype.toString.call(e.count):t.longs===Number?new w.LongBits(e.count.low>>>0,e.count.high>>>0).toNumber():e.count),e.sum!=null&&e.hasOwnProperty(`sum`)&&(s.sum=t.json&&!isFinite(e.sum)?String(e.sum):e.sum,t.oneofs&&(s._sum=`sum`)),e.bucketCounts&&e.bucketCounts.length){s.bucketCounts=[];for(var S=0;S<e.bucketCounts.length;++S)typeof e.bucketCounts[S]==`number`?s.bucketCounts[S]=t.longs===String?String(e.bucketCounts[S]):e.bucketCounts[S]:s.bucketCounts[S]=t.longs===String?w.Long.prototype.toString.call(e.bucketCounts[S]):t.longs===Number?new w.LongBits(e.bucketCounts[S].low>>>0,e.bucketCounts[S].high>>>0).toNumber():e.bucketCounts[S]}if(e.explicitBounds&&e.explicitBounds.length){s.explicitBounds=[];for(var S=0;S<e.explicitBounds.length;++S)s.explicitBounds[S]=t.json&&!isFinite(e.explicitBounds[S])?String(e.explicitBounds[S]):e.explicitBounds[S]}if(e.exemplars&&e.exemplars.length){s.exemplars=[];for(var S=0;S<e.exemplars.length;++S)s.exemplars[S]=E.opentelemetry.proto.metrics.v1.Exemplar.toObject(e.exemplars[S],t)}if(e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}return e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),e.min!=null&&e.hasOwnProperty(`min`)&&(s.min=t.json&&!isFinite(e.min)?String(e.min):e.min,t.oneofs&&(s._min=`min`)),e.max!=null&&e.hasOwnProperty(`max`)&&(s.max=t.json&&!isFinite(e.max)?String(e.max):e.max,t.oneofs&&(s._max=`max`)),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.HistogramDataPoint`},e})(),e.ExponentialHistogramDataPoint=(function(){function e(e){if(this.attributes=[],this.exemplars=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}e.prototype.attributes=w.emptyArray,e.prototype.startTimeUnixNano=null,e.prototype.timeUnixNano=null,e.prototype.count=null,e.prototype.sum=null,e.prototype.scale=null,e.prototype.zeroCount=null,e.prototype.positive=null,e.prototype.negative=null,e.prototype.flags=null,e.prototype.exemplars=w.emptyArray,e.prototype.min=null,e.prototype.max=null,e.prototype.zeroThreshold=null;var t;return Object.defineProperty(e.prototype,`_sum`,{get:w.oneOfGetter(t=[`sum`]),set:w.oneOfSetter(t)}),Object.defineProperty(e.prototype,`_min`,{get:w.oneOfGetter(t=[`min`]),set:w.oneOfSetter(t)}),Object.defineProperty(e.prototype,`_max`,{get:w.oneOfGetter(t=[`max`]),set:w.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(10).fork()).ldelim();if(e.startTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`startTimeUnixNano`)&&t.uint32(17).fixed64(e.startTimeUnixNano),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(25).fixed64(e.timeUnixNano),e.count!=null&&Object.hasOwnProperty.call(e,`count`)&&t.uint32(33).fixed64(e.count),e.sum!=null&&Object.hasOwnProperty.call(e,`sum`)&&t.uint32(41).double(e.sum),e.scale!=null&&Object.hasOwnProperty.call(e,`scale`)&&t.uint32(48).sint32(e.scale),e.zeroCount!=null&&Object.hasOwnProperty.call(e,`zeroCount`)&&t.uint32(57).fixed64(e.zeroCount),e.positive!=null&&Object.hasOwnProperty.call(e,`positive`)&&E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.encode(e.positive,t.uint32(66).fork()).ldelim(),e.negative!=null&&Object.hasOwnProperty.call(e,`negative`)&&E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.encode(e.negative,t.uint32(74).fork()).ldelim(),e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(80).uint32(e.flags),e.exemplars!=null&&e.exemplars.length)for(var s=0;s<e.exemplars.length;++s)E.opentelemetry.proto.metrics.v1.Exemplar.encode(e.exemplars[s],t.uint32(90).fork()).ldelim();return e.min!=null&&Object.hasOwnProperty.call(e,`min`)&&t.uint32(97).double(e.min),e.max!=null&&Object.hasOwnProperty.call(e,`max`)&&t.uint32(105).double(e.max),e.zeroThreshold!=null&&Object.hasOwnProperty.call(e,`zeroThreshold`)&&t.uint32(113).double(e.zeroThreshold),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 2:w.startTimeUnixNano=e.fixed64();break;case 3:w.timeUnixNano=e.fixed64();break;case 4:w.count=e.fixed64();break;case 5:w.sum=e.double();break;case 6:w.scale=e.sint32();break;case 7:w.zeroCount=e.fixed64();break;case 8:w.positive=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.decode(e,e.uint32());break;case 9:w.negative=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.decode(e,e.uint32());break;case 10:w.flags=e.uint32();break;case 11:w.exemplars&&w.exemplars.length||(w.exemplars=[]),w.exemplars.push(E.opentelemetry.proto.metrics.v1.Exemplar.decode(e,e.uint32()));break;case 12:w.min=e.double();break;case 13:w.max=e.double();break;case 14:w.zeroThreshold=e.double();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;var t={};if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var s=0;s<e.attributes.length;++s){var g=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[s]);if(g)return`attributes.`+g}}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&!w.isInteger(e.startTimeUnixNano)&&!(e.startTimeUnixNano&&w.isInteger(e.startTimeUnixNano.low)&&w.isInteger(e.startTimeUnixNano.high)))return`startTimeUnixNano: integer|Long expected`;if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.count!=null&&e.hasOwnProperty(`count`)&&!w.isInteger(e.count)&&!(e.count&&w.isInteger(e.count.low)&&w.isInteger(e.count.high)))return`count: integer|Long expected`;if(e.sum!=null&&e.hasOwnProperty(`sum`)&&(t._sum=1,typeof e.sum!=`number`))return`sum: number expected`;if(e.scale!=null&&e.hasOwnProperty(`scale`)&&!w.isInteger(e.scale))return`scale: integer expected`;if(e.zeroCount!=null&&e.hasOwnProperty(`zeroCount`)&&!w.isInteger(e.zeroCount)&&!(e.zeroCount&&w.isInteger(e.zeroCount.low)&&w.isInteger(e.zeroCount.high)))return`zeroCount: integer|Long expected`;if(e.positive!=null&&e.hasOwnProperty(`positive`)){var g=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(e.positive);if(g)return`positive.`+g}if(e.negative!=null&&e.hasOwnProperty(`negative`)){var g=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(e.negative);if(g)return`negative.`+g}if(e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags))return`flags: integer expected`;if(e.exemplars!=null&&e.hasOwnProperty(`exemplars`)){if(!Array.isArray(e.exemplars))return`exemplars: array expected`;for(var s=0;s<e.exemplars.length;++s){var g=E.opentelemetry.proto.metrics.v1.Exemplar.verify(e.exemplars[s]);if(g)return`exemplars.`+g}}return e.min!=null&&e.hasOwnProperty(`min`)&&(t._min=1,typeof e.min!=`number`)?`min: number expected`:e.max!=null&&e.hasOwnProperty(`max`)&&(t._max=1,typeof e.max!=`number`)?`max: number expected`:e.zeroThreshold!=null&&e.hasOwnProperty(`zeroThreshold`)&&typeof e.zeroThreshold!=`number`?`zeroThreshold: number expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint)return e;var t=new E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint;if(e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}if(e.startTimeUnixNano!=null&&(w.Long?(t.startTimeUnixNano=w.Long.fromValue(e.startTimeUnixNano)).unsigned=!1:typeof e.startTimeUnixNano==`string`?t.startTimeUnixNano=parseInt(e.startTimeUnixNano,10):typeof e.startTimeUnixNano==`number`?t.startTimeUnixNano=e.startTimeUnixNano:typeof e.startTimeUnixNano==`object`&&(t.startTimeUnixNano=new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber())),e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.count!=null&&(w.Long?(t.count=w.Long.fromValue(e.count)).unsigned=!1:typeof e.count==`string`?t.count=parseInt(e.count,10):typeof e.count==`number`?t.count=e.count:typeof e.count==`object`&&(t.count=new w.LongBits(e.count.low>>>0,e.count.high>>>0).toNumber())),e.sum!=null&&(t.sum=Number(e.sum)),e.scale!=null&&(t.scale=e.scale|0),e.zeroCount!=null&&(w.Long?(t.zeroCount=w.Long.fromValue(e.zeroCount)).unsigned=!1:typeof e.zeroCount==`string`?t.zeroCount=parseInt(e.zeroCount,10):typeof e.zeroCount==`number`?t.zeroCount=e.zeroCount:typeof e.zeroCount==`object`&&(t.zeroCount=new w.LongBits(e.zeroCount.low>>>0,e.zeroCount.high>>>0).toNumber())),e.positive!=null){if(typeof e.positive!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.positive: object expected`);t.positive=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(e.positive)}if(e.negative!=null){if(typeof e.negative!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.negative: object expected`);t.negative=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(e.negative)}if(e.flags!=null&&(t.flags=e.flags>>>0),e.exemplars){if(!Array.isArray(e.exemplars))throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: array expected`);t.exemplars=[];for(var s=0;s<e.exemplars.length;++s){if(typeof e.exemplars[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: object expected`);t.exemplars[s]=E.opentelemetry.proto.metrics.v1.Exemplar.fromObject(e.exemplars[s])}}return e.min!=null&&(t.min=Number(e.min)),e.max!=null&&(t.max=Number(e.max)),e.zeroThreshold!=null&&(t.zeroThreshold=Number(e.zeroThreshold)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[],s.exemplars=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.startTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.startTimeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.count=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.count=t.longs===String?`0`:0;if(s.scale=0,w.Long){var g=new w.Long(0,0,!1);s.zeroCount=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.zeroCount=t.longs===String?`0`:0;s.positive=null,s.negative=null,s.flags=0,s.zeroThreshold=0}if(e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&(typeof e.startTimeUnixNano==`number`?s.startTimeUnixNano=t.longs===String?String(e.startTimeUnixNano):e.startTimeUnixNano:s.startTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.startTimeUnixNano):t.longs===Number?new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber():e.startTimeUnixNano),e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.count!=null&&e.hasOwnProperty(`count`)&&(typeof e.count==`number`?s.count=t.longs===String?String(e.count):e.count:s.count=t.longs===String?w.Long.prototype.toString.call(e.count):t.longs===Number?new w.LongBits(e.count.low>>>0,e.count.high>>>0).toNumber():e.count),e.sum!=null&&e.hasOwnProperty(`sum`)&&(s.sum=t.json&&!isFinite(e.sum)?String(e.sum):e.sum,t.oneofs&&(s._sum=`sum`)),e.scale!=null&&e.hasOwnProperty(`scale`)&&(s.scale=e.scale),e.zeroCount!=null&&e.hasOwnProperty(`zeroCount`)&&(typeof e.zeroCount==`number`?s.zeroCount=t.longs===String?String(e.zeroCount):e.zeroCount:s.zeroCount=t.longs===String?w.Long.prototype.toString.call(e.zeroCount):t.longs===Number?new w.LongBits(e.zeroCount.low>>>0,e.zeroCount.high>>>0).toNumber():e.zeroCount),e.positive!=null&&e.hasOwnProperty(`positive`)&&(s.positive=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(e.positive,t)),e.negative!=null&&e.hasOwnProperty(`negative`)&&(s.negative=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(e.negative,t)),e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),e.exemplars&&e.exemplars.length){s.exemplars=[];for(var S=0;S<e.exemplars.length;++S)s.exemplars[S]=E.opentelemetry.proto.metrics.v1.Exemplar.toObject(e.exemplars[S],t)}return e.min!=null&&e.hasOwnProperty(`min`)&&(s.min=t.json&&!isFinite(e.min)?String(e.min):e.min,t.oneofs&&(s._min=`min`)),e.max!=null&&e.hasOwnProperty(`max`)&&(s.max=t.json&&!isFinite(e.max)?String(e.max):e.max,t.oneofs&&(s._max=`max`)),e.zeroThreshold!=null&&e.hasOwnProperty(`zeroThreshold`)&&(s.zeroThreshold=t.json&&!isFinite(e.zeroThreshold)?String(e.zeroThreshold):e.zeroThreshold),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint`},e.Buckets=(function(){function e(e){if(this.bucketCounts=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.offset=null,e.prototype.bucketCounts=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.offset!=null&&Object.hasOwnProperty.call(e,`offset`)&&t.uint32(8).sint32(e.offset),e.bucketCounts!=null&&e.bucketCounts.length){t.uint32(18).fork();for(var s=0;s<e.bucketCounts.length;++s)t.uint64(e.bucketCounts[s]);t.ldelim()}return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.offset=e.sint32();break;case 2:if(w.bucketCounts&&w.bucketCounts.length||(w.bucketCounts=[]),(D&7)==2)for(var O=e.uint32()+e.pos;e.pos<O;)w.bucketCounts.push(e.uint64());else w.bucketCounts.push(e.uint64());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.offset!=null&&e.hasOwnProperty(`offset`)&&!w.isInteger(e.offset))return`offset: integer expected`;if(e.bucketCounts!=null&&e.hasOwnProperty(`bucketCounts`)){if(!Array.isArray(e.bucketCounts))return`bucketCounts: array expected`;for(var t=0;t<e.bucketCounts.length;++t)if(!w.isInteger(e.bucketCounts[t])&&!(e.bucketCounts[t]&&w.isInteger(e.bucketCounts[t].low)&&w.isInteger(e.bucketCounts[t].high)))return`bucketCounts: integer|Long[] expected`}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets)return e;var t=new E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets;if(e.offset!=null&&(t.offset=e.offset|0),e.bucketCounts){if(!Array.isArray(e.bucketCounts))throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.bucketCounts: array expected`);t.bucketCounts=[];for(var s=0;s<e.bucketCounts.length;++s)w.Long?(t.bucketCounts[s]=w.Long.fromValue(e.bucketCounts[s])).unsigned=!0:typeof e.bucketCounts[s]==`string`?t.bucketCounts[s]=parseInt(e.bucketCounts[s],10):typeof e.bucketCounts[s]==`number`?t.bucketCounts[s]=e.bucketCounts[s]:typeof e.bucketCounts[s]==`object`&&(t.bucketCounts[s]=new w.LongBits(e.bucketCounts[s].low>>>0,e.bucketCounts[s].high>>>0).toNumber(!0))}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.bucketCounts=[]),t.defaults&&(s.offset=0),e.offset!=null&&e.hasOwnProperty(`offset`)&&(s.offset=e.offset),e.bucketCounts&&e.bucketCounts.length){s.bucketCounts=[];for(var g=0;g<e.bucketCounts.length;++g)typeof e.bucketCounts[g]==`number`?s.bucketCounts[g]=t.longs===String?String(e.bucketCounts[g]):e.bucketCounts[g]:s.bucketCounts[g]=t.longs===String?w.Long.prototype.toString.call(e.bucketCounts[g]):t.longs===Number?new w.LongBits(e.bucketCounts[g].low>>>0,e.bucketCounts[g].high>>>0).toNumber(!0):e.bucketCounts[g]}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets`},e})(),e})(),e.SummaryDataPoint=(function(){function e(e){if(this.attributes=[],this.quantileValues=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.attributes=w.emptyArray,e.prototype.startTimeUnixNano=null,e.prototype.timeUnixNano=null,e.prototype.count=null,e.prototype.sum=null,e.prototype.quantileValues=w.emptyArray,e.prototype.flags=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.startTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`startTimeUnixNano`)&&t.uint32(17).fixed64(e.startTimeUnixNano),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(25).fixed64(e.timeUnixNano),e.count!=null&&Object.hasOwnProperty.call(e,`count`)&&t.uint32(33).fixed64(e.count),e.sum!=null&&Object.hasOwnProperty.call(e,`sum`)&&t.uint32(41).double(e.sum),e.quantileValues!=null&&e.quantileValues.length)for(var s=0;s<e.quantileValues.length;++s)E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.encode(e.quantileValues[s],t.uint32(50).fork()).ldelim();if(e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(58).fork()).ldelim();return e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(64).uint32(e.flags),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.SummaryDataPoint;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 7:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 2:w.startTimeUnixNano=e.fixed64();break;case 3:w.timeUnixNano=e.fixed64();break;case 4:w.count=e.fixed64();break;case 5:w.sum=e.double();break;case 6:w.quantileValues&&w.quantileValues.length||(w.quantileValues=[]),w.quantileValues.push(E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.decode(e,e.uint32()));break;case 8:w.flags=e.uint32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var t=0;t<e.attributes.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[t]);if(s)return`attributes.`+s}}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&!w.isInteger(e.startTimeUnixNano)&&!(e.startTimeUnixNano&&w.isInteger(e.startTimeUnixNano.low)&&w.isInteger(e.startTimeUnixNano.high)))return`startTimeUnixNano: integer|Long expected`;if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.count!=null&&e.hasOwnProperty(`count`)&&!w.isInteger(e.count)&&!(e.count&&w.isInteger(e.count.low)&&w.isInteger(e.count.high)))return`count: integer|Long expected`;if(e.sum!=null&&e.hasOwnProperty(`sum`)&&typeof e.sum!=`number`)return`sum: number expected`;if(e.quantileValues!=null&&e.hasOwnProperty(`quantileValues`)){if(!Array.isArray(e.quantileValues))return`quantileValues: array expected`;for(var t=0;t<e.quantileValues.length;++t){var s=E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.verify(e.quantileValues[t]);if(s)return`quantileValues.`+s}}return e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags)?`flags: integer expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.SummaryDataPoint)return e;var t=new E.opentelemetry.proto.metrics.v1.SummaryDataPoint;if(e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}if(e.startTimeUnixNano!=null&&(w.Long?(t.startTimeUnixNano=w.Long.fromValue(e.startTimeUnixNano)).unsigned=!1:typeof e.startTimeUnixNano==`string`?t.startTimeUnixNano=parseInt(e.startTimeUnixNano,10):typeof e.startTimeUnixNano==`number`?t.startTimeUnixNano=e.startTimeUnixNano:typeof e.startTimeUnixNano==`object`&&(t.startTimeUnixNano=new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber())),e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.count!=null&&(w.Long?(t.count=w.Long.fromValue(e.count)).unsigned=!1:typeof e.count==`string`?t.count=parseInt(e.count,10):typeof e.count==`number`?t.count=e.count:typeof e.count==`object`&&(t.count=new w.LongBits(e.count.low>>>0,e.count.high>>>0).toNumber())),e.sum!=null&&(t.sum=Number(e.sum)),e.quantileValues){if(!Array.isArray(e.quantileValues))throw TypeError(`.opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: array expected`);t.quantileValues=[];for(var s=0;s<e.quantileValues.length;++s){if(typeof e.quantileValues[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: object expected`);t.quantileValues[s]=E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.fromObject(e.quantileValues[s])}}return e.flags!=null&&(t.flags=e.flags>>>0),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.quantileValues=[],s.attributes=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.startTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.startTimeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.count=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.count=t.longs===String?`0`:0;s.sum=0,s.flags=0}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&(typeof e.startTimeUnixNano==`number`?s.startTimeUnixNano=t.longs===String?String(e.startTimeUnixNano):e.startTimeUnixNano:s.startTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.startTimeUnixNano):t.longs===Number?new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber():e.startTimeUnixNano),e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.count!=null&&e.hasOwnProperty(`count`)&&(typeof e.count==`number`?s.count=t.longs===String?String(e.count):e.count:s.count=t.longs===String?w.Long.prototype.toString.call(e.count):t.longs===Number?new w.LongBits(e.count.low>>>0,e.count.high>>>0).toNumber():e.count),e.sum!=null&&e.hasOwnProperty(`sum`)&&(s.sum=t.json&&!isFinite(e.sum)?String(e.sum):e.sum),e.quantileValues&&e.quantileValues.length){s.quantileValues=[];for(var S=0;S<e.quantileValues.length;++S)s.quantileValues[S]=E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.toObject(e.quantileValues[S],t)}if(e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}return e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.SummaryDataPoint`},e.ValueAtQuantile=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.quantile=null,e.prototype.value=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.quantile!=null&&Object.hasOwnProperty.call(e,`quantile`)&&t.uint32(9).double(e.quantile),e.value!=null&&Object.hasOwnProperty.call(e,`value`)&&t.uint32(17).double(e.value),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.quantile=e.double();break;case 2:w.value=e.double();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){return typeof e!=`object`||!e?`object expected`:e.quantile!=null&&e.hasOwnProperty(`quantile`)&&typeof e.quantile!=`number`?`quantile: number expected`:e.value!=null&&e.hasOwnProperty(`value`)&&typeof e.value!=`number`?`value: number expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile)return e;var t=new E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile;return e.quantile!=null&&(t.quantile=Number(e.quantile)),e.value!=null&&(t.value=Number(e.value)),t},e.toObject=function(e,t){t||={};var s={};return t.defaults&&(s.quantile=0,s.value=0),e.quantile!=null&&e.hasOwnProperty(`quantile`)&&(s.quantile=t.json&&!isFinite(e.quantile)?String(e.quantile):e.quantile),e.value!=null&&e.hasOwnProperty(`value`)&&(s.value=t.json&&!isFinite(e.value)?String(e.value):e.value),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile`},e})(),e})(),e.Exemplar=(function(){function e(e){if(this.filteredAttributes=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}e.prototype.filteredAttributes=w.emptyArray,e.prototype.timeUnixNano=null,e.prototype.asDouble=null,e.prototype.asInt=null,e.prototype.spanId=null,e.prototype.traceId=null;var t;return Object.defineProperty(e.prototype,`value`,{get:w.oneOfGetter(t=[`asDouble`,`asInt`]),set:w.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(17).fixed64(e.timeUnixNano),e.asDouble!=null&&Object.hasOwnProperty.call(e,`asDouble`)&&t.uint32(25).double(e.asDouble),e.spanId!=null&&Object.hasOwnProperty.call(e,`spanId`)&&t.uint32(34).bytes(e.spanId),e.traceId!=null&&Object.hasOwnProperty.call(e,`traceId`)&&t.uint32(42).bytes(e.traceId),e.asInt!=null&&Object.hasOwnProperty.call(e,`asInt`)&&t.uint32(49).sfixed64(e.asInt),e.filteredAttributes!=null&&e.filteredAttributes.length)for(var s=0;s<e.filteredAttributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.filteredAttributes[s],t.uint32(58).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.Exemplar;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 7:w.filteredAttributes&&w.filteredAttributes.length||(w.filteredAttributes=[]),w.filteredAttributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 2:w.timeUnixNano=e.fixed64();break;case 3:w.asDouble=e.double();break;case 6:w.asInt=e.sfixed64();break;case 4:w.spanId=e.bytes();break;case 5:w.traceId=e.bytes();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;var t={};if(e.filteredAttributes!=null&&e.hasOwnProperty(`filteredAttributes`)){if(!Array.isArray(e.filteredAttributes))return`filteredAttributes: array expected`;for(var s=0;s<e.filteredAttributes.length;++s){var g=E.opentelemetry.proto.common.v1.KeyValue.verify(e.filteredAttributes[s]);if(g)return`filteredAttributes.`+g}}if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.asDouble!=null&&e.hasOwnProperty(`asDouble`)&&(t.value=1,typeof e.asDouble!=`number`))return`asDouble: number expected`;if(e.asInt!=null&&e.hasOwnProperty(`asInt`)){if(t.value===1)return`value: multiple values`;if(t.value=1,!w.isInteger(e.asInt)&&!(e.asInt&&w.isInteger(e.asInt.low)&&w.isInteger(e.asInt.high)))return`asInt: integer|Long expected`}return e.spanId!=null&&e.hasOwnProperty(`spanId`)&&!(e.spanId&&typeof e.spanId.length==`number`||w.isString(e.spanId))?`spanId: buffer expected`:e.traceId!=null&&e.hasOwnProperty(`traceId`)&&!(e.traceId&&typeof e.traceId.length==`number`||w.isString(e.traceId))?`traceId: buffer expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.Exemplar)return e;var t=new E.opentelemetry.proto.metrics.v1.Exemplar;if(e.filteredAttributes){if(!Array.isArray(e.filteredAttributes))throw TypeError(`.opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: array expected`);t.filteredAttributes=[];for(var s=0;s<e.filteredAttributes.length;++s){if(typeof e.filteredAttributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: object expected`);t.filteredAttributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.filteredAttributes[s])}}return e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.asDouble!=null&&(t.asDouble=Number(e.asDouble)),e.asInt!=null&&(w.Long?(t.asInt=w.Long.fromValue(e.asInt)).unsigned=!1:typeof e.asInt==`string`?t.asInt=parseInt(e.asInt,10):typeof e.asInt==`number`?t.asInt=e.asInt:typeof e.asInt==`object`&&(t.asInt=new w.LongBits(e.asInt.low>>>0,e.asInt.high>>>0).toNumber())),e.spanId!=null&&(typeof e.spanId==`string`?w.base64.decode(e.spanId,t.spanId=w.newBuffer(w.base64.length(e.spanId)),0):e.spanId.length>=0&&(t.spanId=e.spanId)),e.traceId!=null&&(typeof e.traceId==`string`?w.base64.decode(e.traceId,t.traceId=w.newBuffer(w.base64.length(e.traceId)),0):e.traceId.length>=0&&(t.traceId=e.traceId)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.filteredAttributes=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;t.bytes===String?s.spanId=``:(s.spanId=[],t.bytes!==Array&&(s.spanId=w.newBuffer(s.spanId))),t.bytes===String?s.traceId=``:(s.traceId=[],t.bytes!==Array&&(s.traceId=w.newBuffer(s.traceId)))}if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.asDouble!=null&&e.hasOwnProperty(`asDouble`)&&(s.asDouble=t.json&&!isFinite(e.asDouble)?String(e.asDouble):e.asDouble,t.oneofs&&(s.value=`asDouble`)),e.spanId!=null&&e.hasOwnProperty(`spanId`)&&(s.spanId=t.bytes===String?w.base64.encode(e.spanId,0,e.spanId.length):t.bytes===Array?Array.prototype.slice.call(e.spanId):e.spanId),e.traceId!=null&&e.hasOwnProperty(`traceId`)&&(s.traceId=t.bytes===String?w.base64.encode(e.traceId,0,e.traceId.length):t.bytes===Array?Array.prototype.slice.call(e.traceId):e.traceId),e.asInt!=null&&e.hasOwnProperty(`asInt`)&&(typeof e.asInt==`number`?s.asInt=t.longs===String?String(e.asInt):e.asInt:s.asInt=t.longs===String?w.Long.prototype.toString.call(e.asInt):t.longs===Number?new w.LongBits(e.asInt.low>>>0,e.asInt.high>>>0).toNumber():e.asInt,t.oneofs&&(s.value=`asInt`)),e.filteredAttributes&&e.filteredAttributes.length){s.filteredAttributes=[];for(var S=0;S<e.filteredAttributes.length;++S)s.filteredAttributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.filteredAttributes[S],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.Exemplar`},e})(),e})(),e})(),e.logs=(function(){var e={};return e.v1=(function(){var e={};return e.LogsData=(function(){function e(e){if(this.resourceLogs=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resourceLogs=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resourceLogs!=null&&e.resourceLogs.length)for(var s=0;s<e.resourceLogs.length;++s)E.opentelemetry.proto.logs.v1.ResourceLogs.encode(e.resourceLogs[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.logs.v1.LogsData;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resourceLogs&&w.resourceLogs.length||(w.resourceLogs=[]),w.resourceLogs.push(E.opentelemetry.proto.logs.v1.ResourceLogs.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resourceLogs!=null&&e.hasOwnProperty(`resourceLogs`)){if(!Array.isArray(e.resourceLogs))return`resourceLogs: array expected`;for(var t=0;t<e.resourceLogs.length;++t){var s=E.opentelemetry.proto.logs.v1.ResourceLogs.verify(e.resourceLogs[t]);if(s)return`resourceLogs.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.logs.v1.LogsData)return e;var t=new E.opentelemetry.proto.logs.v1.LogsData;if(e.resourceLogs){if(!Array.isArray(e.resourceLogs))throw TypeError(`.opentelemetry.proto.logs.v1.LogsData.resourceLogs: array expected`);t.resourceLogs=[];for(var s=0;s<e.resourceLogs.length;++s){if(typeof e.resourceLogs[s]!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.LogsData.resourceLogs: object expected`);t.resourceLogs[s]=E.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(e.resourceLogs[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.resourceLogs=[]),e.resourceLogs&&e.resourceLogs.length){s.resourceLogs=[];for(var g=0;g<e.resourceLogs.length;++g)s.resourceLogs[g]=E.opentelemetry.proto.logs.v1.ResourceLogs.toObject(e.resourceLogs[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.logs.v1.LogsData`},e})(),e.ResourceLogs=(function(){function e(e){if(this.scopeLogs=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resource=null,e.prototype.scopeLogs=w.emptyArray,e.prototype.schemaUrl=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resource!=null&&Object.hasOwnProperty.call(e,`resource`)&&E.opentelemetry.proto.resource.v1.Resource.encode(e.resource,t.uint32(10).fork()).ldelim(),e.scopeLogs!=null&&e.scopeLogs.length)for(var s=0;s<e.scopeLogs.length;++s)E.opentelemetry.proto.logs.v1.ScopeLogs.encode(e.scopeLogs[s],t.uint32(18).fork()).ldelim();return e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(26).string(e.schemaUrl),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.logs.v1.ResourceLogs;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resource=E.opentelemetry.proto.resource.v1.Resource.decode(e,e.uint32());break;case 2:w.scopeLogs&&w.scopeLogs.length||(w.scopeLogs=[]),w.scopeLogs.push(E.opentelemetry.proto.logs.v1.ScopeLogs.decode(e,e.uint32()));break;case 3:w.schemaUrl=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resource!=null&&e.hasOwnProperty(`resource`)){var t=E.opentelemetry.proto.resource.v1.Resource.verify(e.resource);if(t)return`resource.`+t}if(e.scopeLogs!=null&&e.hasOwnProperty(`scopeLogs`)){if(!Array.isArray(e.scopeLogs))return`scopeLogs: array expected`;for(var s=0;s<e.scopeLogs.length;++s){var t=E.opentelemetry.proto.logs.v1.ScopeLogs.verify(e.scopeLogs[s]);if(t)return`scopeLogs.`+t}}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl)?`schemaUrl: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.logs.v1.ResourceLogs)return e;var t=new E.opentelemetry.proto.logs.v1.ResourceLogs;if(e.resource!=null){if(typeof e.resource!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.ResourceLogs.resource: object expected`);t.resource=E.opentelemetry.proto.resource.v1.Resource.fromObject(e.resource)}if(e.scopeLogs){if(!Array.isArray(e.scopeLogs))throw TypeError(`.opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: array expected`);t.scopeLogs=[];for(var s=0;s<e.scopeLogs.length;++s){if(typeof e.scopeLogs[s]!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: object expected`);t.scopeLogs[s]=E.opentelemetry.proto.logs.v1.ScopeLogs.fromObject(e.scopeLogs[s])}}return e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.scopeLogs=[]),t.defaults&&(s.resource=null,s.schemaUrl=``),e.resource!=null&&e.hasOwnProperty(`resource`)&&(s.resource=E.opentelemetry.proto.resource.v1.Resource.toObject(e.resource,t)),e.scopeLogs&&e.scopeLogs.length){s.scopeLogs=[];for(var g=0;g<e.scopeLogs.length;++g)s.scopeLogs[g]=E.opentelemetry.proto.logs.v1.ScopeLogs.toObject(e.scopeLogs[g],t)}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.logs.v1.ResourceLogs`},e})(),e.ScopeLogs=(function(){function e(e){if(this.logRecords=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.scope=null,e.prototype.logRecords=w.emptyArray,e.prototype.schemaUrl=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.scope!=null&&Object.hasOwnProperty.call(e,`scope`)&&E.opentelemetry.proto.common.v1.InstrumentationScope.encode(e.scope,t.uint32(10).fork()).ldelim(),e.logRecords!=null&&e.logRecords.length)for(var s=0;s<e.logRecords.length;++s)E.opentelemetry.proto.logs.v1.LogRecord.encode(e.logRecords[s],t.uint32(18).fork()).ldelim();return e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(26).string(e.schemaUrl),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.logs.v1.ScopeLogs;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.decode(e,e.uint32());break;case 2:w.logRecords&&w.logRecords.length||(w.logRecords=[]),w.logRecords.push(E.opentelemetry.proto.logs.v1.LogRecord.decode(e,e.uint32()));break;case 3:w.schemaUrl=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.scope!=null&&e.hasOwnProperty(`scope`)){var t=E.opentelemetry.proto.common.v1.InstrumentationScope.verify(e.scope);if(t)return`scope.`+t}if(e.logRecords!=null&&e.hasOwnProperty(`logRecords`)){if(!Array.isArray(e.logRecords))return`logRecords: array expected`;for(var s=0;s<e.logRecords.length;++s){var t=E.opentelemetry.proto.logs.v1.LogRecord.verify(e.logRecords[s]);if(t)return`logRecords.`+t}}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl)?`schemaUrl: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.logs.v1.ScopeLogs)return e;var t=new E.opentelemetry.proto.logs.v1.ScopeLogs;if(e.scope!=null){if(typeof e.scope!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.ScopeLogs.scope: object expected`);t.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(e.scope)}if(e.logRecords){if(!Array.isArray(e.logRecords))throw TypeError(`.opentelemetry.proto.logs.v1.ScopeLogs.logRecords: array expected`);t.logRecords=[];for(var s=0;s<e.logRecords.length;++s){if(typeof e.logRecords[s]!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.ScopeLogs.logRecords: object expected`);t.logRecords[s]=E.opentelemetry.proto.logs.v1.LogRecord.fromObject(e.logRecords[s])}}return e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.logRecords=[]),t.defaults&&(s.scope=null,s.schemaUrl=``),e.scope!=null&&e.hasOwnProperty(`scope`)&&(s.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.toObject(e.scope,t)),e.logRecords&&e.logRecords.length){s.logRecords=[];for(var g=0;g<e.logRecords.length;++g)s.logRecords[g]=E.opentelemetry.proto.logs.v1.LogRecord.toObject(e.logRecords[g],t)}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.logs.v1.ScopeLogs`},e})(),e.SeverityNumber=(function(){var e={},t=Object.create(e);return t[e[0]=`SEVERITY_NUMBER_UNSPECIFIED`]=0,t[e[1]=`SEVERITY_NUMBER_TRACE`]=1,t[e[2]=`SEVERITY_NUMBER_TRACE2`]=2,t[e[3]=`SEVERITY_NUMBER_TRACE3`]=3,t[e[4]=`SEVERITY_NUMBER_TRACE4`]=4,t[e[5]=`SEVERITY_NUMBER_DEBUG`]=5,t[e[6]=`SEVERITY_NUMBER_DEBUG2`]=6,t[e[7]=`SEVERITY_NUMBER_DEBUG3`]=7,t[e[8]=`SEVERITY_NUMBER_DEBUG4`]=8,t[e[9]=`SEVERITY_NUMBER_INFO`]=9,t[e[10]=`SEVERITY_NUMBER_INFO2`]=10,t[e[11]=`SEVERITY_NUMBER_INFO3`]=11,t[e[12]=`SEVERITY_NUMBER_INFO4`]=12,t[e[13]=`SEVERITY_NUMBER_WARN`]=13,t[e[14]=`SEVERITY_NUMBER_WARN2`]=14,t[e[15]=`SEVERITY_NUMBER_WARN3`]=15,t[e[16]=`SEVERITY_NUMBER_WARN4`]=16,t[e[17]=`SEVERITY_NUMBER_ERROR`]=17,t[e[18]=`SEVERITY_NUMBER_ERROR2`]=18,t[e[19]=`SEVERITY_NUMBER_ERROR3`]=19,t[e[20]=`SEVERITY_NUMBER_ERROR4`]=20,t[e[21]=`SEVERITY_NUMBER_FATAL`]=21,t[e[22]=`SEVERITY_NUMBER_FATAL2`]=22,t[e[23]=`SEVERITY_NUMBER_FATAL3`]=23,t[e[24]=`SEVERITY_NUMBER_FATAL4`]=24,t})(),e.LogRecordFlags=(function(){var e={},t=Object.create(e);return t[e[0]=`LOG_RECORD_FLAGS_DO_NOT_USE`]=0,t[e[255]=`LOG_RECORD_FLAGS_TRACE_FLAGS_MASK`]=255,t})(),e.LogRecord=(function(){function e(e){if(this.attributes=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.timeUnixNano=null,e.prototype.observedTimeUnixNano=null,e.prototype.severityNumber=null,e.prototype.severityText=null,e.prototype.body=null,e.prototype.attributes=w.emptyArray,e.prototype.droppedAttributesCount=null,e.prototype.flags=null,e.prototype.traceId=null,e.prototype.spanId=null,e.prototype.eventName=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(9).fixed64(e.timeUnixNano),e.severityNumber!=null&&Object.hasOwnProperty.call(e,`severityNumber`)&&t.uint32(16).int32(e.severityNumber),e.severityText!=null&&Object.hasOwnProperty.call(e,`severityText`)&&t.uint32(26).string(e.severityText),e.body!=null&&Object.hasOwnProperty.call(e,`body`)&&E.opentelemetry.proto.common.v1.AnyValue.encode(e.body,t.uint32(42).fork()).ldelim(),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(50).fork()).ldelim();return e.droppedAttributesCount!=null&&Object.hasOwnProperty.call(e,`droppedAttributesCount`)&&t.uint32(56).uint32(e.droppedAttributesCount),e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(69).fixed32(e.flags),e.traceId!=null&&Object.hasOwnProperty.call(e,`traceId`)&&t.uint32(74).bytes(e.traceId),e.spanId!=null&&Object.hasOwnProperty.call(e,`spanId`)&&t.uint32(82).bytes(e.spanId),e.observedTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`observedTimeUnixNano`)&&t.uint32(89).fixed64(e.observedTimeUnixNano),e.eventName!=null&&Object.hasOwnProperty.call(e,`eventName`)&&t.uint32(98).string(e.eventName),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.logs.v1.LogRecord;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.timeUnixNano=e.fixed64();break;case 11:w.observedTimeUnixNano=e.fixed64();break;case 2:w.severityNumber=e.int32();break;case 3:w.severityText=e.string();break;case 5:w.body=E.opentelemetry.proto.common.v1.AnyValue.decode(e,e.uint32());break;case 6:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 7:w.droppedAttributesCount=e.uint32();break;case 8:w.flags=e.fixed32();break;case 9:w.traceId=e.bytes();break;case 10:w.spanId=e.bytes();break;case 12:w.eventName=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.observedTimeUnixNano!=null&&e.hasOwnProperty(`observedTimeUnixNano`)&&!w.isInteger(e.observedTimeUnixNano)&&!(e.observedTimeUnixNano&&w.isInteger(e.observedTimeUnixNano.low)&&w.isInteger(e.observedTimeUnixNano.high)))return`observedTimeUnixNano: integer|Long expected`;if(e.severityNumber!=null&&e.hasOwnProperty(`severityNumber`))switch(e.severityNumber){default:return`severityNumber: enum value expected`;case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:case 16:case 17:case 18:case 19:case 20:case 21:case 22:case 23:case 24:break}if(e.severityText!=null&&e.hasOwnProperty(`severityText`)&&!w.isString(e.severityText))return`severityText: string expected`;if(e.body!=null&&e.hasOwnProperty(`body`)){var t=E.opentelemetry.proto.common.v1.AnyValue.verify(e.body);if(t)return`body.`+t}if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var s=0;s<e.attributes.length;++s){var t=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[s]);if(t)return`attributes.`+t}}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&!w.isInteger(e.droppedAttributesCount)?`droppedAttributesCount: integer expected`:e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags)?`flags: integer expected`:e.traceId!=null&&e.hasOwnProperty(`traceId`)&&!(e.traceId&&typeof e.traceId.length==`number`||w.isString(e.traceId))?`traceId: buffer expected`:e.spanId!=null&&e.hasOwnProperty(`spanId`)&&!(e.spanId&&typeof e.spanId.length==`number`||w.isString(e.spanId))?`spanId: buffer expected`:e.eventName!=null&&e.hasOwnProperty(`eventName`)&&!w.isString(e.eventName)?`eventName: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.logs.v1.LogRecord)return e;var t=new E.opentelemetry.proto.logs.v1.LogRecord;switch(e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.observedTimeUnixNano!=null&&(w.Long?(t.observedTimeUnixNano=w.Long.fromValue(e.observedTimeUnixNano)).unsigned=!1:typeof e.observedTimeUnixNano==`string`?t.observedTimeUnixNano=parseInt(e.observedTimeUnixNano,10):typeof e.observedTimeUnixNano==`number`?t.observedTimeUnixNano=e.observedTimeUnixNano:typeof e.observedTimeUnixNano==`object`&&(t.observedTimeUnixNano=new w.LongBits(e.observedTimeUnixNano.low>>>0,e.observedTimeUnixNano.high>>>0).toNumber())),e.severityNumber){default:if(typeof e.severityNumber==`number`){t.severityNumber=e.severityNumber;break}break;case`SEVERITY_NUMBER_UNSPECIFIED`:case 0:t.severityNumber=0;break;case`SEVERITY_NUMBER_TRACE`:case 1:t.severityNumber=1;break;case`SEVERITY_NUMBER_TRACE2`:case 2:t.severityNumber=2;break;case`SEVERITY_NUMBER_TRACE3`:case 3:t.severityNumber=3;break;case`SEVERITY_NUMBER_TRACE4`:case 4:t.severityNumber=4;break;case`SEVERITY_NUMBER_DEBUG`:case 5:t.severityNumber=5;break;case`SEVERITY_NUMBER_DEBUG2`:case 6:t.severityNumber=6;break;case`SEVERITY_NUMBER_DEBUG3`:case 7:t.severityNumber=7;break;case`SEVERITY_NUMBER_DEBUG4`:case 8:t.severityNumber=8;break;case`SEVERITY_NUMBER_INFO`:case 9:t.severityNumber=9;break;case`SEVERITY_NUMBER_INFO2`:case 10:t.severityNumber=10;break;case`SEVERITY_NUMBER_INFO3`:case 11:t.severityNumber=11;break;case`SEVERITY_NUMBER_INFO4`:case 12:t.severityNumber=12;break;case`SEVERITY_NUMBER_WARN`:case 13:t.severityNumber=13;break;case`SEVERITY_NUMBER_WARN2`:case 14:t.severityNumber=14;break;case`SEVERITY_NUMBER_WARN3`:case 15:t.severityNumber=15;break;case`SEVERITY_NUMBER_WARN4`:case 16:t.severityNumber=16;break;case`SEVERITY_NUMBER_ERROR`:case 17:t.severityNumber=17;break;case`SEVERITY_NUMBER_ERROR2`:case 18:t.severityNumber=18;break;case`SEVERITY_NUMBER_ERROR3`:case 19:t.severityNumber=19;break;case`SEVERITY_NUMBER_ERROR4`:case 20:t.severityNumber=20;break;case`SEVERITY_NUMBER_FATAL`:case 21:t.severityNumber=21;break;case`SEVERITY_NUMBER_FATAL2`:case 22:t.severityNumber=22;break;case`SEVERITY_NUMBER_FATAL3`:case 23:t.severityNumber=23;break;case`SEVERITY_NUMBER_FATAL4`:case 24:t.severityNumber=24;break}if(e.severityText!=null&&(t.severityText=String(e.severityText)),e.body!=null){if(typeof e.body!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.LogRecord.body: object expected`);t.body=E.opentelemetry.proto.common.v1.AnyValue.fromObject(e.body)}if(e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.logs.v1.LogRecord.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.LogRecord.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}return e.droppedAttributesCount!=null&&(t.droppedAttributesCount=e.droppedAttributesCount>>>0),e.flags!=null&&(t.flags=e.flags>>>0),e.traceId!=null&&(typeof e.traceId==`string`?w.base64.decode(e.traceId,t.traceId=w.newBuffer(w.base64.length(e.traceId)),0):e.traceId.length>=0&&(t.traceId=e.traceId)),e.spanId!=null&&(typeof e.spanId==`string`?w.base64.decode(e.spanId,t.spanId=w.newBuffer(w.base64.length(e.spanId)),0):e.spanId.length>=0&&(t.spanId=e.spanId)),e.eventName!=null&&(t.eventName=String(e.eventName)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;if(s.severityNumber=t.enums===String?`SEVERITY_NUMBER_UNSPECIFIED`:0,s.severityText=``,s.body=null,s.droppedAttributesCount=0,s.flags=0,t.bytes===String?s.traceId=``:(s.traceId=[],t.bytes!==Array&&(s.traceId=w.newBuffer(s.traceId))),t.bytes===String?s.spanId=``:(s.spanId=[],t.bytes!==Array&&(s.spanId=w.newBuffer(s.spanId))),w.Long){var g=new w.Long(0,0,!1);s.observedTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.observedTimeUnixNano=t.longs===String?`0`:0;s.eventName=``}if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.severityNumber!=null&&e.hasOwnProperty(`severityNumber`)&&(s.severityNumber=t.enums===String?E.opentelemetry.proto.logs.v1.SeverityNumber[e.severityNumber]===void 0?e.severityNumber:E.opentelemetry.proto.logs.v1.SeverityNumber[e.severityNumber]:e.severityNumber),e.severityText!=null&&e.hasOwnProperty(`severityText`)&&(s.severityText=e.severityText),e.body!=null&&e.hasOwnProperty(`body`)&&(s.body=E.opentelemetry.proto.common.v1.AnyValue.toObject(e.body,t)),e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&(s.droppedAttributesCount=e.droppedAttributesCount),e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),e.traceId!=null&&e.hasOwnProperty(`traceId`)&&(s.traceId=t.bytes===String?w.base64.encode(e.traceId,0,e.traceId.length):t.bytes===Array?Array.prototype.slice.call(e.traceId):e.traceId),e.spanId!=null&&e.hasOwnProperty(`spanId`)&&(s.spanId=t.bytes===String?w.base64.encode(e.spanId,0,e.spanId.length):t.bytes===Array?Array.prototype.slice.call(e.spanId):e.spanId),e.observedTimeUnixNano!=null&&e.hasOwnProperty(`observedTimeUnixNano`)&&(typeof e.observedTimeUnixNano==`number`?s.observedTimeUnixNano=t.longs===String?String(e.observedTimeUnixNano):e.observedTimeUnixNano:s.observedTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.observedTimeUnixNano):t.longs===Number?new w.LongBits(e.observedTimeUnixNano.low>>>0,e.observedTimeUnixNano.high>>>0).toNumber():e.observedTimeUnixNano),e.eventName!=null&&e.hasOwnProperty(`eventName`)&&(s.eventName=e.eventName),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.logs.v1.LogRecord`},e})(),e})(),e})(),e})(),e})(),t.exports=E})),require_suppress_tracing$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isTracingSuppressed=e.unsuppressTracing=e.suppressTracing=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key SUPPRESS_TRACING`);function s(e){return e.setValue(t,!0)}e.suppressTracing=s;function g(e){return e.deleteValue(t)}e.unsuppressTracing=g;function S(e){return e.getValue(t)===!0}e.isTracingSuppressed=S})),require_constants$6=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BAGGAGE_MAX_TOTAL_LENGTH=e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=e.BAGGAGE_MAX_NAME_VALUE_PAIRS=e.BAGGAGE_HEADER=e.BAGGAGE_ITEMS_SEPARATOR=e.BAGGAGE_PROPERTIES_SEPARATOR=e.BAGGAGE_KEY_PAIR_SEPARATOR=void 0,e.BAGGAGE_KEY_PAIR_SEPARATOR=`=`,e.BAGGAGE_PROPERTIES_SEPARATOR=`;`,e.BAGGAGE_ITEMS_SEPARATOR=`,`,e.BAGGAGE_HEADER=`baggage`,e.BAGGAGE_MAX_NAME_VALUE_PAIRS=180,e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,e.BAGGAGE_MAX_TOTAL_LENGTH=8192})),require_utils$15=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseKeyPairsIntoRecord=e.parsePairKeyValue=e.getKeyPairs=e.serializeKeyPairs=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_constants$6();function g(e){return e.reduce((e,t)=>{let g=`${e}${e===``?``:s.BAGGAGE_ITEMS_SEPARATOR}${t}`;return g.length>s.BAGGAGE_MAX_TOTAL_LENGTH?e:g},``)}e.serializeKeyPairs=g;function S(e){return e.getAllEntries().map(([e,t])=>{let g=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return t.metadata!==void 0&&(g+=s.BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),g})}e.getKeyPairs=S;function w(e){let g=e.split(s.BAGGAGE_PROPERTIES_SEPARATOR);if(g.length<=0)return;let S=g.shift();if(!S)return;let w=S.indexOf(s.BAGGAGE_KEY_PAIR_SEPARATOR);if(w<=0)return;let E=decodeURIComponent(S.substring(0,w).trim()),D=decodeURIComponent(S.substring(w+1).trim()),O;return g.length>0&&(O=(0,t.baggageEntryMetadataFromString)(g.join(s.BAGGAGE_PROPERTIES_SEPARATOR))),{key:E,value:D,metadata:O}}e.parsePairKeyValue=w;function E(e){let t={};return typeof e==`string`&&e.length>0&&e.split(s.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let s=w(e);s!==void 0&&s.value.length>0&&(t[s.key]=s.value)}),t}e.parseKeyPairsIntoRecord=E})),require_W3CBaggagePropagator$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CBaggagePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$2(),g=require_constants$6(),S=require_utils$15();e.W3CBaggagePropagator=class{inject(e,w,E){let D=t.propagation.getBaggage(e);if(!D||(0,s.isTracingSuppressed)(e))return;let O=(0,S.getKeyPairs)(D).filter(e=>e.length<=g.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,g.BAGGAGE_MAX_NAME_VALUE_PAIRS),k=(0,S.serializeKeyPairs)(O);k.length>0&&E.set(w,g.BAGGAGE_HEADER,k)}extract(e,s,w){let E=w.get(s,g.BAGGAGE_HEADER),D=Array.isArray(E)?E.join(g.BAGGAGE_ITEMS_SEPARATOR):E;if(!D)return e;let O={};return D.length===0||(D.split(g.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let t=(0,S.parsePairKeyValue)(e);if(t){let e={value:t.value};t.metadata&&(e.metadata=t.metadata),O[t.key]=e}}),Object.entries(O).length===0)?e:t.propagation.setBaggage(e,t.propagation.createBaggage(O))}fields(){return[g.BAGGAGE_HEADER]}}})),require_anchored_clock$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AnchoredClock=void 0,e.AnchoredClock=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}})),require_attributes$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isAttributeValue=e.isAttributeKey=e.sanitizeAttributes=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function s(e){let s={};if(typeof e!=`object`||!e)return s;for(let[w,E]of Object.entries(e)){if(!g(w)){t.diag.warn(`Invalid attribute key: ${w}`);continue}if(!S(E)){t.diag.warn(`Invalid attribute value set for key: ${w}`);continue}Array.isArray(E)?s[w]=E.slice():s[w]=E}return s}e.sanitizeAttributes=s;function g(e){return typeof e==`string`&&e.length>0}e.isAttributeKey=g;function S(e){return e==null?!0:Array.isArray(e)?w(e):E(e)}e.isAttributeValue=S;function w(e){let t;for(let s of e)if(s!=null){if(!t){if(E(s)){t=typeof s;continue}return!1}if(typeof s!==t)return!1}return!0}function E(e){switch(typeof e){case`number`:case`boolean`:case`string`:return!0}return!1}})),require_logging_error_handler$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.loggingErrorHandler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function s(){return e=>{t.diag.error(g(e))}}e.loggingErrorHandler=s;function g(e){return typeof e==`string`?e:JSON.stringify(S(e))}function S(e){let t={},s=e;for(;s!==null;)Object.getOwnPropertyNames(s).forEach(e=>{if(t[e])return;let g=s[e];g&&(t[e]=String(g))}),s=Object.getPrototypeOf(s);return t}})),require_global_error_handler$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.globalErrorHandler=e.setGlobalErrorHandler=void 0;let t=(0,require_logging_error_handler$2().loggingErrorHandler)();function s(e){t=e}e.setGlobalErrorHandler=s;function g(e){try{t(e)}catch{}}e.globalErrorHandler=g})),require_environment$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e.getNumberFromEnv=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=__require$2(`util`);function g(e){let g=process.env[e];if(g==null||g.trim()===``)return;let S=Number(g);if(isNaN(S)){t.diag.warn(`Unknown value ${(0,s.inspect)(g)} for ${e}, expected a number, using defaults`);return}return S}e.getNumberFromEnv=g;function S(e){let t=process.env[e];if(!(t==null||t.trim()===``))return t}e.getStringFromEnv=S;function w(e){let g=process.env[e]?.trim().toLowerCase();return g==null||g===``?!1:g===`true`?!0:(g===`false`||t.diag.warn(`Unknown value ${(0,s.inspect)(g)} for ${e}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}e.getBooleanFromEnv=w;function E(e){return S(e)?.split(`,`).map(e=>e.trim()).filter(e=>e!==``)}e.getStringListFromEnv=E})),require_globalThis$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._globalThis=void 0,e._globalThis=typeof globalThis==`object`?globalThis:global})),require_performance$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.otperformance=void 0,e.otperformance=__require$2(`perf_hooks`).performance})),require_version$5=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.1.0`})),require_semconv$6=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_PROCESS_RUNTIME_NAME=void 0,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`})),require_sdk_info$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SDK_INFO=void 0;let t=require_version$5(),s=(init_esm$1(),__toCommonJS(esm_exports$1)),g=require_semconv$6();e.SDK_INFO={[s.ATTR_TELEMETRY_SDK_NAME]:`opentelemetry`,[g.ATTR_PROCESS_RUNTIME_NAME]:`node`,[s.ATTR_TELEMETRY_SDK_LANGUAGE]:s.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[s.ATTR_TELEMETRY_SDK_VERSION]:t.VERSION}})),require_timer_util$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=void 0;function t(e){e.unref()}e.unrefTimer=t})),require_node$10=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=e.SDK_INFO=e.otperformance=e._globalThis=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=void 0;var t=require_environment$2();Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}});var s=require_globalThis$2();Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return s._globalThis}});var g=require_performance$2();Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return g.otperformance}});var S=require_sdk_info$2();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return S.SDK_INFO}});var w=require_timer_util$2();Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return w.unrefTimer}})})),require_platform$10=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getNumberFromEnv=e.getStringFromEnv=e.getBooleanFromEnv=e.unrefTimer=e.otperformance=e._globalThis=e.SDK_INFO=void 0;var t=require_node$10();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return t.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return t._globalThis}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return t.otperformance}}),Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return t.unrefTimer}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}})})),require_time$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.addHrTimes=e.isTimeInput=e.isTimeInputHrTime=e.hrTimeToMicroseconds=e.hrTimeToMilliseconds=e.hrTimeToNanoseconds=e.hrTimeToTimeStamp=e.hrTimeDuration=e.timeInputToHrTime=e.hrTime=e.getTimeOrigin=e.millisToHrTime=void 0;let t=require_platform$10(),s=9,g=10**6,S=10**9;function w(e){let t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*g)]}e.millisToHrTime=w;function E(){let e=t.otperformance.timeOrigin;if(typeof e!=`number`){let s=t.otperformance;e=s.timing&&s.timing.fetchStart}return e}e.getTimeOrigin=E;function D(e){return ee(w(E()),w(typeof e==`number`?e:t.otperformance.now()))}e.hrTime=D;function O(e){if(H(e))return e;if(typeof e==`number`)return e<E()?D(e):w(e);if(e instanceof Date)return w(e.getTime());throw TypeError(`Invalid input type`)}e.timeInputToHrTime=O;function k(e,t){let s=t[0]-e[0],g=t[1]-e[1];return g<0&&(--s,g+=S),[s,g]}e.hrTimeDuration=k;function j(e){let t=9,s=`${`0`.repeat(9)}${e[1]}Z`,g=s.substring(s.length-9-1);return new Date(e[0]*1e3).toISOString().replace(`000Z`,g)}e.hrTimeToTimeStamp=j;function F(e){return e[0]*S+e[1]}e.hrTimeToNanoseconds=F;function L(e){return e[0]*1e3+e[1]/1e6}e.hrTimeToMilliseconds=L;function B(e){return e[0]*1e6+e[1]/1e3}e.hrTimeToMicroseconds=B;function H(e){return Array.isArray(e)&&e.length===2&&typeof e[0]==`number`&&typeof e[1]==`number`}e.isTimeInputHrTime=H;function q(e){return H(e)||typeof e==`number`||e instanceof Date}e.isTimeInput=q;function ee(e,t){let s=[e[0]+t[0],e[1]+t[1]];return s[1]>=S&&(s[1]-=S,s[0]+=1),s}e.addHrTimes=ee})),require_ExportResult$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExportResultCode=void 0,(function(e){e[e.SUCCESS=0]=`SUCCESS`,e[e.FAILED=1]=`FAILED`})(e.ExportResultCode||={})})),require_composite$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CompositePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));e.CompositePropagator=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>typeof e.fields==`function`?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,s,g){for(let S of this._propagators)try{S.inject(e,s,g)}catch(e){t.diag.warn(`Failed to inject with ${S.constructor.name}. Err: ${e.message}`)}}extract(e,s,g){return this._propagators.reduce((e,S)=>{try{return S.extract(e,s,g)}catch(e){t.diag.warn(`Failed to extract with ${S.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}})),require_validators$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateValue=e.validateKey=void 0;let t=`[_0-9a-z-*/]`,s=`[a-z]${t}{0,255}`,g=`[a-z0-9]${t}{0,240}@[a-z]${t}{0,13}`,S=RegExp(`^(?:${s}|${g})$`),w=/^[ -~]{0,255}[!-~]$/,E=/,|=/;function D(e){return S.test(e)}e.validateKey=D;function O(e){return w.test(e)&&!E.test(e)}e.validateValue=O})),require_TraceState$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceState=void 0;let t=require_validators$2(),s=32,g=512,S=`,`,w=`=`;e.TraceState=class e{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){let s=this._clone();return s._internalState.has(e)&&s._internalState.delete(e),s._internalState.set(e,t),s}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+`=`+this.get(t)),e),[]).join(`,`)}_parse(e){e.length>512||(this._internalState=e.split(`,`).reverse().reduce((e,s)=>{let g=s.trim(),S=g.indexOf(`=`);if(S!==-1){let w=g.slice(0,S),E=g.slice(S+1,s.length);(0,t.validateKey)(w)&&(0,t.validateValue)(E)&&e.set(w,E)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let t=new e;return t._internalState=new Map(this._internalState),t}}})),require_W3CTraceContextPropagator$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CTraceContextPropagator=e.parseTraceParent=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$2(),g=require_TraceState$2();e.TRACE_PARENT_HEADER=`traceparent`,e.TRACE_STATE_HEADER=`tracestate`;let S=`00`,w=RegExp(`^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$`);function E(e){let t=w.exec(e);return!t||t[1]===`00`&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}}e.parseTraceParent=E,e.W3CTraceContextPropagator=class{inject(g,S,w){let E=t.trace.getSpanContext(g);if(!E||(0,s.isTracingSuppressed)(g)||!(0,t.isSpanContextValid)(E))return;let D=`00-${E.traceId}-${E.spanId}-0${Number(E.traceFlags||t.TraceFlags.NONE).toString(16)}`;w.set(S,e.TRACE_PARENT_HEADER,D),E.traceState&&w.set(S,e.TRACE_STATE_HEADER,E.traceState.serialize())}extract(s,S,w){let D=w.get(S,e.TRACE_PARENT_HEADER);if(!D)return s;let O=Array.isArray(D)?D[0]:D;if(typeof O!=`string`)return s;let k=E(O);if(!k)return s;k.isRemote=!0;let j=w.get(S,e.TRACE_STATE_HEADER);if(j){let e=Array.isArray(j)?j.join(`,`):j;k.traceState=new g.TraceState(typeof e==`string`?e:void 0)}return t.trace.setSpanContext(s,k)}fields(){return[e.TRACE_PARENT_HEADER,e.TRACE_STATE_HEADER]}}})),require_rpc_metadata$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRPCMetadata=e.deleteRPCMetadata=e.setRPCMetadata=e.RPCType=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key RPC_METADATA`);(function(e){e.HTTP=`http`})(e.RPCType||={});function s(e,s){return e.setValue(t,s)}e.setRPCMetadata=s;function g(e){return e.deleteValue(t)}e.deleteRPCMetadata=g;function S(e){return e.getValue(t)}e.getRPCMetadata=S})),require_lodash_merge$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isPlainObject=void 0;let t=`[object Object]`,s=`[object Null]`,g=`[object Undefined]`,S=Function.prototype.toString,w=S.call(Object),E=Object.getPrototypeOf,D=Object.prototype,O=D.hasOwnProperty,k=Symbol?Symbol.toStringTag:void 0,j=D.toString;function F(e){if(!L(e)||B(e)!==`[object Object]`)return!1;let t=E(e);if(t===null)return!0;let s=O.call(t,`constructor`)&&t.constructor;return typeof s==`function`&&s instanceof s&&S.call(s)===w}e.isPlainObject=F;function L(e){return typeof e==`object`&&!!e}function B(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:k&&k in Object(e)?H(e):q(e)}function H(e){let t=O.call(e,k),s=e[k],g=!1;try{e[k]=void 0,g=!0}catch{}let S=j.call(e);return g&&(t?e[k]=s:delete e[k]),S}function q(e){return j.call(e)}})),require_merge$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.merge=void 0;let t=require_lodash_merge$2(),s=20;function g(...e){let t=e.shift(),s=new WeakMap;for(;e.length>0;)t=w(t,e.shift(),0,s);return t}e.merge=g;function S(e){return D(e)?e.slice():e}function w(e,t,s=0,g){let L;if(!(s>20)){if(s++,j(e)||j(t)||O(t))L=S(t);else if(D(e)){if(L=e.slice(),D(t))for(let e=0,s=t.length;e<s;e++)L.push(S(t[e]));else if(k(t)){let e=Object.keys(t);for(let s=0,g=e.length;s<g;s++){let g=e[s];L[g]=S(t[g])}}}else if(k(e))if(k(t)){if(!F(e,t))return t;L=Object.assign({},e);let S=Object.keys(t);for(let D=0,O=S.length;D<O;D++){let O=S[D],F=t[O];if(j(F))F===void 0?delete L[O]:L[O]=F;else{let S=L[O],D=F;if(E(e,O,g)||E(t,O,g))delete L[O];else{if(k(S)&&k(D)){let s=g.get(S)||[],w=g.get(D)||[];s.push({obj:e,key:O}),w.push({obj:t,key:O}),g.set(S,s),g.set(D,w)}L[O]=w(L[O],F,s,g)}}}}else L=t;return L}}function E(e,t,s){let g=s.get(e[t])||[];for(let s=0,S=g.length;s<S;s++){let S=g[s];if(S.key===t&&S.obj===e)return!0}return!1}function D(e){return Array.isArray(e)}function O(e){return typeof e==`function`}function k(e){return!j(e)&&!D(e)&&!O(e)&&typeof e==`object`}function j(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e===void 0||e instanceof Date||e instanceof RegExp||e===null}function F(e,s){return!(!(0,t.isPlainObject)(e)||!(0,t.isPlainObject)(s))}})),require_timeout$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callWithTimeout=e.TimeoutError=void 0;var t=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=t;function s(e,s){let g,S=new Promise(function(e,S){g=setTimeout(function(){S(new t(`Operation timed out.`))},s)});return Promise.race([e,S]).then(e=>(clearTimeout(g),e),e=>{throw clearTimeout(g),e})}e.callWithTimeout=s})),require_url$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isUrlIgnored=e.urlMatches=void 0;function t(e,t){return typeof t==`string`?e===t:!!e.match(t)}e.urlMatches=t;function s(e,s){if(!s)return!1;for(let g of s)if(t(e,g))return!0;return!1}e.isUrlIgnored=s})),require_promise$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Deferred=void 0,e.Deferred=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}})),require_callback$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BindOnceFuture=void 0;let t=require_promise$2();e.BindOnceFuture=class{_callback;_that;_isCalled=!1;_deferred=new t.Deferred;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}})),require_configuration$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.diagLogLevelFromString=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s={ALL:t.DiagLogLevel.ALL,VERBOSE:t.DiagLogLevel.VERBOSE,DEBUG:t.DiagLogLevel.DEBUG,INFO:t.DiagLogLevel.INFO,WARN:t.DiagLogLevel.WARN,ERROR:t.DiagLogLevel.ERROR,NONE:t.DiagLogLevel.NONE};function g(e){return e==null?void 0:s[e.toUpperCase()]??(t.diag.warn(`Unknown log level "${e}", expected one of ${Object.keys(s)}, using default`),t.DiagLogLevel.INFO)}e.diagLogLevelFromString=g})),require_exporter$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._export=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$2();function g(e,g){return new Promise(S=>{t.context.with((0,s.suppressTracing)(t.context.active()),()=>{e.export(g,e=>{S(e)})})})}e._export=g})),require_src$13=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.internal=e.diagLogLevelFromString=e.BindOnceFuture=e.urlMatches=e.isUrlIgnored=e.callWithTimeout=e.TimeoutError=e.merge=e.TraceState=e.unsuppressTracing=e.suppressTracing=e.isTracingSuppressed=e.setRPCMetadata=e.getRPCMetadata=e.deleteRPCMetadata=e.RPCType=e.parseTraceParent=e.W3CTraceContextPropagator=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=e.CompositePropagator=e.unrefTimer=e.otperformance=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e._globalThis=e.SDK_INFO=e.parseKeyPairsIntoRecord=e.ExportResultCode=e.timeInputToHrTime=e.millisToHrTime=e.isTimeInputHrTime=e.isTimeInput=e.hrTimeToTimeStamp=e.hrTimeToNanoseconds=e.hrTimeToMilliseconds=e.hrTimeToMicroseconds=e.hrTimeDuration=e.hrTime=e.getTimeOrigin=e.addHrTimes=e.loggingErrorHandler=e.setGlobalErrorHandler=e.globalErrorHandler=e.sanitizeAttributes=e.isAttributeValue=e.AnchoredClock=e.W3CBaggagePropagator=void 0;var t=require_W3CBaggagePropagator$2();Object.defineProperty(e,`W3CBaggagePropagator`,{enumerable:!0,get:function(){return t.W3CBaggagePropagator}});var s=require_anchored_clock$2();Object.defineProperty(e,`AnchoredClock`,{enumerable:!0,get:function(){return s.AnchoredClock}});var g=require_attributes$2();Object.defineProperty(e,`isAttributeValue`,{enumerable:!0,get:function(){return g.isAttributeValue}}),Object.defineProperty(e,`sanitizeAttributes`,{enumerable:!0,get:function(){return g.sanitizeAttributes}});var S=require_global_error_handler$2();Object.defineProperty(e,`globalErrorHandler`,{enumerable:!0,get:function(){return S.globalErrorHandler}}),Object.defineProperty(e,`setGlobalErrorHandler`,{enumerable:!0,get:function(){return S.setGlobalErrorHandler}});var w=require_logging_error_handler$2();Object.defineProperty(e,`loggingErrorHandler`,{enumerable:!0,get:function(){return w.loggingErrorHandler}});var E=require_time$3();Object.defineProperty(e,`addHrTimes`,{enumerable:!0,get:function(){return E.addHrTimes}}),Object.defineProperty(e,`getTimeOrigin`,{enumerable:!0,get:function(){return E.getTimeOrigin}}),Object.defineProperty(e,`hrTime`,{enumerable:!0,get:function(){return E.hrTime}}),Object.defineProperty(e,`hrTimeDuration`,{enumerable:!0,get:function(){return E.hrTimeDuration}}),Object.defineProperty(e,`hrTimeToMicroseconds`,{enumerable:!0,get:function(){return E.hrTimeToMicroseconds}}),Object.defineProperty(e,`hrTimeToMilliseconds`,{enumerable:!0,get:function(){return E.hrTimeToMilliseconds}}),Object.defineProperty(e,`hrTimeToNanoseconds`,{enumerable:!0,get:function(){return E.hrTimeToNanoseconds}}),Object.defineProperty(e,`hrTimeToTimeStamp`,{enumerable:!0,get:function(){return E.hrTimeToTimeStamp}}),Object.defineProperty(e,`isTimeInput`,{enumerable:!0,get:function(){return E.isTimeInput}}),Object.defineProperty(e,`isTimeInputHrTime`,{enumerable:!0,get:function(){return E.isTimeInputHrTime}}),Object.defineProperty(e,`millisToHrTime`,{enumerable:!0,get:function(){return E.millisToHrTime}}),Object.defineProperty(e,`timeInputToHrTime`,{enumerable:!0,get:function(){return E.timeInputToHrTime}});var D=require_ExportResult$2();Object.defineProperty(e,`ExportResultCode`,{enumerable:!0,get:function(){return D.ExportResultCode}});var O=require_utils$15();Object.defineProperty(e,`parseKeyPairsIntoRecord`,{enumerable:!0,get:function(){return O.parseKeyPairsIntoRecord}});var k=require_platform$10();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return k.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return k._globalThis}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return k.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return k.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return k.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return k.getStringListFromEnv}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return k.otperformance}}),Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return k.unrefTimer}});var j=require_composite$2();Object.defineProperty(e,`CompositePropagator`,{enumerable:!0,get:function(){return j.CompositePropagator}});var F=require_W3CTraceContextPropagator$2();Object.defineProperty(e,`TRACE_PARENT_HEADER`,{enumerable:!0,get:function(){return F.TRACE_PARENT_HEADER}}),Object.defineProperty(e,`TRACE_STATE_HEADER`,{enumerable:!0,get:function(){return F.TRACE_STATE_HEADER}}),Object.defineProperty(e,`W3CTraceContextPropagator`,{enumerable:!0,get:function(){return F.W3CTraceContextPropagator}}),Object.defineProperty(e,`parseTraceParent`,{enumerable:!0,get:function(){return F.parseTraceParent}});var L=require_rpc_metadata$2();Object.defineProperty(e,`RPCType`,{enumerable:!0,get:function(){return L.RPCType}}),Object.defineProperty(e,`deleteRPCMetadata`,{enumerable:!0,get:function(){return L.deleteRPCMetadata}}),Object.defineProperty(e,`getRPCMetadata`,{enumerable:!0,get:function(){return L.getRPCMetadata}}),Object.defineProperty(e,`setRPCMetadata`,{enumerable:!0,get:function(){return L.setRPCMetadata}});var B=require_suppress_tracing$2();Object.defineProperty(e,`isTracingSuppressed`,{enumerable:!0,get:function(){return B.isTracingSuppressed}}),Object.defineProperty(e,`suppressTracing`,{enumerable:!0,get:function(){return B.suppressTracing}}),Object.defineProperty(e,`unsuppressTracing`,{enumerable:!0,get:function(){return B.unsuppressTracing}});var H=require_TraceState$2();Object.defineProperty(e,`TraceState`,{enumerable:!0,get:function(){return H.TraceState}});var q=require_merge$2();Object.defineProperty(e,`merge`,{enumerable:!0,get:function(){return q.merge}});var ee=require_timeout$2();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return ee.TimeoutError}}),Object.defineProperty(e,`callWithTimeout`,{enumerable:!0,get:function(){return ee.callWithTimeout}});var J=require_url$2();Object.defineProperty(e,`isUrlIgnored`,{enumerable:!0,get:function(){return J.isUrlIgnored}}),Object.defineProperty(e,`urlMatches`,{enumerable:!0,get:function(){return J.urlMatches}});var Y=require_callback$2();Object.defineProperty(e,`BindOnceFuture`,{enumerable:!0,get:function(){return Y.BindOnceFuture}});var te=require_configuration$2();Object.defineProperty(e,`diagLogLevelFromString`,{enumerable:!0,get:function(){return te.diagLogLevelFromString}}),e.internal={_export:require_exporter$2()._export}})),require_hex_to_binary=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hexToBinary=void 0;function t(e){return e>=48&&e<=57?e-48:e>=97&&e<=102?e-87:e-55}function s(e){let s=new Uint8Array(e.length/2),g=0;for(let S=0;S<e.length;S+=2){let w=t(e.charCodeAt(S)),E=t(e.charCodeAt(S+1));s[g++]=w<<4|E}return s}e.hexToBinary=s})),require_utils$14=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getOtlpEncoder=e.encodeAsString=e.encodeAsLongBits=e.toLongBits=e.hrTimeToNanos=void 0;let t=require_src$13(),s=require_hex_to_binary();function g(e){let t=BigInt(1e9);return BigInt(e[0])*t+BigInt(e[1])}e.hrTimeToNanos=g;function S(e){return{low:Number(BigInt.asUintN(32,e)),high:Number(BigInt.asUintN(32,e>>BigInt(32)))}}e.toLongBits=S;function w(e){return S(g(e))}e.encodeAsLongBits=w;function E(e){return g(e).toString()}e.encodeAsString=E;let D=typeof BigInt<`u`?E:t.hrTimeToNanoseconds;function O(e){return e}function k(e){if(e!==void 0)return(0,s.hexToBinary)(e)}let j={encodeHrTime:w,encodeSpanContext:s.hexToBinary,encodeOptionalSpanContext:k};function F(e){if(e===void 0)return j;let t=e.useLongBits??!0,g=e.useHex??!1;return{encodeHrTime:t?w:D,encodeSpanContext:g?O:s.hexToBinary,encodeOptionalSpanContext:g?O:k}}e.getOtlpEncoder=F})),require_internal$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.toAnyValue=e.toKeyValue=e.toAttributes=e.createInstrumentationScope=e.createResource=void 0;function t(e){let t={attributes:g(e.attributes),droppedAttributesCount:0},s=e.schemaUrl;return s&&s!==``&&(t.schemaUrl=s),t}e.createResource=t;function s(e){return{name:e.name,version:e.version}}e.createInstrumentationScope=s;function g(e){return Object.keys(e).map(t=>S(t,e[t]))}e.toAttributes=g;function S(e,t){return{key:e,value:w(t)}}e.toKeyValue=S;function w(e){let t=typeof e;return t===`string`?{stringValue:e}:t===`number`?Number.isInteger(e)?{intValue:e}:{doubleValue:e}:t===`boolean`?{boolValue:e}:e instanceof Uint8Array?{bytesValue:e}:Array.isArray(e)?{arrayValue:{values:e.map(w)}}:t===`object`&&e!=null?{kvlistValue:{values:Object.entries(e).map(([e,t])=>S(e,t))}}:{}}e.toAnyValue=w})),require_internal$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.toLogAttributes=e.createExportLogsServiceRequest=void 0;let t=require_utils$14(),s=require_internal$3();function g(e,s){return{resourceLogs:w(e,(0,t.getOtlpEncoder)(s))}}e.createExportLogsServiceRequest=g;function S(e){let t=new Map;for(let s of e){let{resource:e,instrumentationScope:{name:g,version:S=``,schemaUrl:w=``}}=s,E=t.get(e);E||(E=new Map,t.set(e,E));let D=`${g}@${S}:${w}`,O=E.get(D);O||(O=[],E.set(D,O)),O.push(s)}return t}function w(e,t){let g=S(e);return Array.from(g,([e,g])=>{let S=(0,s.createResource)(e);return{resource:S,scopeLogs:Array.from(g,([,e])=>({scope:(0,s.createInstrumentationScope)(e[0].instrumentationScope),logRecords:e.map(e=>E(e,t)),schemaUrl:e[0].instrumentationScope.schemaUrl})),schemaUrl:S.schemaUrl}})}function E(e,t){return{timeUnixNano:t.encodeHrTime(e.hrTime),observedTimeUnixNano:t.encodeHrTime(e.hrTimeObserved),severityNumber:D(e.severityNumber),severityText:e.severityText,body:(0,s.toAnyValue)(e.body),eventName:e.eventName,attributes:O(e.attributes),droppedAttributesCount:e.droppedAttributesCount,flags:e.spanContext?.traceFlags,traceId:t.encodeOptionalSpanContext(e.spanContext?.traceId),spanId:t.encodeOptionalSpanContext(e.spanContext?.spanId)}}function D(e){return e}function O(e){return Object.keys(e).map(t=>(0,s.toKeyValue)(t,e[t]))}e.toLogAttributes=O})),require_logs$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufLogsSerializer=void 0;let t=require_root(),s=require_internal$2(),g=t.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse,S=t.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest;e.ProtobufLogsSerializer={serializeRequest:e=>{let t=(0,s.createExportLogsServiceRequest)(e);return S.encode(t).finish()},deserializeResponse:e=>g.decode(e)}})),require_protobuf$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufLogsSerializer=void 0;var t=require_logs$1();Object.defineProperty(e,`ProtobufLogsSerializer`,{enumerable:!0,get:function(){return t.ProtobufLogsSerializer}})})),require_AggregationTemporality$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AggregationTemporality=void 0,(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(e.AggregationTemporality||={})})),require_MetricData$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DataPointType=e.InstrumentType=void 0,(function(e){e.COUNTER=`COUNTER`,e.GAUGE=`GAUGE`,e.HISTOGRAM=`HISTOGRAM`,e.UP_DOWN_COUNTER=`UP_DOWN_COUNTER`,e.OBSERVABLE_COUNTER=`OBSERVABLE_COUNTER`,e.OBSERVABLE_GAUGE=`OBSERVABLE_GAUGE`,e.OBSERVABLE_UP_DOWN_COUNTER=`OBSERVABLE_UP_DOWN_COUNTER`})(e.InstrumentType||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(e.DataPointType||={})})),require_utils$13=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.equalsCaseInsensitive=e.binarySearchUB=e.setEquals=e.FlatMap=e.isPromiseAllSettledRejectionResult=e.PromiseAllSettled=e.callWithTimeout=e.TimeoutError=e.instrumentationScopeId=e.hashAttributes=e.isNotNullish=void 0;function t(e){return e!=null}e.isNotNullish=t;function s(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}e.hashAttributes=s;function g(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}e.instrumentationScopeId=g;var S=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=S;function w(e,t){let s,g=new Promise(function(e,g){s=setTimeout(function(){g(new S(`Operation timed out.`))},t)});return Promise.race([e,g]).then(e=>(clearTimeout(s),e),e=>{throw clearTimeout(s),e})}e.callWithTimeout=w;async function E(e){return Promise.all(e.map(async e=>{try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}))}e.PromiseAllSettled=E;function D(e){return e.status===`rejected`}e.isPromiseAllSettledRejectionResult=D;function O(e,t){let s=[];return e.forEach(e=>{s.push(...t(e))}),s}e.FlatMap=O;function k(e,t){if(e.size!==t.size)return!1;for(let s of e)if(!t.has(s))return!1;return!0}e.setEquals=k;function j(e,t){let s=0,g=e.length-1,S=e.length;for(;g>=s;){let w=s+Math.trunc((g-s)/2);e[w]<t?s=w+1:(S=w,g=w-1)}return S}e.binarySearchUB=j;function F(e,t){return e.toLowerCase()===t.toLowerCase()}e.equalsCaseInsensitive=F})),require_types$6=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AggregatorKind=void 0,(function(e){e[e.DROP=0]=`DROP`,e[e.SUM=1]=`SUM`,e[e.LAST_VALUE=2]=`LAST_VALUE`,e[e.HISTOGRAM=3]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=4]=`EXPONENTIAL_HISTOGRAM`})(e.AggregatorKind||={})})),require_Drop$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DropAggregator=void 0;let t=require_types$6();e.DropAggregator=class{kind=t.AggregatorKind.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,s,g){}}})),require_Histogram$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.HistogramAggregator=e.HistogramAccumulation=void 0;let t=require_types$6(),s=require_MetricData$2(),g=require_utils$13();function S(e){let t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var w=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,s=!0,g=S(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=s,this._current=g}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);let t=(0,g.binarySearchUB)(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}};e.HistogramAccumulation=w,e.HistogramAggregator=class{_boundaries;_recordMinMax;kind=t.AggregatorKind.HISTOGRAM;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new w(e,this._boundaries,this._recordMinMax)}merge(e,t){let s=e.toPointValue(),g=t.toPointValue(),S=s.buckets.counts,E=g.buckets.counts,D=Array(S.length);for(let e=0;e<S.length;e++)D[e]=S[e]+E[e];let O=1/0,k=-1/0;return this._recordMinMax&&(s.hasMinMax&&g.hasMinMax?(O=Math.min(s.min,g.min),k=Math.max(s.max,g.max)):s.hasMinMax?(O=s.min,k=s.max):g.hasMinMax&&(O=g.min,k=g.max)),new w(e.startTime,s.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:s.buckets.boundaries,counts:D},count:s.count+g.count,sum:s.sum+g.sum,hasMinMax:this._recordMinMax&&(s.hasMinMax||g.hasMinMax),min:O,max:k})}diff(e,t){let s=e.toPointValue(),g=t.toPointValue(),S=s.buckets.counts,E=g.buckets.counts,D=Array(S.length);for(let e=0;e<S.length;e++)D[e]=E[e]-S[e];return new w(t.startTime,s.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:s.buckets.boundaries,counts:D},count:g.count-s.count,sum:g.sum-s.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,t,g,S){return{descriptor:e,aggregationTemporality:t,dataPointType:s.DataPointType.HISTOGRAM,dataPoints:g.map(([t,g])=>{let w=g.toPointValue(),E=e.type===s.InstrumentType.GAUGE||e.type===s.InstrumentType.UP_DOWN_COUNTER||e.type===s.InstrumentType.OBSERVABLE_GAUGE||e.type===s.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:g.startTime,endTime:S,value:{min:w.hasMinMax?w.min:void 0,max:w.hasMinMax?w.max:void 0,sum:E?void 0:w.sum,buckets:w.buckets,count:w.count}}})}}}})),require_Buckets$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Buckets=void 0,e.Buckets=class e{backing;indexBase;indexStart;indexEnd;constructor(e=new t,s=0,g=0,S=0){this.backing=e,this.indexBase=s,this.indexStart=g,this.indexEnd=S}get offset(){return this.indexStart}get length(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){let t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)}incrementBucket(e,t){this.backing.increment(e,t)}decrementBucket(e,t){this.backing.decrement(e,t)}trim(){for(let e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(let e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();let t=1+this.indexEnd-this.indexStart,s=1<<e,g=0,S=0;for(let e=this.indexStart;e<=this.indexEnd;){let w=e%s;w<0&&(w+=s);for(let E=w;E<s&&g<t;E++)this._relocateBucket(S,g),g++,e++;S++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new e(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){let e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}};var t=class e{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,s){let g=Array(e).fill(0);g.splice(s,this._counts.length-t,...this._counts.slice(t)),g.splice(0,t,...this._counts.slice(0,t)),this._counts=g}reverse(e,t){let s=Math.floor((e+t)/2)-e;for(let g=0;g<s;g++){let s=this._counts[e+g];this._counts[e+g]=this._counts[t-g-1],this._counts[t-g-1]=s}}emptyBucket(e){let t=this._counts[e];return this._counts[e]=0,t}increment(e,t){this._counts[e]+=t}decrement(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new e([...this._counts])}}})),require_ieee754$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSignificand=e.getNormalBase2=e.MIN_VALUE=e.MAX_NORMAL_EXPONENT=e.MIN_NORMAL_EXPONENT=e.SIGNIFICAND_WIDTH=void 0,e.SIGNIFICAND_WIDTH=52;let t=2146435072,s=1048575,g=1023;e.MIN_NORMAL_EXPONENT=-g+1,e.MAX_NORMAL_EXPONENT=g,e.MIN_VALUE=2**-1022;function S(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e),((t.getUint32(0)&2146435072)>>20)-g}e.getNormalBase2=S;function w(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let s=t.getUint32(0),g=t.getUint32(4);return(s&1048575)*2**32+g}e.getSignificand=w})),require_util$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.nextGreaterSquare=e.ldexp=void 0;function t(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}e.ldexp=t;function s(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}e.nextGreaterSquare=s})),require_types$5=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MappingError=void 0,e.MappingError=class extends Error{}})),require_ExponentMapping$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExponentMapping=void 0;let t=require_ieee754$2(),s=require_util$3(),g=require_types$5();e.ExponentMapping=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<t.MIN_VALUE?this._minNormalLowerBoundaryIndex():t.getNormalBase2(e)+this._rightShift(t.getSignificand(e)-1,t.SIGNIFICAND_WIDTH)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new g.MappingError(`underflow: ${e} is < minimum lower boundary: ${t}`);let S=this._maxNormalLowerBoundaryIndex();if(e>S)throw new g.MappingError(`overflow: ${e} is > maximum lower boundary: ${S}`);return s.ldexp(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=t.MIN_NORMAL_EXPONENT>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return t.MAX_NORMAL_EXPONENT>>this._shift}_rightShift(e,t){return Math.floor(e*2**-t)}}})),require_LogarithmMapping$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LogarithmMapping=void 0;let t=require_ieee754$2(),s=require_util$3(),g=require_types$5();e.LogarithmMapping=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=s.ldexp(Math.LOG2E,e),this._inverseFactor=s.ldexp(Math.LN2,-e)}mapToIndex(e){if(e<=t.MIN_VALUE)return this._minNormalLowerBoundaryIndex()-1;if(t.getSignificand(e)===0)return(t.getNormalBase2(e)<<this._scale)-1;let s=Math.floor(Math.log(e)*this._scaleFactor),g=this._maxNormalLowerBoundaryIndex();return s>=g?g:s}lowerBoundary(e){let s=this._maxNormalLowerBoundaryIndex();if(e>=s){if(e===s)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new g.MappingError(`overflow: ${e} is > maximum lower boundary: ${s}`)}let S=this._minNormalLowerBoundaryIndex();if(e<=S){if(e===S)return t.MIN_VALUE;if(e===S-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new g.MappingError(`overflow: ${e} is < minimum lower boundary: ${S}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return t.MIN_NORMAL_EXPONENT<<this._scale}_maxNormalLowerBoundaryIndex(){return(t.MAX_NORMAL_EXPONENT+1<<this._scale)-1}}})),require_getMapping$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getMapping=void 0;let t=require_ExponentMapping$2(),s=require_LogarithmMapping$2(),g=require_types$5(),S=-10,w=20,E=Array.from({length:31},(e,g)=>g>10?new s.LogarithmMapping(g-10):new t.ExponentMapping(g-10));function D(e){if(e>20||e<-10)throw new g.MappingError(`expected scale >= -10 && <= 20, got: ${e}`);return E[e+10]}e.getMapping=D})),require_ExponentialHistogram$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExponentialHistogramAggregator=e.ExponentialHistogramAccumulation=void 0;let t=require_types$6(),s=require_MetricData$2(),g=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_Buckets$2(),w=require_getMapping$2(),E=require_util$3();var D=class e{low;high;static combine(t,s){return new e(Math.min(t.low,s.low),Math.max(t.high,s.high))}constructor(e,t){this.low=e,this.high=t}};let O=20,k=160,j=2;var F=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=160,s=!0,E=0,D=0,O=0,k=1/0,j=-1/0,F=new S.Buckets,L=new S.Buckets,B=(0,w.getMapping)(20)){this.startTime=e,this._maxSize=t,this._recordMinMax=s,this._sum=E,this._count=D,this._zeroCount=O,this._min=k,this._max=j,this._positive=F,this._negative=L,this._mapping=B,this._maxSize<2&&(g.diag.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
|
|
@@ -47,7 +47,7 @@ To resolve the conflict:`,(0,g.getConflictResolutionRecipe)(S,e))),w=E):s.diag.w
|
|
|
47
47
|
missingProperty: ${S},
|
|
48
48
|
depsCount: ${s},
|
|
49
49
|
deps: ${g}}`};let S={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,s]=w(e);E(e,t),D(e,s)}};function w({schema:e}){let t={},s={};for(let g in e){if(g===`__proto__`)continue;let S=Array.isArray(e[g])?t:s;S[g]=e[g]}return[t,s]}function E(e,s=e.schema){let{gen:S,data:w,it:E}=e;if(Object.keys(s).length===0)return;let D=S.let(`missing`);for(let O in s){let k=s[O];if(k.length===0)continue;let j=(0,g.propertyInData)(S,w,O,E.opts.ownProperties);e.setParams({property:O,depsCount:k.length,deps:k.join(`, `)}),E.allErrors?S.if(j,()=>{for(let t of k)(0,g.checkReportMissingProp)(e,t)}):(S.if((0,t._)`${j} && (${(0,g.checkMissingProp)(e,k,D)})`),(0,g.reportMissingProp)(e,D),S.else())}}e.validatePropertyDeps=E;function D(e,t=e.schema){let{gen:S,data:w,keyword:E,it:D}=e,O=S.name(`valid`);for(let k in t)(0,s.alwaysValidSchema)(D,t[k])||(S.if((0,g.propertyInData)(S,w,k,D.opts.ownProperties),()=>{let t=e.subschema({keyword:E,schemaProp:k},O);e.mergeValidEvaluated(t,O)},()=>S.var(O,!0)),e.ok(O))}e.validateSchemaDeps=D,e.default=S})),require_propertyNames=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:g,schema:S,data:w,it:E}=e;if((0,s.alwaysValidSchema)(E,S))return;let D=g.name(`valid`);g.forIn(`key`,w,s=>{e.setParams({propertyName:s}),e.subschema({keyword:`propertyNames`,data:s,dataTypes:[`string`],propertyName:s,compositeRule:!0},D),g.if((0,t.not)(D),()=>{e.error(!0),E.allErrors||g.break()})}),e.ok(D)}}})),require_additionalProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_names(),S=require_util();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,s._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:w,schema:E,parentSchema:D,data:O,errsCount:k,it:j}=e;if(!k)throw Error(`ajv implementation error`);let{allErrors:F,opts:L}=j;if(j.props=!0,L.removeAdditional!==`all`&&(0,S.alwaysValidSchema)(j,E))return;let B=(0,t.allSchemaProperties)(D.properties),H=(0,t.allSchemaProperties)(D.patternProperties);q(),e.ok((0,s._)`${k} === ${g.default.errors}`);function q(){w.forIn(`key`,O,e=>{!B.length&&!H.length?Y(e):w.if(ee(e),()=>Y(e))})}function ee(g){let E;if(B.length>8){let e=(0,S.schemaRefOrVal)(j,D.properties,`properties`);E=(0,t.isOwnProperty)(w,e,g)}else E=B.length?(0,s.or)(...B.map(e=>(0,s._)`${g} === ${e}`)):s.nil;return H.length&&(E=(0,s.or)(E,...H.map(S=>(0,s._)`${(0,t.usePattern)(e,S)}.test(${g})`))),(0,s.not)(E)}function J(e){w.code((0,s._)`delete ${O}[${e}]`)}function Y(t){if(L.removeAdditional===`all`||L.removeAdditional&&E===!1){J(t);return}if(E===!1){e.setParams({additionalProperty:t}),e.error(),F||w.break();return}if(typeof E==`object`&&!(0,S.alwaysValidSchema)(j,E)){let g=w.name(`valid`);L.removeAdditional===`failing`?(te(t,g,!1),w.if((0,s.not)(g),()=>{e.reset(),J(t)})):(te(t,g),F||w.if((0,s.not)(g),()=>w.break()))}}function te(t,s,g){let w={keyword:`additionalProperties`,dataProp:t,dataPropType:S.Type.Str};g===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(w,s)}}}})),require_properties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_validate(),s=require_code(),g=require_util(),S=require_additionalProperties();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,parentSchema:D,data:O,it:k}=e;k.opts.removeAdditional===`all`&&D.additionalProperties===void 0&&S.default.code(new t.KeywordCxt(k,S.default,`additionalProperties`));let j=(0,s.allSchemaProperties)(E);for(let e of j)k.definedProperties.add(e);k.opts.unevaluated&&j.length&&k.props!==!0&&(k.props=g.mergeEvaluated.props(w,(0,g.toHash)(j),k.props));let F=j.filter(e=>!(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0)return;let L=w.name(`valid`);for(let t of F)B(t)?H(t):(w.if((0,s.propertyInData)(w,O,t,k.opts.ownProperties)),H(t),k.allErrors||w.else().var(L,!0),w.endIf()),e.it.definedProperties.add(t),e.ok(L);function B(e){return k.opts.useDefaults&&!k.compositeRule&&E[e].default!==void 0}function H(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},L)}}}})),require_patternProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_util(),S=require_util();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,data:D,parentSchema:O,it:k}=e,{opts:j}=k,F=(0,t.allSchemaProperties)(E),L=F.filter(e=>(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0||L.length===F.length&&(!k.opts.unevaluated||k.props===!0))return;let B=j.strictSchema&&!j.allowMatchingProperties&&O.properties,H=w.name(`valid`);k.props!==!0&&!(k.props instanceof s.Name)&&(k.props=(0,S.evaluatedPropsToName)(w,k.props));let{props:q}=k;ee();function ee(){for(let e of F)B&&J(e),k.allErrors?Y(e):(w.var(H,!0),Y(e),w.if(H))}function J(e){for(let t in B)new RegExp(e).test(t)&&(0,g.checkStrictMode)(k,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function Y(g){w.forIn(`key`,D,E=>{w.if((0,s._)`${(0,t.usePattern)(e,g)}.test(${E})`,()=>{let t=L.includes(g);t||e.subschema({keyword:`patternProperties`,schemaProp:g,dataProp:E,dataPropType:S.Type.Str},H),k.opts.unevaluated&&q!==!0?w.assign((0,s._)`${q}[${E}]`,!0):!t&&!k.allErrors&&w.if((0,s.not)(H),()=>w.break())})})}}}})),require_not=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:s,schema:g,it:S}=e;if((0,t.alwaysValidSchema)(S,g)){e.fail();return}let w=s.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},w),e.failResult(w,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),require_anyOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:require_code().validateUnion,error:{message:`must match a schema in anyOf`}}})),require_oneOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:g,schema:S,parentSchema:w,it:E}=e;if(!Array.isArray(S))throw Error(`ajv implementation error`);if(E.opts.discriminator&&w.discriminator)return;let D=S,O=g.let(`valid`,!1),k=g.let(`passing`,null),j=g.name(`_valid`);e.setParams({passing:k}),g.block(F),e.result(O,()=>e.reset(),()=>e.error(!0));function F(){D.forEach((S,w)=>{let D;(0,s.alwaysValidSchema)(E,S)?g.var(j,!0):D=e.subschema({keyword:`oneOf`,schemaProp:w,compositeRule:!0},j),w>0&&g.if((0,t._)`${j} && ${O}`).assign(O,!1).assign(k,(0,t._)`[${k}, ${w}]`).else(),g.if(j,()=>{g.assign(O,!0),g.assign(k,w),D&&e.mergeEvaluated(D,t.Name)})})}}}})),require_allOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:s,schema:g,it:S}=e;if(!Array.isArray(g))throw Error(`ajv implementation error`);let w=s.name(`valid`);g.forEach((s,g)=>{if((0,t.alwaysValidSchema)(S,s))return;let E=e.subschema({keyword:`allOf`,schemaProp:g},w);e.ok(w),e.mergeEvaluated(E)})}}})),require_if=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:g,parentSchema:w,it:E}=e;w.then===void 0&&w.else===void 0&&(0,s.checkStrictMode)(E,`"if" without "then" and "else" is ignored`);let D=S(E,`then`),O=S(E,`else`);if(!D&&!O)return;let k=g.let(`valid`,!0),j=g.name(`_valid`);if(F(),e.reset(),D&&O){let t=g.let(`ifClause`);e.setParams({ifClause:t}),g.if(j,L(`then`,t),L(`else`,t))}else D?g.if(j,L(`then`)):g.if((0,t.not)(j),L(`else`));e.pass(k,()=>e.error(!0));function F(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},j);e.mergeEvaluated(t)}function L(s,S){return()=>{let w=e.subschema({keyword:s},j);g.assign(k,j),e.mergeValidEvaluated(w,k),S?g.assign(S,(0,t._)`${s}`):e.setParams({ifClause:s})}}}};function S(e,t){let g=e.schema[t];return g!==void 0&&!(0,s.alwaysValidSchema)(e,g)}e.default=g})),require_thenElse=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:s,it:g}){s.if===void 0&&(0,t.checkStrictMode)(g,`"${e}" without "if" is ignored`)}}})),require_applicator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_additionalItems(),s=require_prefixItems(),g=require_items(),S=require_items2020(),w=require_contains(),E=require_dependencies(),D=require_propertyNames(),O=require_additionalProperties(),k=require_properties(),j=require_patternProperties(),F=require_not(),L=require_anyOf(),B=require_oneOf(),H=require_allOf(),q=require_if(),ee=require_thenElse();function J(e=!1){let J=[F.default,L.default,B.default,H.default,q.default,ee.default,D.default,O.default,E.default,k.default,j.default];return e?J.push(s.default,S.default):J.push(t.default,g.default),J.push(w.default),J}e.default=J})),require_format$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,s){let{gen:g,data:S,$data:w,schema:E,schemaCode:D,it:O}=e,{opts:k,errSchemaPath:j,schemaEnv:F,self:L}=O;if(!k.validateFormats)return;w?B():H();function B(){let w=g.scopeValue(`formats`,{ref:L.formats,code:k.code.formats}),E=g.const(`fDef`,(0,t._)`${w}[${D}]`),O=g.let(`fType`),j=g.let(`format`);g.if((0,t._)`typeof ${E} == "object" && !(${E} instanceof RegExp)`,()=>g.assign(O,(0,t._)`${E}.type || "string"`).assign(j,(0,t._)`${E}.validate`),()=>g.assign(O,(0,t._)`"string"`).assign(j,E)),e.fail$data((0,t.or)(B(),H()));function B(){return k.strictSchema===!1?t.nil:(0,t._)`${D} && !${j}`}function H(){let e=F.$async?(0,t._)`(${E}.async ? await ${j}(${S}) : ${j}(${S}))`:(0,t._)`${j}(${S})`,g=(0,t._)`(typeof ${j} == "function" ? ${e} : ${j}.test(${S}))`;return(0,t._)`${j} && ${j} !== true && ${O} === ${s} && !${g}`}}function H(){let w=L.formats[E];if(!w){H();return}if(w===!0)return;let[D,O,B]=q(w);D===s&&e.pass(ee());function H(){if(k.strictSchema===!1){L.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${E}" ignored in schema at path "${j}"`}}function q(e){let s=e instanceof RegExp?(0,t.regexpCode)(e):k.code.formats?(0,t._)`${k.code.formats}${(0,t.getProperty)(E)}`:void 0,S=g.scopeValue(`formats`,{key:E,ref:e,code:s});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${S}.validate`]:[`string`,e,S]}function ee(){if(typeof w==`object`&&!(w instanceof RegExp)&&w.async){if(!F.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${B}(${S})`}return typeof O==`function`?(0,t._)`${B}(${S})`:(0,t._)`${B}.test(${S})`}}}}})),require_format=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[require_format$1().default]})),require_metadata=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),require_draft7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_core(),s=require_validation$2(),g=require_applicator(),S=require_format(),w=require_metadata();e.default=[t.default,s.default,(0,g.default)(),S.default,w.metadataVocabulary,w.contentVocabulary]})),require_types=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),require_discriminator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_types(),g=require_compile(),S=require_ref_error(),w=require_util();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===s.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:s,tagName:g}})=>(0,t._)`{error: ${e}, tag: ${g}, tagValue: ${s}}`},code(e){let{gen:E,data:D,schema:O,parentSchema:k,it:j}=e,{oneOf:F}=k;if(!j.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let L=O.propertyName;if(typeof L!=`string`)throw Error(`discriminator: requires propertyName`);if(O.mapping)throw Error(`discriminator: mapping is not supported`);if(!F)throw Error(`discriminator: requires oneOf keyword`);let B=E.let(`valid`,!1),H=E.const(`tag`,(0,t._)`${D}${(0,t.getProperty)(L)}`);E.if((0,t._)`typeof ${H} == "string"`,()=>q(),()=>e.error(!1,{discrError:s.DiscrError.Tag,tag:H,tagName:L})),e.ok(B);function q(){let g=J();E.if(!1);for(let e in g)E.elseIf((0,t._)`${H} === ${e}`),E.assign(B,ee(g[e]));E.else(),e.error(!1,{discrError:s.DiscrError.Mapping,tag:H,tagName:L}),E.endIf()}function ee(s){let g=E.name(`valid`),S=e.subschema({keyword:`oneOf`,schemaProp:s},g);return e.mergeEvaluated(S,t.Name),g}function J(){var e;let t={},s=D(k),E=!0;for(let e=0;e<F.length;e++){let t=F[e];if(t?.$ref&&!(0,w.schemaHasRulesButRef)(t,j.self.RULES)){let e=t.$ref;if(t=g.resolveRef.call(j.self,j.schemaEnv.root,j.baseId,e),t instanceof g.SchemaEnv&&(t=t.schema),t===void 0)throw new S.default(j.opts.uriResolver,j.baseId,e)}let k=t?.properties?.[L];if(typeof k!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${L}"`);E&&=s||D(t),O(k,e)}if(!E)throw Error(`discriminator: "${L}" must be required`);return t;function D({required:e}){return Array.isArray(e)&&e.includes(L)}function O(e,t){if(e.const)B(e.const,t);else if(e.enum)for(let s of e.enum)B(s,t);else throw Error(`discriminator: "properties/${L}" must have "const" or "enum"`)}function B(e,s){if(typeof e!=`string`||e in t)throw Error(`discriminator: "${L}" values must be unique strings`);t[e]=s}}}}})),require_json_schema_draft_07=__commonJSMin$2(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),require_ajv=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let s=require_core$1(),g=require_draft7(),S=require_discriminator(),w=require_json_schema_draft_07(),E=[`/properties`],D=`http://json-schema.org/draft-07/schema`;var O=class extends s.default{_addVocabularies(){super._addVocabularies(),g.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(S.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(w,E):w;this.addMetaSchema(e,D,!1),this.refs[`http://json-schema.org/schema`]=D}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(D)?D:void 0)}};e.Ajv=O,t.exports=e=O,t.exports.Ajv=O,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=O;var k=require_validate();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return k.KeywordCxt}});var j=require_codegen();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return j._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return j.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return j.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return j.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return j.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return j.CodeGen}});var F=require_validation_error();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return F.default}});var L=require_ref_error();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return L.default}})})),require_formats=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(w,E),time:t(O(!0),k),"date-time":t(L(!0),B),"iso-time":t(O(),j),"iso-date-time":t(L(),H),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:J,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:de,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:te,int32:{type:`number`,validate:oe},int64:{type:`number`,validate:se},float:{type:`number`,validate:ce},double:{type:`number`,validate:ce},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,E),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,k),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,B),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,j),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,H),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function s(e){return e%4==0&&(e%100!=0||e%400==0)}let g=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,S=[0,31,28,31,30,31,30,31,31,30,31,30,31];function w(e){let t=g.exec(e);if(!t)return!1;let w=+t[1],E=+t[2],D=+t[3];return E>=1&&E<=12&&D>=1&&D<=(E===2&&s(w)?29:S[E])}function E(e,t){if(e&&t)return e>t?1:e<t?-1:0}let D=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function O(e){return function(t){let s=D.exec(t);if(!s)return!1;let g=+s[1],S=+s[2],w=+s[3],E=s[4],O=s[5]===`-`?-1:1,k=+(s[6]||0),j=+(s[7]||0);if(k>23||j>59||e&&!E)return!1;if(g<=23&&S<=59&&w<60)return!0;let F=S-j*O,L=g-k*O-(F<0?1:0);return(L===23||L===-1)&&(F===59||F===-1)&&w<61}}function k(e,t){if(!(e&&t))return;let s=new Date(`2020-01-01T`+e).valueOf(),g=new Date(`2020-01-01T`+t).valueOf();if(s&&g)return s-g}function j(e,t){if(!(e&&t))return;let s=D.exec(e),g=D.exec(t);if(s&&g)return e=s[1]+s[2]+s[3],t=g[1]+g[2]+g[3],e>t?1:e<t?-1:0}let F=/t|\s/i;function L(e){let t=O(e);return function(e){let s=e.split(F);return s.length===2&&w(s[0])&&t(s[1])}}function B(e,t){if(!(e&&t))return;let s=new Date(e).valueOf(),g=new Date(t).valueOf();if(s&&g)return s-g}function H(e,t){if(!(e&&t))return;let[s,g]=e.split(F),[S,w]=t.split(F),D=E(s,S);if(D!==void 0)return D||k(g,w)}let q=/\/|:/,ee=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function J(e){return q.test(e)&&ee.test(e)}let Y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function te(e){return Y.lastIndex=0,Y.test(e)}let ne=-(2**31),ae=2**31-1;function oe(e){return Number.isInteger(e)&&e<=ae&&e>=ne}function se(e){return Number.isInteger(e)}function ce(){return!0}let ue=/[^\\]\\Z/;function de(e){if(ue.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),require_limit=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=require_ajv(),s=require_codegen(),g=s.operators,S={formatMaximum:{okStr:`<=`,ok:g.LTE,fail:g.GT},formatMinimum:{okStr:`>=`,ok:g.GTE,fail:g.LT},formatExclusiveMaximum:{okStr:`<`,ok:g.LT,fail:g.GTE},formatExclusiveMinimum:{okStr:`>`,ok:g.GT,fail:g.LTE}};e.formatLimitDefinition={keyword:Object.keys(S),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,s.str)`should be ${S[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,s._)`{comparison: ${S[e].okStr}, limit: ${t}}`},code(e){let{gen:g,data:w,schemaCode:E,keyword:D,it:O}=e,{opts:k,self:j}=O;if(!k.validateFormats)return;let F=new t.KeywordCxt(O,j.RULES.all.format.definition,`format`);F.$data?L():B();function L(){let t=g.scopeValue(`formats`,{ref:j.formats,code:k.code.formats}),S=g.const(`fmt`,(0,s._)`${t}[${F.schemaCode}]`);e.fail$data((0,s.or)((0,s._)`typeof ${S} != "object"`,(0,s._)`${S} instanceof RegExp`,(0,s._)`typeof ${S}.compare != "function"`,H(S)))}function B(){let t=F.schema,S=j.formats[t];if(!S||S===!0)return;if(typeof S!=`object`||S instanceof RegExp||typeof S.compare!=`function`)throw Error(`"${D}": format "${t}" does not define "compare" function`);let w=g.scopeValue(`formats`,{key:t,ref:S,code:k.code.formats?(0,s._)`${k.code.formats}${(0,s.getProperty)(t)}`:void 0});e.fail$data(H(w))}function H(e){return(0,s._)`${e}.compare(${w}, ${E}) ${S[D].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),require_dist=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let s=require_formats(),g=require_limit(),S=require_codegen(),w=new S.Name(`fullFormats`),E=new S.Name(`fastFormats`),D=(e,t={keywords:!0})=>{if(Array.isArray(t))return O(e,t,s.fullFormats,w),e;let[S,D]=t.mode===`fast`?[s.fastFormats,E]:[s.fullFormats,w];return O(e,t.formats||s.formatNames,S,D),t.keywords&&(0,g.default)(e),e};D.get=(e,t=`full`)=>{let g=(t===`fast`?s.fastFormats:s.fullFormats)[e];if(!g)throw Error(`Unknown format "${e}"`);return g};function O(e,t,s,g){var w,E;(E=e.opts.code).formats??(E.formats=(0,S._)`require("ajv-formats/dist/formats").${g}`);for(let g of t)e.addFormat(g,s[g])}t.exports=e=D,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=D})),import_ajv=__toESM$2(require_ajv(),1),import_dist=__toESM$2(require_dist(),1);function createDefaultAjvInstance(){let e=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_dist.default)(e),e}var AjvJsonSchemaValidator=class{constructor(e){this._ajv=e??createDefaultAjvInstance()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},ExperimentalServerTasks=class{constructor(e){this._server=e}requestStream(e,t,s){return this._server.requestStream(e,t,s)}createMessageStream(e,t){let s=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!s?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}elicitInputStream(e,t){let s=this._server.getClientCapabilities(),g=e.mode??`form`;switch(g){case`url`:if(!s?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!s?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let S=g===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:S},ElicitResultSchema,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,s){return this._server.getTaskResult({taskId:e},t,s)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function assertToolsCallTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${s} does not support task creation for tools/call (required for ${t})`);break;default:break}}function assertClientRequestTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${s} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${s} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Server=class extends Protocol{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let s=this._loggingLevels.get(t);return s?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,e=>this._oninitialize(e)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(e,t)=>{let s=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:g}=e.params,S=LoggingLevelSchema.safeParse(g);return S.success&&this._loggingLevels.set(s,S.data),{}})}get experimental(){return this._experimental||={tasks:new ExperimentalServerTasks(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=mergeCapabilities(this._capabilities,e)}setRequestHandler(e,t){let s=getObjectShape(e)?.method;if(!s)throw Error(`Schema is missing a method literal`);let g;if(isZ4Schema(s)){let e=s;g=e._zod?.def?.value??e.value}else{let e=s;g=e._def?.value??e.value}if(typeof g!=`string`)throw Error(`Schema method literal must be a string`);return g===`tools/call`?super.setRequestHandler(e,async(e,s)=>{let g=safeParse(CallToolRequestSchema,e);if(!g.success){let e=g.error instanceof Error?g.error.message:String(g.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:S}=g.data,w=await Promise.resolve(t(e,s));if(S.task){let e=safeParse(CreateTaskResultSchema,w);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let E=safeParse(CallToolResultSchema,w);if(!E.success){let e=E.error instanceof Error?E.error.message:String(E.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return E.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(t)?t:LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},EmptyResultSchema)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},CreateMessageResultWithToolsSchema,t):this.request({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let s=e;return this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let s=e.mode===`form`?e:{...e,mode:`form`},g=await this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t);if(g.action===`accept`&&g.content&&s.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(s.requestedSchema)(g.content);if(!e.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof McpError?e:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return g}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},ListRootsResultSchema,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const COMPLETABLE_SYMBOL=Symbol.for(`mcp.completable`);function isCompletable(e){return!!e&&typeof e==`object`&&COMPLETABLE_SYMBOL in e}function getCompleter(e){return e[COMPLETABLE_SYMBOL]?.complete}var McpZodTypeKind;(function(e){e.Completable=`McpCompletable`})(McpZodTypeKind||={});const TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!TOOL_NAME_REGEX.test(e)){let s=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,s)=>s.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${s.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function issueToolNameWarning(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function validateAndWarnToolName(e){let t=validateToolName(e);return issueToolNameWarning(e,t.warnings),t.isValid}var ExperimentalMcpServerTasks=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,s){let g={taskSupport:`required`,...t.execution};if(g.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,g,t._meta,s)}},McpServer=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Server(e,t)}get experimental(){return this._experimental||={tasks:new ExperimentalMcpServerTasks(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let s={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=normalizeObjectSchema(t.inputSchema);return e?toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`input`}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=normalizeObjectSchema(t.outputSchema);e&&(s.outputSchema=toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`output`}))}return s})})),this.server.setRequestHandler(CallToolRequestSchema,async(e,t)=>{try{let s=this._registeredTools[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);let g=!!e.params.task,S=s.execution?.taskSupport,w=`createTask`in s.handler;if((S===`required`||S===`optional`)&&!w)throw new McpError(ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${S}' but was not registered with registerToolTask`);if(S===`required`&&!g)throw new McpError(ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(S===`optional`&&!g&&w)return await this.handleAutomaticTaskPolling(s,e,t);let E=await this.validateToolInput(s,e.params.arguments,e.params.name),D=await this.executeToolHandler(s,E,t);return g||await this.validateToolOutput(s,D,e.params.name),D}catch(e){if(e instanceof McpError&&e.code===ErrorCode.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,s){if(!e.inputSchema)return;let g=await safeParseAsync(normalizeObjectSchema(e.inputSchema)??e.inputSchema,t);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${s}: ${e}`)}return g.data}async validateToolOutput(e,t,s){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${s} has an output schema but no structured content was provided`);let g=await safeParseAsync(normalizeObjectSchema(e.outputSchema),t.structuredContent);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${s}: ${e}`)}}async executeToolHandler(e,t,s){let g=e.handler;if(`createTask`in g){if(!s.taskStore)throw Error(`No task store provided.`);let S={...s,taskStore:s.taskStore};if(e.inputSchema){let e=g;return await Promise.resolve(e.createTask(t,S))}else{let e=g;return await Promise.resolve(e.createTask(S))}}if(e.inputSchema){let e=g;return await Promise.resolve(e(t,s))}else{let e=g;return await Promise.resolve(e(s))}}async handleAutomaticTaskPolling(e,t,s){if(!s.taskStore)throw Error(`No task store provided for task-capable tool.`);let g=await this.validateToolInput(e,t.params.arguments,t.params.name),S=e.handler,w={...s,taskStore:s.taskStore},E=g?await Promise.resolve(S.createTask(g,w)):await Promise.resolve(S.createTask(w)),D=E.task.taskId,O=E.task,k=O.pollInterval??5e3;for(;O.status!==`completed`&&O.status!==`failed`&&O.status!==`cancelled`;){await new Promise(e=>setTimeout(e,k));let e=await s.taskStore.getTask(D);if(!e)throw new McpError(ErrorCode.InternalError,`Task ${D} not found during polling`);O=e}return await s.taskStore.getTaskResult(D)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CompleteRequestSchema,async e=>{switch(e.params.ref.type){case`ref/prompt`:return assertCompleteRequestPrompt(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return assertCompleteRequestResourceTemplate(e),this.handleResourceCompletion(e,e.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let s=this._registeredPrompts[t.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} disabled`);if(!s.argsSchema)return EMPTY_COMPLETION_RESULT;let g=getObjectShape(s.argsSchema)?.[e.params.argument.name];if(!isCompletable(g))return EMPTY_COMPLETION_RESULT;let S=getCompleter(g);return S?createCompletionResult(await S(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}async handleResourceCompletion(e,t){let s=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!s){if(this._registeredResources[t.uri])return EMPTY_COMPLETION_RESULT;throw new McpError(ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let g=s.resourceTemplate.completeCallback(e.params.argument.name);return g?createCompletionResult(await g(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ListResourcesRequestSchema,async(e,t)=>{let s=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),g=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let s=await e.resourceTemplate.listCallback(t);for(let t of s.resources)g.push({...e.metadata,...t})}return{resources:[...s,...g]}}),this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(ReadResourceRequestSchema,async(e,t)=>{let s=new URL(e.params.uri),g=this._registeredResources[s.toString()];if(g){if(!g.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${s} disabled`);return g.readCallback(s,t)}for(let e of Object.values(this._registeredResourceTemplates)){let g=e.resourceTemplate.uriTemplate.match(s.toString());if(g)return e.readCallback(s,g,t)}throw new McpError(ErrorCode.InvalidParams,`Resource ${s} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?promptArgumentsFromSchema(t.argsSchema):void 0}))})),this.server.setRequestHandler(GetPromptRequestSchema,async(e,t)=>{let s=this._registeredPrompts[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(s.argsSchema){let g=await safeParseAsync(normalizeObjectSchema(s.argsSchema),e.params.arguments);if(!g.success){let t=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let S=g.data,w=s.callback;return await Promise.resolve(w(S,t))}else{let e=s.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...s){let g;typeof s[0]==`object`&&(g=s.shift());let S=s[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,t,s,g){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let S=this._createRegisteredResource(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let S=this._createRegisteredResourceTemplate(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}}_createRegisteredResource(e,t,s,g,S){let w={name:e,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==s&&(delete this._registeredResources[s],e.uri&&(this._registeredResources[e.uri]=w)),e.name!==void 0&&(w.name=e.name),e.title!==void 0&&(w.title=e.title),e.metadata!==void 0&&(w.metadata=e.metadata),e.callback!==void 0&&(w.readCallback=e.callback),e.enabled!==void 0&&(w.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[s]=w,w}_createRegisteredResourceTemplate(e,t,s,g,S){let w={resourceTemplate:s,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.template!==void 0&&(w.resourceTemplate=t.template),t.metadata!==void 0&&(w.metadata=t.metadata),t.callback!==void 0&&(w.readCallback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=w;let E=s.uriTemplate.variableNames;return Array.isArray(E)&&E.some(e=>!!s.completeCallback(e))&&this.setCompletionRequestHandler(),w}_createRegisteredPrompt(e,t,s,g,S){let w={title:t,description:s,argsSchema:g===void 0?void 0:objectFromShape(g),callback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.description!==void 0&&(w.description=t.description),t.argsSchema!==void 0&&(w.argsSchema=objectFromShape(t.argsSchema)),t.callback!==void 0&&(w.callback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=w,g&&Object.values(g).some(e=>isCompletable(e instanceof ZodOptional$1?e._def?.innerType:e))&&this.setCompletionRequestHandler(),w}_createRegisteredTool(e,t,s,g,S,w,E,D,O){validateAndWarnToolName(e);let k={title:t,description:s,inputSchema:getZodSchemaObject(g),outputSchema:getZodSchemaObject(S),annotations:w,execution:E,_meta:D,handler:O,enabled:!0,disable:()=>k.update({enabled:!1}),enable:()=>k.update({enabled:!0}),remove:()=>k.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&validateAndWarnToolName(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=k)),t.title!==void 0&&(k.title=t.title),t.description!==void 0&&(k.description=t.description),t.paramsSchema!==void 0&&(k.inputSchema=objectFromShape(t.paramsSchema)),t.outputSchema!==void 0&&(k.outputSchema=objectFromShape(t.outputSchema)),t.callback!==void 0&&(k.handler=t.callback),t.annotations!==void 0&&(k.annotations=t.annotations),t._meta!==void 0&&(k._meta=t._meta),t.enabled!==void 0&&(k.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=k,this.setToolRequestHandlers(),this.sendToolListChanged(),k}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let s,g,S,w;if(typeof t[0]==`string`&&(s=t.shift()),t.length>1){let s=t[0];if(isZodRawShapeCompat(s))g=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!isZodRawShapeCompat(t[0])&&(w=t.shift());else if(typeof s==`object`&&s){if(Object.values(s).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);w=t.shift()}}let E=t[0];return this._createRegisteredTool(e,void 0,s,g,void 0,w,{taskSupport:`forbidden`},void 0,E)}registerTool(e,t,s){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:g,description:S,inputSchema:w,outputSchema:E,annotations:D,_meta:O}=t;return this._createRegisteredTool(e,g,S,w,E,D,{taskSupport:`forbidden`},O,s)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let s;typeof t[0]==`string`&&(s=t.shift());let g;t.length>1&&(g=t.shift());let S=t[0],w=this._createRegisteredPrompt(e,void 0,s,g,S);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),w}registerPrompt(e,t,s){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:g,description:S,argsSchema:w}=t,E=this._createRegisteredPrompt(e,g,S,w,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),E}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const EMPTY_OBJECT_JSON_SCHEMA={type:`object`,properties:{}};function isZodTypeLike(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function isZodSchemaInstance(e){return`_def`in e||`_zod`in e||isZodTypeLike(e)}function isZodRawShapeCompat(e){return typeof e!=`object`||!e||isZodSchemaInstance(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(isZodTypeLike)}function getZodSchemaObject(e){if(e){if(isZodRawShapeCompat(e))return objectFromShape(e);if(!isZodSchemaInstance(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function promptArgumentsFromSchema(e){let t=getObjectShape(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:getSchemaDescription(t),required:!isSchemaOptional(t)})):[]}function getMethodValue(e){let t=getObjectShape(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let s=getLiteralValue(t);if(typeof s==`string`)return s;throw Error(`Schema method literal must be a string`)}function createCompletionResult(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};var RequestError=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},toRequestError=e=>e instanceof RequestError?e:new RequestError(e.message,{cause:e}),GlobalRequest=global.Request,Request$1=class extends GlobalRequest{constructor(e,t){typeof e==`object`&&getRequestCache in e&&(e=e[getRequestCache]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},newHeadersFromIncoming=e=>{let t=[],s=e.rawHeaders;for(let e=0;e<s.length;e+=2){let{[e]:g,[e+1]:S}=s;g.charCodeAt(0)!==58&&t.push([g,S])}return new Headers(t)},wrapBodyStream=Symbol(`wrapBodyStream`),newRequestFromIncoming=(e,t,s,g,S)=>{let w={method:e,headers:s,signal:S.signal};if(e===`TRACE`){w.method=`GET`;let e=new Request$1(t,w);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in g&&g.rawBody instanceof Buffer)w.body=new ReadableStream({start(e){e.enqueue(g.rawBody),e.close()}});else if(g[wrapBodyStream]){let e;w.body=new ReadableStream({async pull(t){try{e||=Readable$1.toWeb(g).getReader();let{done:s,value:S}=await e.read();s?t.close():t.enqueue(S)}catch(e){t.error(e)}}})}else w.body=Readable$1.toWeb(g);return new Request$1(t,w)},getRequestCache=Symbol(`getRequestCache`),requestCache=Symbol(`requestCache`),incomingKey=Symbol(`incomingKey`),urlKey=Symbol(`urlKey`),headersKey=Symbol(`headersKey`),abortControllerKey=Symbol(`abortControllerKey`),requestPrototype={get method(){return this[incomingKey].method||`GET`},get url(){return this[urlKey]},get headers(){return this[headersKey]||=newHeadersFromIncoming(this[incomingKey])},[Symbol(`getAbortController`)](){return this[getRequestCache](),this[abortControllerKey]},[getRequestCache](){return this[abortControllerKey]||=new AbortController,this[requestCache]||=newRequestFromIncoming(this.method,this[urlKey],this.headers,this[incomingKey],this[abortControllerKey])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(requestPrototype,e,{get(){return this[getRequestCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(requestPrototype,e,{value:function(){return this[getRequestCache]()[e]()}})}),Object.setPrototypeOf(requestPrototype,Request$1.prototype);var newRequest=(e,t)=>{let s=Object.create(requestPrototype);s[incomingKey]=e;let g=e.url||``;if(g[0]!==`/`&&(g.startsWith(`http://`)||g.startsWith(`https://`))){if(e instanceof Http2ServerRequest)throw new RequestError(`Absolute URL for :path is not allowed in HTTP/2`);try{s[urlKey]=new URL(g).href}catch(e){throw new RequestError(`Invalid absolute URL`,{cause:e})}return s}let S=(e instanceof Http2ServerRequest?e.authority:e.headers.host)||t;if(!S)throw new RequestError(`Missing host header`);let w;if(e instanceof Http2ServerRequest){if(w=e.scheme,!(w===`http`||w===`https`))throw new RequestError(`Unsupported scheme`)}else w=e.socket&&e.socket.encrypted?`https`:`http`;let E=new URL(`${w}://${S}${g}`);if(E.hostname.length!==S.length&&E.hostname!==S.replace(/:\d+$/,``))throw new RequestError(`Invalid host header`);return s[urlKey]=E.href,s},responseCache=Symbol(`responseCache`),getResponseCache=Symbol(`getResponseCache`),cacheKey=Symbol(`cache`),GlobalResponse=global.Response,Response2=class e{#e;#t;[getResponseCache](){return delete this[cacheKey],this[responseCache]||=new GlobalResponse(this.#e,this.#t)}constructor(t,s){let g;if(this.#e=t,s instanceof e){let e=s[responseCache];if(e){this.#t=e,this[getResponseCache]();return}else this.#t=s.#t,g=new Headers(s.#t.headers)}else this.#t=s;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[cacheKey]=[s?.status||200,t,g||s?.headers])}get headers(){let e=this[cacheKey];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[getResponseCache]().headers}get status(){return this[cacheKey]?.[0]??this[getResponseCache]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{get(){return this[getResponseCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{value:function(){return this[getResponseCache]()[e]()}})}),Object.setPrototypeOf(Response2,GlobalResponse),Object.setPrototypeOf(Response2.prototype,GlobalResponse.prototype);async function readWithoutBlocking(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function writeFromReadableStreamDefaultReader(e,t,s){let g=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,g),t.on(`error`,g),(s??e.read()).then(E,S),e.closed.finally(()=>{t.off(`close`,g),t.off(`error`,g)});function S(e){e&&t.destroy(e)}function w(){e.read().then(E,S)}function E({done:s,value:g}){try{if(s)t.end();else if(!t.write(g))t.once(`drain`,w);else return e.read().then(E,S)}catch(e){S(e)}}}function writeFromReadableStream(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:writeFromReadableStreamDefaultReader(e.getReader(),t)}var buildOutgoingHttpHeaders=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let s=[];for(let[g,S]of e)g===`set-cookie`?s.push(S):t[g]=S;return s.length>0&&(t[`set-cookie`]=s),t[`content-type`]??=`text/plain; charset=UTF-8`,t},X_ALREADY_SENT=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=crypto$1);var outgoingEnded=Symbol(`outgoingEnded`),incomingDraining=Symbol(`incomingDraining`),DRAIN_TIMEOUT_MS=500,MAX_DRAIN_BYTES=64*1024*1024,drainIncoming=e=>{let t=e;if(e.destroyed||t[incomingDraining])return;if(t[incomingDraining]=!0,e instanceof Http2ServerRequest){try{e.stream?.close?.(constants$2.NGHTTP2_NO_ERROR)}catch{}return}let s=0,g=()=>{clearTimeout(w),e.off(`data`,E),e.off(`end`,g),e.off(`error`,g)},S=()=>{g();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},w=setTimeout(S,DRAIN_TIMEOUT_MS);w.unref?.();let E=e=>{s+=e.length,s>MAX_DRAIN_BYTES&&S()};e.on(`data`,E),e.on(`end`,g),e.on(`error`,g),e.resume()},handleRequestError=()=>new Response(null,{status:400}),handleFetchError=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),handleResponseError=(e,t)=>{let s=e instanceof Error?e:Error(`unknown error`,{cause:e});s.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${s.message}`),t.destroy(s))},flushHeaders=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},responseViaCache=async(e,t)=>{let[s,g,S]=e[cacheKey],w=!1;if(!S)S={"content-type":`text/plain; charset=UTF-8`};else if(S instanceof Headers)w=S.has(`content-length`),S=buildOutgoingHttpHeaders(S);else if(Array.isArray(S)){let e=new Headers(S);w=e.has(`content-length`),S=buildOutgoingHttpHeaders(e)}else for(let e in S)if(e.length===14&&e.toLowerCase()===`content-length`){w=!0;break}w||(typeof g==`string`?S[`Content-Length`]=Buffer.byteLength(g):g instanceof Uint8Array?S[`Content-Length`]=g.byteLength:g instanceof Blob&&(S[`Content-Length`]=g.size)),t.writeHead(s,S),typeof g==`string`||g instanceof Uint8Array?t.end(g):g instanceof Blob?t.end(new Uint8Array(await g.arrayBuffer())):(flushHeaders(t),await writeFromReadableStream(g,t)?.catch(e=>handleResponseError(e,t))),t[outgoingEnded]?.()},isPromise=e=>typeof e.then==`function`,responseViaResponseObject=async(e,t,s={})=>{if(isPromise(e))if(s.errorHandler)try{e=await e}catch(t){let g=await s.errorHandler(t);if(!g)return;e=g}else e=await e.catch(handleFetchError);if(cacheKey in e)return responseViaCache(e,t);let g=buildOutgoingHttpHeaders(e.headers);if(e.body){let s=e.body.getReader(),S=[],w=!1,E;if(g[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){E||=s.read();let g=await readWithoutBlocking(E).catch(e=>{console.error(e),w=!0});if(!g){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(E=void 0,g.value&&S.push(g.value),g.done){w=!0;break}}w&&!(`content-length`in g)&&(g[`content-length`]=S.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,g),S.forEach(e=>{t.write(e)}),w?t.end():(S.length===0&&flushHeaders(t),await writeFromReadableStreamDefaultReader(s,t,E))}else g[X_ALREADY_SENT]||(t.writeHead(e.status,g),t.end());t[outgoingEnded]?.()},getRequestListener=(e,t={})=>{let s=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Request$1&&(Object.defineProperty(global,`Request`,{value:Request$1}),Object.defineProperty(global,`Response`,{value:Response2})),async(g,S)=>{let w,E;try{E=newRequest(g,t.hostname);let D=!s||g.method===`GET`||g.method===`HEAD`;if(D||(g[wrapBodyStream]=!0,g.on(`end`,()=>{D=!0}),g instanceof Http2ServerRequest&&(S[outgoingEnded]=()=>{D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),S.on(`finish`,()=>{D||drainIncoming(g)})),S.on(`close`,()=>{E[abortControllerKey]&&(g.errored?E[abortControllerKey].abort(g.errored.toString()):S.writableFinished||E[abortControllerKey].abort(`Client connection prematurely closed.`)),D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),w=e(E,{incoming:g,outgoing:S}),cacheKey in w)return responseViaCache(w,S)}catch(e){if(w)return handleResponseError(e,S);if(t.errorHandler){if(w=await t.errorHandler(E?e:toRequestError(e)),!w)return}else w=E?handleFetchError(e):handleRequestError()}try{return await responseViaResponseObject(w,S,t)}catch(e){return handleResponseError(e,S)}}},WebStandardStreamableHTTPServerTransport=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,s,g){let S={code:t,message:s};return g?.data!==void 0&&(S.data=g.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:S,id:null}),{status:e,headers:{"Content-Type":`application/json`,...g?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let s=this.validateRequestHeaders(e);if(s)return s;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,s,g){if(!this._eventStore||g<`2025-11-25`)return;let S=await this._eventStore.storeEvent(s,{}),w=`id: ${S}\ndata: \n\n`;this._retryInterval!==void 0&&(w=`id: ${S}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(w))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let s=this.validateProtocolVersion(e);if(s)return s;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),E={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(E[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{S.close()}catch{}}}),new Response(w,{headers:E})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let s={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(s[`mcp-session-id`]=this.sessionId);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{}}),E=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(S,g,t,e)){this.onerror?.(Error(`Failed replay events`));try{S.close()}catch{}}}});return this._streamMapping.set(E,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(E);try{S.close()}catch{}}}),new Response(w,{headers:s})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,s,g){try{let S=`event: message
|
|
50
|
-
`;return g&&(S+=`id: ${g}\n`),S+=`data: ${JSON.stringify(s)}\n\n`,e.enqueue(t.encode(S)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let s=e.headers.get(`accept`);if(!s?.includes(`application/json`)||!s.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let g=e.headers.get(`content-type`);if(!g||!g.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let S={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},w;if(t?.parsedBody!==void 0)w=t.parsedBody;else try{w=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let E;try{E=Array.isArray(w)?w.map(e=>JSONRPCMessageSchema.parse(e)):[JSONRPCMessageSchema.parse(w)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let D=E.some(isInitializeRequest);if(D){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(E.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!D){let t=this.validateSession(e);if(t)return t;let s=this.validateProtocolVersion(e);if(s)return s}if(!E.some(isJSONRPCRequest)){for(let e of E)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S});return new Response(null,{status:202})}let O=crypto.randomUUID(),k=E.find(e=>isInitializeRequest(e)),j=k?k.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(O,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(O)}});for(let e of E)isJSONRPCRequest(e)&&this._requestToStreamMapping.set(e.id,O);for(let e of E)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S})});let F=new TextEncoder,L,B=new ReadableStream({start:e=>{L=e},cancel:()=>{this._streamMapping.delete(O)}}),H={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(H[`mcp-session-id`]=this.sessionId);for(let e of E)isJSONRPCRequest(e)&&(this._streamMapping.set(O,{controller:L,encoder:F,cleanup:()=>{this._streamMapping.delete(O);try{L.close()}catch{}}}),this._requestToStreamMapping.set(e.id,O));await this.writePrimingEvent(L,F,O,j);for(let e of E){let s,g;isJSONRPCRequest(e)&&this._eventStore&&j>=`2025-11-25`&&(s=()=>{this.closeSSEStream(e.id)},g=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S,closeSSEStream:s,closeStandaloneSSEStream:g})}return new Response(B,{status:200,headers:H})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!SUPPORTED_PROTOCOL_VERSIONS.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(`, `)})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let s=this._streamMapping.get(t);s&&s.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let s=t?.relatedRequestId;if((isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e))&&(s=e.id),s===void 0){if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let s=this._streamMapping.get(this._standaloneSseStreamId);if(s===void 0)return;s.controller&&s.encoder&&this.writeSSEEvent(s.controller,s.encoder,e,t);return}let g=this._requestToStreamMapping.get(s);if(!g)throw Error(`No connection established for request ID: ${String(s)}`);let S=this._streamMapping.get(g);if(!this._enableJsonResponse&&S?.controller&&S?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(g,e)),this.writeSSEEvent(S.controller,S.encoder,e,t)}if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)){this._requestResponseMap.set(s,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===g).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!S)throw Error(`No connection established for request ID: ${String(s)}`);if(this._enableJsonResponse&&S.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let s=t.map(e=>this._requestResponseMap.get(e));s.length===1?S.resolveJson(new Response(JSON.stringify(s[0]),{status:200,headers:e})):S.resolveJson(new Response(JSON.stringify(s),{status:200,headers:e}))}else S.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}},StreamableHTTPServerTransport=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new WebStandardStreamableHTTPServerTransport(e),this._requestListener=getRequestListener(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,s){let g=e.auth;await getRequestListener(async e=>this._webStandardTransport.handleRequest(e,{authInfo:g,parsedBody:s}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}},Ye=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-Cr9jHdYm.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-BNwer8pK.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-0abCeF-D.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-BFVVAoBi.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-DTyG__G-.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-DrUUkxCF.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-4yR1M9Nd.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-DVQCHLUL.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-Dy5aHk72.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-CmjBk72Q.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-C7xn5Rqr.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-BN-B1xmG.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-AYS4A9o1.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-BvzND_DT.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-BR-dv_ar.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-DSe2aEO8.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-Qw6WjSl1.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-BjNsVAze.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-3AIAIJVR-DhLMPK9o.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-3AIAIJVR-DhLMPK9o.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-3AIAIJVR-DhLMPK9o.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-FOQSCCX3-CrVzsut-.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-VFTTATXJ-QHemmbCP.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-POPGKRAI-BZ_7e8H1.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-BTlvuG7X.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-DtBj3lmA.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-BXsiD7To.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-GohHdbJ4.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-BnDgUhuq.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-Ca-NmLk7.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-Bqdhxuez.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-5XaxKjVN.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-BQyKAmCr.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-D4dbwBrD.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-D-1EwjbB.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-B6_kjNM-.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-BmGbaiMe.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-CEev_e2R.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-BLgXAHZ_.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-BD6QXg_b.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-TPUOAIUQ-DuBwOGWI.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-C5R0pcfV.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-C6aDcxLl.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-CR3kfmh6.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-Da1HuQkH.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-6RSqo9Bn.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-6RSqo9Bn.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-oTDRHt3W.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-oTDRHt3W.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-jb5B-tWQ.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-aS184J1w.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-x85l8vsW.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-x85l8vsW.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-B6kVcfOw.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-DywpGlyx.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-DywpGlyx.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-ODXZBPLY-JpgGenzN.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-BhIrz6He.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-Ci7M3Pfx.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-RM_vdvCh.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-C-x_VGtG.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-D_oS0IDg.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-CRnH51wk.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-BBSGpJq5.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-5T3UU5KE-D7ekHiOy.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-0GZIz1Ci.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-D6-7B21n.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-BYVtIJOS.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-ZIGAJ4YS-DzKHvjCj.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-B5yiu2Qr.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-jdvqGfQj.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-B-Xo178d.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-BEQ9sZmi.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-CVVAGatl.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-_Mgzu6ty.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-BYZOEzSd.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-kzAFjO_Y.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-kzAFjO_Y.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-kzAFjO_Y.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Ye.push({name:`tar`,load:async()=>(await import(`./tar-ANUBEFJY-HbwMpE1g.mjs`)).tarCommand}),Ye.push({name:`yq`,load:async()=>(await import(`./yq-MJMAR36V-Cgql6fKu.mjs`)).yqCommand}),Ye.push({name:`xan`,load:async()=>(await import(`./xan-BXDXYEIB-qijhj_cA.mjs`)).xanCommand}),Ye.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-56UMWEY3-Cjvsy5Oo.mjs`)).sqlite3Command}));var Zt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Zt.push({name:`python3`,load:async()=>(await import(`./python3-AUFTPCU6-1PPUn2I7.mjs`)).python3Command}),Zt.push({name:`python`,load:async()=>(await import(`./python3-AUFTPCU6-1PPUn2I7.mjs`)).pythonCommand}));var qt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(qt.push({name:`js-exec`,load:async()=>(await import(`./js-exec-M6UR76J5-Bo7dCQVP.mjs`)).jsExecCommand}),qt.push({name:`node`,load:async()=>(await import(`./js-exec-M6UR76J5-Bo7dCQVP.mjs`)).nodeStubCommand}));var sn=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-CdMFK7aW.mjs`)).curlCommand}],tn=new Map;function Gt(e){return{name:e.name,async execute(t,s){let g=tn.get(e.name);if(g||(g=await _$1.runTrustedAsync(()=>e.load()),tn.set(e.name,g)),s.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:g}=await import(`./flag-coverage-QT4N2Z44-C38ybzz7.mjs`);g(s.coverage,e.name,t)}return g.execute(t,s)}}}function rn(e){return(e?Ye.filter(t=>e.includes(t.name)):Ye).map(Gt)}function nn(){return sn.map(Gt)}function on(){return Zt.map(Gt)}function an(){return qt.map(Gt)}function ln(e){return`load`in e&&typeof e.load==`function`}function cn(e){let t=null;return{name:e.name,trusted:!0,async execute(s,g){return t||=await e.load(),t.execute(s,g)}}}var ot=new TextEncoder;function Qi(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&`content`in e}var Le=class{data=new Map;constructor(e){if(this.data.set(`/`,{type:`directory`,mode:493,mtime:new Date}),e)for(let[t,s]of Object.entries(e))typeof s==`function`?this.writeFileLazy(t,s):Qi(s)?this.writeFileSync(t,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(t,s)}ensureParentDirs(e){let t=m$1(e);t!==`/`&&(this.data.has(t)||(this.ensureParentDirs(t),this.data.set(t,{type:`directory`,mode:493,mtime:new Date})))}writeFileSync(e,t,s,g){h$1(e,`write`);let S=c$1(e);this.ensureParentDirs(S);let w=o(t,l$1(s));this.data.set(S,{type:`file`,content:w,mode:g?.mode??420,mtime:g?.mtime??new Date})}writeFileLazy(e,t,s){h$1(e,`write`);let g=c$1(e);this.ensureParentDirs(g),this.data.set(g,{type:`file`,lazy:t,mode:s?.mode??420,mtime:s?.mtime??new Date})}async materializeLazy(e,t){let s=await t.lazy(),g={type:`file`,content:typeof s==`string`?ot.encode(s):s,mode:t.mode,mtime:t.mtime};return this.data.set(e,g),g}async readFile(e,t){return h$2(await this.readFileBuffer(e),l$1(t))}async readFileBuffer(e){h$1(e,`open`);let t=this.resolvePathWithSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(s.type!==`file`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(`lazy`in s){let e=await this.materializeLazy(t,s);return e.content instanceof Uint8Array?e.content:ot.encode(e.content)}return s.content instanceof Uint8Array?s.content:ot.encode(s.content)}async writeFile(e,t,s){this.writeFileSync(e,t,s)}async appendFile(e,t,s){h$1(e,`append`);let g=c$1(e),S=this.data.get(g);if(S&&S.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let w=o(t,l$1(s));if(S?.type===`file`){let e=S;`lazy`in e&&(e=await this.materializeLazy(g,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:ot.encode(`content`in e?e.content:``),s=new Uint8Array(t.length+w.length);s.set(t),s.set(w,t.length),this.data.set(g,{type:`file`,content:s,mode:e.mode,mtime:new Date})}else this.writeFileSync(e,t,s)}async exists(e){if(e.includes(`\0`))return!1;try{let t=this.resolvePathWithSymlinks(e);return this.data.has(t)}catch{return!1}}async stat(e){h$1(e,`stat`);let t=this.resolvePathWithSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, stat '${e}'`);s.type===`file`&&`lazy`in s&&(s=await this.materializeLazy(t,s));let g=0;return s.type===`file`&&`content`in s&&s.content&&(g=s.content instanceof Uint8Array?s.content.length:ot.encode(s.content).length),{isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:!1,mode:s.mode,size:g,mtime:s.mtime||new Date}}async lstat(e){h$1(e,`lstat`);let t=this.resolveIntermediateSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);if(s.type===`symlink`)return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:s.mode,size:s.target.length,mtime:s.mtime||new Date};s.type===`file`&&`lazy`in s&&(s=await this.materializeLazy(t,s));let g=0;return s.type===`file`&&`content`in s&&s.content&&(g=s.content instanceof Uint8Array?s.content.length:ot.encode(s.content).length),{isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:!1,mode:s.mode,size:g,mtime:s.mtime||new Date}}resolveIntermediateSymlinks(e){let t=c$1(e);if(t===`/`)return`/`;let s=t.slice(1).split(`/`);if(s.length<=1)return t;let g=``,S=new Set;for(let t=0;t<s.length-1;t++){let w=s[t];g=`${g}/${w}`;let E=this.data.get(g),D=0,O=40;for(;E&&E.type===`symlink`&&D<40;){if(S.has(g))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);S.add(g),g=v$1(g,E.target),E=this.data.get(g),D++}if(D>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${g}/${s[s.length-1]}`}resolvePathWithSymlinks(e){let t=c$1(e);if(t===`/`)return`/`;let s=t.slice(1).split(`/`),g=``,S=new Set;for(let t of s){g=`${g}/${t}`;let s=this.data.get(g),w=0,E=40;for(;s&&s.type===`symlink`&&w<40;){if(S.has(g))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);S.add(g),g=v$1(g,s.target),s=this.data.get(g),w++}if(w>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return g}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){h$1(e,`mkdir`);let s=c$1(e);if(this.data.has(s)){if(this.data.get(s)?.type===`file`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(!t?.recursive)throw Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let g=m$1(s);if(g!==`/`&&!this.data.has(g))if(t?.recursive)this.mkdirSync(g,{recursive:!0});else throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(s,{type:`directory`,mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){h$1(e,`scandir`);let t=c$1(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let g=new Set;for(;s&&s.type===`symlink`;){if(g.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);g.add(t),t=v$1(t,s.target),s=this.data.get(t)}if(!s)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(s.type!==`directory`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);let S=t===`/`?`/`:`${t}/`,w=new Map;for(let[e,s]of this.data.entries())if(e!==t&&e.startsWith(S)){let t=e.slice(S.length),g=t.split(`/`)[0];g&&!t.includes(`/`,g.length)&&!w.has(g)&&w.set(g,{name:g,isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:s.type===`symlink`})}return Array.from(w.values()).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}async rm(e,t){h$1(e,`rm`);let s=c$1(e),g=this.data.get(s);if(!g){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(g.type===`directory`){let g=await this.readdir(s);if(g.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of g){let g=p$1(s,e);await this.rm(g,t)}}}this.data.delete(s)}async cp(e,t,s){h$1(e,`cp`),h$1(t,`cp`);let g=c$1(e),S=c$1(t),w=this.data.get(g);if(!w)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(w.type===`file`)if(this.ensureParentDirs(S),`content`in w){let e=w.content instanceof Uint8Array?new Uint8Array(w.content):w.content;this.data.set(S,{...w,content:e})}else this.data.set(S,{...w});else if(w.type===`symlink`)this.ensureParentDirs(S),this.data.set(S,{...w});else if(w.type===`directory`){if(!s?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(S,{recursive:!0});let t=await this.readdir(g);for(let e of t){let t=p$1(g,e),w=p$1(S,e);await this.cp(t,w,s)}}}async mv(e,t){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,t){return y(e,t)}async chmod(e,t){h$1(e,`chmod`);let s=c$1(e),g=this.data.get(s);if(!g)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);g.mode=t}async symlink(e,t){h$1(t,`symlink`);let s=c$1(t);if(this.data.has(s))throw Error(`EEXIST: file already exists, symlink '${t}'`);this.ensureParentDirs(s),this.data.set(s,{type:`symlink`,target:e,mode:511,mtime:new Date})}async link(e,t){h$1(e,`link`),h$1(t,`link`);let s=c$1(e),g=c$1(t),S=this.data.get(s);if(!S)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(S.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(g))throw Error(`EEXIST: file already exists, link '${t}'`);let w=S;`lazy`in w&&(w=await this.materializeLazy(s,w)),this.ensureParentDirs(g),this.data.set(g,{type:`file`,content:w.content,mode:w.mode,mtime:w.mtime})}async readlink(e){h$1(e,`readlink`);let t=c$1(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(s.type!==`symlink`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);return s.target}async realpath(e){h$1(e,`realpath`);let t=this.resolvePathWithSymlinks(e);if(!this.data.has(t))throw Error(`ENOENT: no such file or directory, realpath '${e}'`);return t}async utimes(e,t,s){h$1(e,`utimes`);let g=c$1(e),S=this.resolvePathWithSymlinks(g),w=this.data.get(S);if(!w)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);w.mtime=s}};function Ji(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function eo(e,t){e.mkdirSync(`/bin`,{recursive:!0}),e.mkdirSync(`/usr/bin`,{recursive:!0}),t&&(e.mkdirSync(`/home/user`,{recursive:!0}),e.mkdirSync(`/tmp`,{recursive:!0}))}function to(e){e.mkdirSync(`/dev`,{recursive:!0}),e.writeFileSync(`/dev/null`,``),e.writeFileSync(`/dev/zero`,new Uint8Array),e.writeFileSync(`/dev/stdin`,``),e.writeFileSync(`/dev/stdout`,``),e.writeFileSync(`/dev/stderr`,``)}function so(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${xi$1}
|
|
50
|
+
`;return g&&(S+=`id: ${g}\n`),S+=`data: ${JSON.stringify(s)}\n\n`,e.enqueue(t.encode(S)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let s=e.headers.get(`accept`);if(!s?.includes(`application/json`)||!s.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let g=e.headers.get(`content-type`);if(!g||!g.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let S={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},w;if(t?.parsedBody!==void 0)w=t.parsedBody;else try{w=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let E;try{E=Array.isArray(w)?w.map(e=>JSONRPCMessageSchema.parse(e)):[JSONRPCMessageSchema.parse(w)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let D=E.some(isInitializeRequest);if(D){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(E.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!D){let t=this.validateSession(e);if(t)return t;let s=this.validateProtocolVersion(e);if(s)return s}if(!E.some(isJSONRPCRequest)){for(let e of E)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S});return new Response(null,{status:202})}let O=crypto.randomUUID(),k=E.find(e=>isInitializeRequest(e)),j=k?k.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(O,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(O)}});for(let e of E)isJSONRPCRequest(e)&&this._requestToStreamMapping.set(e.id,O);for(let e of E)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S})});let F=new TextEncoder,L,B=new ReadableStream({start:e=>{L=e},cancel:()=>{this._streamMapping.delete(O)}}),H={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(H[`mcp-session-id`]=this.sessionId);for(let e of E)isJSONRPCRequest(e)&&(this._streamMapping.set(O,{controller:L,encoder:F,cleanup:()=>{this._streamMapping.delete(O);try{L.close()}catch{}}}),this._requestToStreamMapping.set(e.id,O));await this.writePrimingEvent(L,F,O,j);for(let e of E){let s,g;isJSONRPCRequest(e)&&this._eventStore&&j>=`2025-11-25`&&(s=()=>{this.closeSSEStream(e.id)},g=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S,closeSSEStream:s,closeStandaloneSSEStream:g})}return new Response(B,{status:200,headers:H})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!SUPPORTED_PROTOCOL_VERSIONS.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(`, `)})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let s=this._streamMapping.get(t);s&&s.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let s=t?.relatedRequestId;if((isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e))&&(s=e.id),s===void 0){if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let s=this._streamMapping.get(this._standaloneSseStreamId);if(s===void 0)return;s.controller&&s.encoder&&this.writeSSEEvent(s.controller,s.encoder,e,t);return}let g=this._requestToStreamMapping.get(s);if(!g)throw Error(`No connection established for request ID: ${String(s)}`);let S=this._streamMapping.get(g);if(!this._enableJsonResponse&&S?.controller&&S?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(g,e)),this.writeSSEEvent(S.controller,S.encoder,e,t)}if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)){this._requestResponseMap.set(s,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===g).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!S)throw Error(`No connection established for request ID: ${String(s)}`);if(this._enableJsonResponse&&S.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let s=t.map(e=>this._requestResponseMap.get(e));s.length===1?S.resolveJson(new Response(JSON.stringify(s[0]),{status:200,headers:e})):S.resolveJson(new Response(JSON.stringify(s),{status:200,headers:e}))}else S.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}},StreamableHTTPServerTransport=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new WebStandardStreamableHTTPServerTransport(e),this._requestListener=getRequestListener(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,s){let g=e.auth;await getRequestListener(async e=>this._webStandardTransport.handleRequest(e,{authInfo:g,parsedBody:s}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}},Ye=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-Cr9jHdYm.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-BNwer8pK.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-0abCeF-D.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-BFVVAoBi.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-DTyG__G-.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-DrUUkxCF.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-4yR1M9Nd.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-DVQCHLUL.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-Dy5aHk72.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-CmjBk72Q.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-C7xn5Rqr.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-BN-B1xmG.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-AYS4A9o1.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-BvzND_DT.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-BR-dv_ar.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-DSe2aEO8.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-Qw6WjSl1.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-BjNsVAze.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-3AIAIJVR-DhLMPK9o.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-3AIAIJVR-DhLMPK9o.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-3AIAIJVR-DhLMPK9o.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-FOQSCCX3-CrVzsut-.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-VFTTATXJ-QHemmbCP.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-POPGKRAI-BZ_7e8H1.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-BTlvuG7X.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-DtBj3lmA.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-BXsiD7To.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-GohHdbJ4.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-BnDgUhuq.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-Ca-NmLk7.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-Bqdhxuez.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-5XaxKjVN.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-BQyKAmCr.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-D4dbwBrD.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-D-1EwjbB.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-B6_kjNM-.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-BmGbaiMe.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-CEev_e2R.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-BLgXAHZ_.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-BD6QXg_b.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-TPUOAIUQ-DuBwOGWI.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-C5R0pcfV.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-C6aDcxLl.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-CR3kfmh6.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-Da1HuQkH.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-6RSqo9Bn.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-6RSqo9Bn.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-oTDRHt3W.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-oTDRHt3W.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-jb5B-tWQ.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-aS184J1w.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-x85l8vsW.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-x85l8vsW.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-B6kVcfOw.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-DywpGlyx.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-DywpGlyx.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-ODXZBPLY-JpgGenzN.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-BhIrz6He.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-DTuHZGVW.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-RM_vdvCh.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-C-x_VGtG.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-D_oS0IDg.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-CRnH51wk.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-BBSGpJq5.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-5T3UU5KE-D7ekHiOy.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-0GZIz1Ci.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-D6-7B21n.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-BYVtIJOS.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-ZIGAJ4YS-DzKHvjCj.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-B5yiu2Qr.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-jdvqGfQj.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-B-Xo178d.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-BEQ9sZmi.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-CVVAGatl.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-_Mgzu6ty.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-BYZOEzSd.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-kzAFjO_Y.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-kzAFjO_Y.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-kzAFjO_Y.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Ye.push({name:`tar`,load:async()=>(await import(`./tar-ANUBEFJY-HbwMpE1g.mjs`)).tarCommand}),Ye.push({name:`yq`,load:async()=>(await import(`./yq-MJMAR36V-Cgql6fKu.mjs`)).yqCommand}),Ye.push({name:`xan`,load:async()=>(await import(`./xan-BXDXYEIB-qijhj_cA.mjs`)).xanCommand}),Ye.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-56UMWEY3-Cjvsy5Oo.mjs`)).sqlite3Command}));var Zt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Zt.push({name:`python3`,load:async()=>(await import(`./python3-AUFTPCU6-1PPUn2I7.mjs`)).python3Command}),Zt.push({name:`python`,load:async()=>(await import(`./python3-AUFTPCU6-1PPUn2I7.mjs`)).pythonCommand}));var qt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(qt.push({name:`js-exec`,load:async()=>(await import(`./js-exec-M6UR76J5-Bo7dCQVP.mjs`)).jsExecCommand}),qt.push({name:`node`,load:async()=>(await import(`./js-exec-M6UR76J5-Bo7dCQVP.mjs`)).nodeStubCommand}));var sn=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-CdMFK7aW.mjs`)).curlCommand}],tn=new Map;function Gt(e){return{name:e.name,async execute(t,s){let g=tn.get(e.name);if(g||(g=await _$1.runTrustedAsync(()=>e.load()),tn.set(e.name,g)),s.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:g}=await import(`./flag-coverage-QT4N2Z44-DmAL_7h5.mjs`);g(s.coverage,e.name,t)}return g.execute(t,s)}}}function rn(e){return(e?Ye.filter(t=>e.includes(t.name)):Ye).map(Gt)}function nn(){return sn.map(Gt)}function on(){return Zt.map(Gt)}function an(){return qt.map(Gt)}function ln(e){return`load`in e&&typeof e.load==`function`}function cn(e){let t=null;return{name:e.name,trusted:!0,async execute(s,g){return t||=await e.load(),t.execute(s,g)}}}var ot=new TextEncoder;function Qi(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&`content`in e}var Le=class{data=new Map;constructor(e){if(this.data.set(`/`,{type:`directory`,mode:493,mtime:new Date}),e)for(let[t,s]of Object.entries(e))typeof s==`function`?this.writeFileLazy(t,s):Qi(s)?this.writeFileSync(t,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(t,s)}ensureParentDirs(e){let t=m$1(e);t!==`/`&&(this.data.has(t)||(this.ensureParentDirs(t),this.data.set(t,{type:`directory`,mode:493,mtime:new Date})))}writeFileSync(e,t,s,g){h$1(e,`write`);let S=c$1(e);this.ensureParentDirs(S);let w=o(t,l$1(s));this.data.set(S,{type:`file`,content:w,mode:g?.mode??420,mtime:g?.mtime??new Date})}writeFileLazy(e,t,s){h$1(e,`write`);let g=c$1(e);this.ensureParentDirs(g),this.data.set(g,{type:`file`,lazy:t,mode:s?.mode??420,mtime:s?.mtime??new Date})}async materializeLazy(e,t){let s=await t.lazy(),g={type:`file`,content:typeof s==`string`?ot.encode(s):s,mode:t.mode,mtime:t.mtime};return this.data.set(e,g),g}async readFile(e,t){return h$2(await this.readFileBuffer(e),l$1(t))}async readFileBuffer(e){h$1(e,`open`);let t=this.resolvePathWithSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(s.type!==`file`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(`lazy`in s){let e=await this.materializeLazy(t,s);return e.content instanceof Uint8Array?e.content:ot.encode(e.content)}return s.content instanceof Uint8Array?s.content:ot.encode(s.content)}async writeFile(e,t,s){this.writeFileSync(e,t,s)}async appendFile(e,t,s){h$1(e,`append`);let g=c$1(e),S=this.data.get(g);if(S&&S.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let w=o(t,l$1(s));if(S?.type===`file`){let e=S;`lazy`in e&&(e=await this.materializeLazy(g,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:ot.encode(`content`in e?e.content:``),s=new Uint8Array(t.length+w.length);s.set(t),s.set(w,t.length),this.data.set(g,{type:`file`,content:s,mode:e.mode,mtime:new Date})}else this.writeFileSync(e,t,s)}async exists(e){if(e.includes(`\0`))return!1;try{let t=this.resolvePathWithSymlinks(e);return this.data.has(t)}catch{return!1}}async stat(e){h$1(e,`stat`);let t=this.resolvePathWithSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, stat '${e}'`);s.type===`file`&&`lazy`in s&&(s=await this.materializeLazy(t,s));let g=0;return s.type===`file`&&`content`in s&&s.content&&(g=s.content instanceof Uint8Array?s.content.length:ot.encode(s.content).length),{isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:!1,mode:s.mode,size:g,mtime:s.mtime||new Date}}async lstat(e){h$1(e,`lstat`);let t=this.resolveIntermediateSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);if(s.type===`symlink`)return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:s.mode,size:s.target.length,mtime:s.mtime||new Date};s.type===`file`&&`lazy`in s&&(s=await this.materializeLazy(t,s));let g=0;return s.type===`file`&&`content`in s&&s.content&&(g=s.content instanceof Uint8Array?s.content.length:ot.encode(s.content).length),{isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:!1,mode:s.mode,size:g,mtime:s.mtime||new Date}}resolveIntermediateSymlinks(e){let t=c$1(e);if(t===`/`)return`/`;let s=t.slice(1).split(`/`);if(s.length<=1)return t;let g=``,S=new Set;for(let t=0;t<s.length-1;t++){let w=s[t];g=`${g}/${w}`;let E=this.data.get(g),D=0,O=40;for(;E&&E.type===`symlink`&&D<40;){if(S.has(g))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);S.add(g),g=v$1(g,E.target),E=this.data.get(g),D++}if(D>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${g}/${s[s.length-1]}`}resolvePathWithSymlinks(e){let t=c$1(e);if(t===`/`)return`/`;let s=t.slice(1).split(`/`),g=``,S=new Set;for(let t of s){g=`${g}/${t}`;let s=this.data.get(g),w=0,E=40;for(;s&&s.type===`symlink`&&w<40;){if(S.has(g))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);S.add(g),g=v$1(g,s.target),s=this.data.get(g),w++}if(w>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return g}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){h$1(e,`mkdir`);let s=c$1(e);if(this.data.has(s)){if(this.data.get(s)?.type===`file`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(!t?.recursive)throw Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let g=m$1(s);if(g!==`/`&&!this.data.has(g))if(t?.recursive)this.mkdirSync(g,{recursive:!0});else throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(s,{type:`directory`,mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){h$1(e,`scandir`);let t=c$1(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let g=new Set;for(;s&&s.type===`symlink`;){if(g.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);g.add(t),t=v$1(t,s.target),s=this.data.get(t)}if(!s)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(s.type!==`directory`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);let S=t===`/`?`/`:`${t}/`,w=new Map;for(let[e,s]of this.data.entries())if(e!==t&&e.startsWith(S)){let t=e.slice(S.length),g=t.split(`/`)[0];g&&!t.includes(`/`,g.length)&&!w.has(g)&&w.set(g,{name:g,isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:s.type===`symlink`})}return Array.from(w.values()).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}async rm(e,t){h$1(e,`rm`);let s=c$1(e),g=this.data.get(s);if(!g){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(g.type===`directory`){let g=await this.readdir(s);if(g.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of g){let g=p$1(s,e);await this.rm(g,t)}}}this.data.delete(s)}async cp(e,t,s){h$1(e,`cp`),h$1(t,`cp`);let g=c$1(e),S=c$1(t),w=this.data.get(g);if(!w)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(w.type===`file`)if(this.ensureParentDirs(S),`content`in w){let e=w.content instanceof Uint8Array?new Uint8Array(w.content):w.content;this.data.set(S,{...w,content:e})}else this.data.set(S,{...w});else if(w.type===`symlink`)this.ensureParentDirs(S),this.data.set(S,{...w});else if(w.type===`directory`){if(!s?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(S,{recursive:!0});let t=await this.readdir(g);for(let e of t){let t=p$1(g,e),w=p$1(S,e);await this.cp(t,w,s)}}}async mv(e,t){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,t){return y(e,t)}async chmod(e,t){h$1(e,`chmod`);let s=c$1(e),g=this.data.get(s);if(!g)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);g.mode=t}async symlink(e,t){h$1(t,`symlink`);let s=c$1(t);if(this.data.has(s))throw Error(`EEXIST: file already exists, symlink '${t}'`);this.ensureParentDirs(s),this.data.set(s,{type:`symlink`,target:e,mode:511,mtime:new Date})}async link(e,t){h$1(e,`link`),h$1(t,`link`);let s=c$1(e),g=c$1(t),S=this.data.get(s);if(!S)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(S.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(g))throw Error(`EEXIST: file already exists, link '${t}'`);let w=S;`lazy`in w&&(w=await this.materializeLazy(s,w)),this.ensureParentDirs(g),this.data.set(g,{type:`file`,content:w.content,mode:w.mode,mtime:w.mtime})}async readlink(e){h$1(e,`readlink`);let t=c$1(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(s.type!==`symlink`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);return s.target}async realpath(e){h$1(e,`realpath`);let t=this.resolvePathWithSymlinks(e);if(!this.data.has(t))throw Error(`ENOENT: no such file or directory, realpath '${e}'`);return t}async utimes(e,t,s){h$1(e,`utimes`);let g=c$1(e),S=this.resolvePathWithSymlinks(g),w=this.data.get(S);if(!w)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);w.mtime=s}};function Ji(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function eo(e,t){e.mkdirSync(`/bin`,{recursive:!0}),e.mkdirSync(`/usr/bin`,{recursive:!0}),t&&(e.mkdirSync(`/home/user`,{recursive:!0}),e.mkdirSync(`/tmp`,{recursive:!0}))}function to(e){e.mkdirSync(`/dev`,{recursive:!0}),e.writeFileSync(`/dev/null`,``),e.writeFileSync(`/dev/zero`,new Uint8Array),e.writeFileSync(`/dev/stdin`,``),e.writeFileSync(`/dev/stdout`,``),e.writeFileSync(`/dev/stderr`,``)}function so(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${xi$1}
|
|
51
51
|
`),e.writeFileSync(`/proc/self/exe`,`/bin/bash`),e.writeFileSync(`/proc/self/cmdline`,`bash\0`),e.writeFileSync(`/proc/self/comm`,`bash
|
|
52
52
|
`),e.writeFileLazy?e.writeFileLazy(`/proc/self/status`,()=>_i$1(t)):e.writeFileSync(`/proc/self/status`,_i$1(t)),e.writeFileSync(`/proc/self/fd/0`,`/dev/stdin`),e.writeFileSync(`/proc/self/fd/1`,`/dev/stdout`),e.writeFileSync(`/proc/self/fd/2`,`/dev/stderr`)}function un(e,t,s={pid:1,ppid:0,uid:1e3,gid:1e3}){Ji(e)&&(eo(e,t),to(e),so(e,s))}var ro=[`allexport`,`errexit`,`noglob`,`noclobber`,`noexec`,`nounset`,`pipefail`,`posix`,`verbose`,`xtrace`],no=[`braceexpand`,`hashall`,`interactive-comments`];function Ls(e){let t=[],s=[...no.map(e=>({name:e,enabled:!0})),...ro.map(t=>({name:t,enabled:e[t]}))].sort((e,t)=>e.name.localeCompare(t.name));for(let e of s)e.enabled&&t.push(e.name);return t.join(`:`)}function lt(e){e.state.env.set(`SHELLOPTS`,Ls(e.state.options))}var io=[`dotglob`,`expand_aliases`,`extglob`,`failglob`,`globskipdots`,`globstar`,`lastpipe`,`nocaseglob`,`nocasematch`,`nullglob`,`xpg_echo`];function Fs(e){let t=[];for(let s of io)e[s]&&t.push(s);return t.join(`:`)}function Ms(e){e.state.env.set(`BASHOPTS`,Fs(e.state.shoptOptions))}var oo=`BASH_ALIAS_`;function fn(e){return e.parts.length===1?e.parts[0].type===`Literal`:!1}function dn(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type===`Literal`?t.value:null}function hn(e,t){return e.env.get(`${oo}${t}`)}function Ws(e,t,s){if(!t.name||!fn(t.name))return t;let g=dn(t.name);if(!g)return t;let S=hn(e,g);if(!S||s.has(g))return t;try{s.add(g);let w=new V,E=S,D=S.endsWith(` `);if(!D)for(let e of t.args){let t=mn(e);E+=` ${t}`}let O;try{O=w.parse(E)}catch(e){if(e instanceof G$1)throw e;return t}if(O.statements.length!==1||O.statements[0].pipelines.length!==1||O.statements[0].pipelines[0].commands.length!==1)return pn(t,S);let k=O.statements[0].pipelines[0].commands[0];if(k.type!==`SimpleCommand`)return pn(t,S);let j={...k,assignments:[...t.assignments,...k.assignments],redirections:[...k.redirections,...t.redirections],line:t.line};if(D&&t.args.length>0&&(j={...j,args:[...j.args,...t.args]},j.args.length>0)){let t=j.args[0];if(fn(t)){let g=dn(t);if(g&&hn(e,g)){let g={type:`SimpleCommand`,name:t,args:j.args.slice(1),assignments:[],redirections:[]},S=Ws(e,g,s);S!==g&&(j={...j,name:S.name,args:[...S.args]})}}}return j}catch(e){throw s.delete(g),e}}function pn(e,t){let s=t;for(let t of e.args){let e=mn(t);s+=` ${e}`}let g=new V;return{type:`SimpleCommand`,name:g.parseWordFromString(`eval`,!1,!1),args:[g.parseWordFromString(`'${s.replace(/'/g,`'\\''`)}'`,!1,!1)],assignments:e.assignments,redirections:e.redirections,line:e.line}}function mn(e){let t=``;for(let s of e.parts)switch(s.type){case`Literal`:t+=s.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,`\\$1`);break;case`SingleQuoted`:t+=`'${s.value}'`;break;case`DoubleQuoted`:t+=`"${s.parts.map(e=>e.type===`Literal`?e.value:`$${e.type}`).join(``)}"`;break;case`ParameterExpansion`:t+=`\${${s.parameter}}`;break;case`CommandSubstitution`:t+=`$(...)`;break;case`ArithmeticExpansion`:t+=`$((${s.expression}))`;break;case`Glob`:t+=s.pattern;break;default:break}return t}async function yn(e,t){let s=t.parts.map(e=>e.type===`Literal`?e.value:`\0`).join(``),g=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!g||!s.endsWith(`)`))return null;let S=g[1],w=[],E=!1,D=``,O=!1;for(let s of t.parts)if(s.type===`Literal`){let e=s.value;if(!E){let t=e.indexOf(`=(`);t!==-1&&(E=!0,e=e.slice(t+2))}if(E){e.endsWith(`)`)&&(e=e.slice(0,-1));let t=e.split(/(\s+)/);for(let e of t)/^\s+$/.test(e)?(D||O)&&(w.push(D),D=``,O=!1):e&&(D+=e)}}else if(E)if(s.type===`BraceExpansion`)if(/^\[.+\]=/.test(D))D+=En$1({type:`Word`,parts:[s]});else{(D||O)&&(w.push(D),D=``,O=!1);let t=await wl(e,{type:`Word`,parts:[s]});w.push(...t.values)}else{(s.type===`SingleQuoted`||s.type===`DoubleQuoted`||s.type===`Escaped`)&&(O=!0);let t=await Pt$1(e,{type:`Word`,parts:[s]});D+=t}return(D||O)&&w.push(D),`${S}=(${w.map(e=>/^\[.+\]=/.test(e)?e:e===``?`''`:/[\s"'\\$`!*?[\]{}|&;<>()]/.test(e)&&!e.startsWith(`'`)&&!e.startsWith(`"`)?`'${e.replace(/'/g,`'\\''`)}'`:e).join(` `)})`}async function gn(e,t){let s=-1,g=-1,S=!1;for(let e=0;e<t.parts.length;e++){let w=t.parts[e];if(w.type===`Literal`){let t=w.value.indexOf(`+=`);if(t!==-1){let E=w.value.slice(0,t);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(E)){s=e,g=t,S=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(E)){s=e,g=t,S=!0;break}}let E=w.value.indexOf(`=`);if(E!==-1&&(E===0||w.value[E-1]!==`+`)){let t=w.value.slice(0,E);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(t)){s=e,g=E;break}}}}if(s===-1)return null;let w=t.parts.slice(0,s),E=t.parts[s];if(E.type!==`Literal`)return null;let D=S?2:1,O=E.value.slice(0,g),k=E.value.slice(g+D),j=t.parts.slice(s+1),F=``;for(let t of w)F+=await Pt$1(e,{type:`Word`,parts:[t]});F+=O;let L={type:`Word`,parts:k===``?j:[{type:`Literal`,value:k},...j]},B=L.parts.length>0?await Pt$1(e,L):``;return`${F}${S?`+=`:`=`}${B}`}var ao=[`tar`,`yq`,`xan`,`sqlite3`,`python3`,`python`];function wn(e){return ao.includes(e)}var W=Object.freeze({stdout:``,stderr:``,exitCode:0});function z(e=``){return{stdout:e,stderr:``,exitCode:0}}function A(e,t=1){return{stdout:``,stderr:e,exitCode:t}}function _(e,t,s){return{stdout:e,stderr:t,exitCode:s}}function Q(e){return{stdout:``,stderr:``,exitCode:e?0:1}}function Ne(e,t,s=``,g=``){throw new b(e,t,s,g)}function le(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new b(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,`file_descriptors`)}function zs(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new f;return W}if(t.length>1)throw new d(1,``,`bash: break: too many arguments
|
|
53
53
|
`);let s=1;if(t.length>0){let e=Number.parseInt(t[0],10);if(Number.isNaN(e)||e<1)throw new d(128,``,`bash: break: ${t[0]}: numeric argument required
|
|
@@ -783,7 +783,7 @@ caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?
|
|
|
783
783
|
`).trim()),S=[]):S.push(e)}if(S.length>0){let e=S.join(`
|
|
784
784
|
`).trim();e&&g.push(e)}return g}function reconcile(e){if(isSystemDoc(e.docName)||isConfigDoc(e.docName))return{kind:`noop`};let{base:t,ours:s,theirs:g}=e;if(containsConflictMarkers(g))return{kind:`refused`,reason:`conflict-markers`};if(g===t)return{kind:`noop`};if(s===t)return{kind:`clean`,newContent:g};let S=splitMarkdownBlocks(t),w=splitMarkdownBlocks(s),E=splitMarkdownBlocks(g);return(S.length+1)*(w.length+1)>4e6||(S.length+1)*(E.length+1)>4e6?{kind:`refused`,reason:`too-large`}:mergeBlocks(S,w,E)}function mergeBlocks(e,t,s){let g=computeEditOps(e,t),S=computeEditOps(e,s),w=[],E=[];for(let t=0;t<e.length;t++){let s=e[t],D=g.get(t),O=S.get(t),k=D?.insertsBefore??[],j=O?.insertsBefore??[];w.push(...k,...j);let F=D?.action??`keep`,L=O?.action??`keep`;if(F===`keep`&&L===`keep`)w.push(s);else if(F===`keep`&&L!==`keep`)L===`modify`&&O?.newContent!==void 0&&w.push(O.newContent);else if(F!==`keep`&&L===`keep`)F===`modify`&&D?.newContent!==void 0&&w.push(D.newContent);else{let e=F===`modify`?D?.newContent:null,g=L===`modify`?O?.newContent:null;e===g||E.push({blockIndex:t,base:s,ours:e??``,theirs:g??``}),e!=null&&w.push(e)}}let D=g.get(e.length),O=S.get(e.length);D?.insertsBefore&&w.push(...D.insertsBefore),O?.insertsBefore&&w.push(...O.insertsBefore);let k=w.length>0?`${w.join(`
|
|
785
785
|
|
|
786
|
-
`)}\n`:``;return E.length>0?{kind:`conflicts`,newContent:k,conflicts:E}:{kind:`merged`,newContent:k,mergedBlocks:w.length}}function computeEditOps(e,t){let s=new Map,g=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)s.set(t,{action:`keep`,insertsBefore:[]});let S=new Set,w=new Set;for(let[e,t]of g)S.add(e),w.add(t);let E=-1;for(let D=0;D<e.length;D++)if(S.has(D)){let e=g.find(e=>e[0]===D)?.[1]??-1,S=[];for(let s=E+1;s<e;s++)w.has(s)||S.push(t[s]);let O=s.get(D);O&&(O.insertsBefore=S),E=e}else{let e=g.find(e=>e[0]>D),S=e?e[1]:t.length,O=[];for(let e=E+1;e<S;e++)w.has(e)||O.push(e);if(O.length>0){let e=O[0];w.add(e);let g=s.get(D);g&&(g.action=`modify`,g.newContent=t[e])}else{let e=s.get(D);e&&(e.action=`delete`)}}let D=[];for(let e=E+1;e<t.length;e++)w.has(e)||D.push(t[e]);let O=s.get(e.length);return O&&(O.insertsBefore=D),s}function longestCommonSubsequence(e,t){let s=e.length,g=t.length,S=g+1,w=new Uint32Array((s+1)*S);for(let E=1;E<=s;E++){let s=E*S,D=(E-1)*S;for(let S=1;S<=g;S++)if(e[E-1]===t[S-1])w[s+S]=w[D+(S-1)]+1;else{let e=w[D+S],t=w[s+(S-1)];w[s+S]=e>t?e:t}}let E=[],D=s,O=g;for(;D>0&&O>0;)e[D-1]===t[O-1]?(E.push([D-1,O-1]),D--,O--):w[(D-1)*S+O]>=w[D*S+(O-1)]?D--:O--;return E.reverse()}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let s=writeTracker.get(e)??[];s.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,s)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,s]of writeTracker){let g=s.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);g.length===0?writeTracker.delete(t):g.length!==s.length&&writeTracker.set(t,g)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function eventEscapesContentDir(e,t){let s;try{s=lstatSync(e)}catch(t){let s=t.code;return s===`ENOENT`?!1:(console.warn(`[file-watcher] lstat failed for escape check on ${e} (${s}), dropping event`),!0)}if(!s.isSymbolicLink())return!1;let g;try{g=realpathSync(e)}catch(t){let s=t.code;return s!==`ENOENT`&&s!==`ELOOP`&&console.warn(`[file-watcher] realpath failed for escape check on ${e} (${s}), dropping event`),!0}return!isWithinContentDir(g,t)}function pathToDocName(e,t){return stripDocExtension(relative(t,e))}function contentRelativePath(e,t){let s=relative(e,t).replaceAll(`\\`,`/`);return!s||s===`.`||s===`..`||s.startsWith(`../`)?null:s}function upsertFolderIndexEntry(e,t,s,g,S=s){let w=contentRelativePath(t,s);return w?(e.set(w,{size:0,modified:g.mtime.toISOString(),canonicalPath:S,inode:Number(g.ino)}),w):null}function removeFolderIndexEntries(e,t){let s=!1;for(let g of e.keys())(g===t||g.startsWith(`${t}/`))&&(e.delete(g),s=!0);return s}function extractDocExtension(e){let t=extname(e);if(t===``)return null;let s=t.toLowerCase();return s===`.mdx`||s===`.md`?t:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,s,g){let S=[],w=[],E=[];for(let g of e)if(isSupportedDocFile(g.path)){if(s){let e=relative(t,g.path);if(s.isExcluded(e))continue}switch(g.type){case`delete`:S.push(g);break;case`create`:lastKnownHash.has(g.path)?E.push(g):w.push(g);break;case`update`:E.push(g);break}}let D=new Map,O=new Map;for(let e of w)try{D.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of E)try{O.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function k(e){let s=pathToDocName(e,t);if(!g)return s;let S=null;try{S=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),g.has(s)&&g.delete(s),s}if(!S.isSymbolicLink())return g.has(s)&&g.delete(s),s;let w;try{w=realpathSync(e)}catch(t){let S=t.code;return S!==`ENOENT`&&S!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),g.delete(s),s}if(!isWithinContentDir(w,t))return g.delete(s),s;let E=pathToDocName(w,t);return E===s?s:(g.set(s,E),E)}let j=[],F=new Set,L=new Set;for(let e of S){let t=removeLastKnownHash(e.path);if(t)for(let s of w){if(F.has(s.path))continue;let g=D.get(s.path);if(g===void 0)continue;let S=contentHash(g);if(S===t){F.add(s.path),L.add(e.path),updateLastKnownHash(s.path,S),j.push({kind:`rename`,oldPath:e.path,newPath:s.path,oldDocName:k(e.path),newDocName:k(s.path),content:g});break}}}for(let e of S)L.has(e.path)||(removeLastKnownHash(e.path),j.push({kind:`delete`,path:e.path,docName:k(e.path)}));for(let e of w){if(F.has(e.path))continue;let t=D.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`create`,path:e.path,docName:k(e.path),content:t})}for(let e of E){let t=O.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`update`,path:e.path,docName:k(e.path),content:t})}return j}function isSelfWrite(e,t){let s=writeTracker.get(e);if(!s)return!1;let g=s.findIndex(e=>e.hash===t);return g<0?!1:(s.splice(g,1),s.length===0&&writeTracker.delete(e),!0)}function seedLastKnownHashes(e,t,s,g,S,w,E){let D=E??new Set;try{let E=readdirSync(e,{withFileTypes:!0});for(let O of E){let E=join(e,O.name),k;try{k=lstatSync(E)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${E}, skipping:`,e);continue}if(k.isSymbolicLink()){let e;try{e=realpathSync(E)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${E}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${E}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${E} → ${e}, skipping`);continue}try{let k=statSync(e);if(D.has(k.ino)){if(k.isFile()&&isSupportedDocFile(O.name)){let s=pathToDocName(E,t),S=pathToDocName(e,t);w.set(s,S);let D=g.get(S);D&&!D.aliases.includes(s)&&D.aliases.push(s)}continue}if(D.add(k.ino),k.isDirectory()){let O=contentRelativePath(t,E);if(s&&(!O||s.isDirExcluded(O)))continue;upsertFolderIndexEntry(S,t,E,k,e),seedLastKnownHashes(e,t,s,g,S,w,D)}else if(k.isFile()&&isSupportedDocFile(O.name)){if(s){let g=relative(t,e);if(s.isExcluded(g))continue}let S=pathToDocName(E,t),D=pathToDocName(e,t);w.set(S,D);try{let t=contentHash(readFileSync(e,`utf-8`));lastKnownHash.set(e,t);let s=extractDocExtension(e);if(s){let e=registerDocExtension(D,s);if(e.shadowed&&(console.warn(`[file-watcher] docName "${D}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(D,{size:k.size,modified:k.mtime.toISOString(),canonicalPath:e,inode:k.ino,aliases:[S]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(k.isDirectory()){let e=contentRelativePath(t,E);if(s&&(!e||s.isDirExcluded(e)))continue;upsertFolderIndexEntry(S,t,E,k),seedLastKnownHashes(E,t,s,g,S,w,D)}else if(k.isFile()&&isSupportedDocFile(O.name)){if(D.has(k.ino))continue;if(D.add(k.ino),s){let e=relative(t,E);if(s.isExcluded(e))continue}try{let e=readFileSync(E,`utf-8`);lastKnownHash.set(E,contentHash(e));let s=pathToDocName(E,t),S=extractDocExtension(E);if(S){let e=registerDocExtension(s,S);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(s,{size:k.size,modified:k.mtime.toISOString(),canonicalPath:E,inode:k.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${E}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${E}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)return;let s=e.kind===`rename`?e.newDocName:e.docName;if(!(isSystemDoc(s)||isConfigDoc(s)))switch(e.kind){case`create`:case`update`:case`conflict`:{let s=e.docName,g=t.get(s),S=extractDocExtension(e.path);S&®isterDocExtension(s,S),t.set(s,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:g?.inode??0,aliases:g?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,s]of t){let t=s.aliases.indexOf(e.docName);if(t!==-1){s.aliases.splice(t,1);break}}break;case`rename`:{let s=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let g=extractDocExtension(e.newPath);g&®isterDocExtension(e.newDocName,g),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:s?.canonicalPath??e.newPath,inode:s?.inode??0,aliases:s?.aliases??[]});break}default:assertNeverDiskEvent(e)}}function updateFolderIndexFromRawEvents(e,t,s,g){let S=[];for(let w of e){let e=contentRelativePath(t,w.path);if(!e)continue;if(w.type===`delete`){removeFolderIndexEntries(g,e)&&S.push({kind:`folder-delete`,path:w.path,relativePath:e});continue}let E;try{E=lstatSync(w.path)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder lstat failed for ${w.path} (${t})`);continue}let D=null,O=w.path;if(E.isDirectory())D=E;else if(E.isSymbolicLink())try{if(O=realpathSync(w.path),!isWithinContentDir(O,t))continue;let e=statSync(O);e.isDirectory()&&(D=e)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder symlink resolve failed for ${w.path} (${t})`),D=null}if(!D||s?.isDirExcluded(e))continue;let k=g.has(e);upsertFolderIndexEntry(g,t,w.path,D,O),k||(S.push({kind:`folder-create`,path:w.path,relativePath:e}),scanForUntrackedSubfolders(O,t,s,g,S))}return S}function scanForUntrackedSubfolders(e,t,s,g,S){let w=[e];for(;w.length>0;){let e=w.shift();if(e===void 0)continue;let E;try{E=readdirSync(e,{withFileTypes:!0})}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] folder rescan readdir failed for ${e} (${s})`);continue}for(let D of E){if(!D.isDirectory())continue;let E=join(e,D.name),O=contentRelativePath(t,E);if(!O||s?.isDirExcluded(O))continue;let k;try{k=lstatSync(E)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder rescan lstat failed for ${E} (${t})`);continue}k.isDirectory()&&(g.has(O)||(upsertFolderIndexEntry(g,t,E,k),S.push({kind:`folder-create`,path:E,relativePath:O})),w.push(E))}}}async function handleRawEvents(e,t,s,g,S,w,E){let D=e.filter(e=>eventEscapesContentDir(e.path,t)?(console.warn(`[file-watcher] Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),O=D.filter(e=>isSupportedDocFile(e.path)),k=D.filter(e=>isSupportedAssetFile(e.path,LINKABLE_ASSET_EXTENSIONS)),j=updateFolderIndexFromRawEvents(D,t,s,S);if(O.length===0&&k.length===0&&j.length===0)return;let F=O.length>0?await classifyEvents(O,t,s,E):[];for(let e of F){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let s=contentHash(e.content),g=e.path;try{g=realpathSync(e.path)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${s})`)}t=isSelfWrite(g,s)}else if(e.kind===`rename`){let s=contentHash(e.content),g=e.newPath;try{g=realpathSync(e.newPath)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${s})`)}t=isSelfWrite(g,s)}if(updateFileIndex(e,g),s&&!t)switch(e.kind){case`create`:s.incrementMdDir(dirname(e.docName));break;case`delete`:s.decrementMdDir(dirname(e.docName));break;case`rename`:s.decrementMdDir(dirname(e.oldDocName)),s.incrementMdDir(dirname(e.newDocName));break;case`update`:case`conflict`:break;default:assertNeverDiskEvent(e)}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let S=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(S),"disk.path.role":classifyFsPath(S)}},async()=>w(e))}for(let e of j)getLogger(`file-watcher`).debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1}),await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(e.path),"disk.path.role":classifyFsPath(e.path)}},async()=>w(e));for(let e of k){if(s){let g=relative(t,e.path);if(s.isExcluded(g))continue}let g=relative(t,e.path);await w(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:g}:{kind:`asset-create`,path:e.path,relativePath:g})}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,s,g,S,w){let E;try{E=await import(`@parcel/watcher`)}catch(e){return getLogger(`file-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[file-watcher] @parcel/watcher import failed; falling back to chokidar`),null}try{let D=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await E.subscribe(e,async(E,D)=>{if(E){console.error(`[file-watcher]`,E);return}try{await handleRawEvents(D.map(e=>({type:e.type,path:e.path})),e,t,s,g,S,w)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},D)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,s,g,S,w){let{watch:E}=await import(`./chokidar-BDjANGpQ.mjs`),D=E(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(s,g)=>{let S=relative(e,s);return S===``||S===`.`?!1:g?.isDirectory()?t.isDirExcluded(S):t.isExcluded(S)}:void 0});D.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let O=50,k=[],j=null;function F(E,D){k.push({type:E,path:D}),j||=setTimeout(()=>{let E=k;k=[],j=null,handleRawEvents(E,e,t,s,g,S,w).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return D.on(`add`,e=>F(`create`,e)),D.on(`change`,e=>F(`update`,e)),D.on(`unlink`,e=>F(`delete`,e)),D.on(`addDir`,e=>F(`create`,e)),D.on(`unlinkDir`,e=>F(`delete`,e)),{unsubscribe:()=>(j&&(clearTimeout(j),j=null,k=[]),D.close())}}async function startWatcher(e,t,s){let g;try{g=realpathSync(e)}catch{g=e}let S=new Map,w=new Map,E=new Map;seedLastKnownHashes(g,g,s,S,w,E);let D=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),O,k;try{let e=await startParcelWatcher(g,s,S,w,t,E);e?(O=e,k=`parcel`):(O=await startChokidarWatcher(g,s,S,w,t,E),k=`chokidar`)}catch(e){throw clearInterval(D),e}let j=O.unsubscribe.bind(O);return getLogger(`file-watcher`).info({contentDir:g,backend:k},`watching for external .md changes`),{async unsubscribe(){return clearInterval(D),writeTracker.clear(),lastKnownHash.clear(),j()},getFileIndex(){return S},getFolderIndex(){return w},getAliasMap(){return E},pruneFileIndexNowExcluded(){if(!s)return 0;let e=0;for(let[t,w]of S){let E=relative(g,w.canonicalPath);s.isExcluded(E)&&(S.delete(t),e++)}return e},pruneFolderIndexNowExcluded(){if(!s)return 0;let e=0;for(let t of w.keys())s.isDirExcluded(t)&&(w.delete(t),e++);return e},rescanFromDisk(){seedLastKnownHashes(g,g,s,S,w,E)}}}function reconcileFileIndexAfterFilterRebuild(e){if(!e)return{prunedFiles:0,prunedFolders:0};let t=e.pruneFileIndexNowExcluded(),s=e.pruneFolderIndexNowExcluded();return e.rescanFromDisk(),{prunedFiles:t,prunedFolders:s}}function normalizeBody(e){let{body:t}=stripFrontmatter(e);return normalizeBridge(t).trim()}function isWhitespace(e){return e===` `||e===`
|
|
786
|
+
`)}\n`:``;return E.length>0?{kind:`conflicts`,newContent:k,conflicts:E}:{kind:`merged`,newContent:k,mergedBlocks:w.length}}function computeEditOps(e,t){let s=new Map,g=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)s.set(t,{action:`keep`,insertsBefore:[]});let S=new Set,w=new Set;for(let[e,t]of g)S.add(e),w.add(t);let E=-1;for(let D=0;D<e.length;D++)if(S.has(D)){let e=g.find(e=>e[0]===D)?.[1]??-1,S=[];for(let s=E+1;s<e;s++)w.has(s)||S.push(t[s]);let O=s.get(D);O&&(O.insertsBefore=S),E=e}else{let e=g.find(e=>e[0]>D),S=e?e[1]:t.length,O=[];for(let e=E+1;e<S;e++)w.has(e)||O.push(e);if(O.length>0){let e=O[0];w.add(e);let g=s.get(D);g&&(g.action=`modify`,g.newContent=t[e])}else{let e=s.get(D);e&&(e.action=`delete`)}}let D=[];for(let e=E+1;e<t.length;e++)w.has(e)||D.push(t[e]);let O=s.get(e.length);return O&&(O.insertsBefore=D),s}function longestCommonSubsequence(e,t){let s=e.length,g=t.length,S=g+1,w=new Uint32Array((s+1)*S);for(let E=1;E<=s;E++){let s=E*S,D=(E-1)*S;for(let S=1;S<=g;S++)if(e[E-1]===t[S-1])w[s+S]=w[D+(S-1)]+1;else{let e=w[D+S],t=w[s+(S-1)];w[s+S]=e>t?e:t}}let E=[],D=s,O=g;for(;D>0&&O>0;)e[D-1]===t[O-1]?(E.push([D-1,O-1]),D--,O--):w[(D-1)*S+O]>=w[D*S+(O-1)]?D--:O--;return E.reverse()}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let s=writeTracker.get(e)??[];s.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,s)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,s]of writeTracker){let g=s.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);g.length===0?writeTracker.delete(t):g.length!==s.length&&writeTracker.set(t,g)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function eventEscapesContentDir(e,t){let s;try{s=lstatSync(e)}catch(t){let s=t.code;return s===`ENOENT`?!1:(console.warn(`[file-watcher] lstat failed for escape check on ${e} (${s}), dropping event`),!0)}if(!s.isSymbolicLink())return!1;let g;try{g=realpathSync(e)}catch(t){let s=t.code;return s!==`ENOENT`&&s!==`ELOOP`&&console.warn(`[file-watcher] realpath failed for escape check on ${e} (${s}), dropping event`),!0}return!isWithinContentDir(g,t)}function pathToDocName(e,t){return stripDocExtension(relative(t,e))}function contentRelativePath(e,t){let s=relative(e,t).replaceAll(`\\`,`/`);return!s||s===`.`||s===`..`||s.startsWith(`../`)?null:s}function upsertFolderIndexEntry(e,t,s,g,S=s){let w=contentRelativePath(t,s);return w?(e.set(w,{size:0,modified:g.mtime.toISOString(),canonicalPath:S,inode:Number(g.ino)}),w):null}function removeFolderIndexEntries(e,t){let s=!1;for(let g of e.keys())(g===t||g.startsWith(`${t}/`))&&(e.delete(g),s=!0);return s}function extractDocExtension(e){let t=extname(e);if(t===``)return null;let s=t.toLowerCase();return s===`.mdx`||s===`.md`?t:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,s,g){let S=[],w=[],E=[];for(let g of e)if(isSupportedDocFile(g.path)){if(s){let e=relative(t,g.path);if(s.isExcluded(e))continue}switch(g.type){case`delete`:S.push(g);break;case`create`:lastKnownHash.has(g.path)?E.push(g):w.push(g);break;case`update`:E.push(g);break}}let D=new Map,O=new Map;for(let e of w)try{D.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of E)try{O.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function k(e){let s=pathToDocName(e,t);if(!g)return s;let S=null;try{S=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),g.has(s)&&g.delete(s),s}if(!S.isSymbolicLink())return g.has(s)&&g.delete(s),s;let w;try{w=realpathSync(e)}catch(t){let S=t.code;return S!==`ENOENT`&&S!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),g.delete(s),s}if(!isWithinContentDir(w,t))return g.delete(s),s;let E=pathToDocName(w,t);return E===s?s:(g.set(s,E),E)}let j=[],F=new Set,L=new Set;for(let e of S){let t=removeLastKnownHash(e.path);if(t)for(let s of w){if(F.has(s.path))continue;let g=D.get(s.path);if(g===void 0)continue;let S=contentHash(g);if(S===t){F.add(s.path),L.add(e.path),updateLastKnownHash(s.path,S),j.push({kind:`rename`,oldPath:e.path,newPath:s.path,oldDocName:k(e.path),newDocName:k(s.path),content:g});break}}}for(let e of S)L.has(e.path)||(removeLastKnownHash(e.path),j.push({kind:`delete`,path:e.path,docName:k(e.path)}));for(let e of w){if(F.has(e.path))continue;let t=D.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`create`,path:e.path,docName:k(e.path),content:t})}for(let e of E){let t=O.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`update`,path:e.path,docName:k(e.path),content:t})}return j}function isSelfWrite(e,t){let s=writeTracker.get(e);if(!s)return!1;let g=s.findIndex(e=>e.hash===t);return g<0?!1:(s.splice(g,1),s.length===0&&writeTracker.delete(e),!0)}async function seedLastKnownHashes(e,t,s,g,S,w,E){let D=E??new Set;try{let E=await readdir(e,{withFileTypes:!0});for(let O of E){let E=join(e,O.name),k;try{k=await lstat(E)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${E}, skipping:`,e);continue}if(k.isSymbolicLink()){let e;try{e=await realpath(E)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${E}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${E}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${E} → ${e}, skipping`);continue}try{let k=await stat$1(e);if(D.has(k.ino)){if(k.isFile()&&isSupportedDocFile(O.name)){let s=pathToDocName(E,t),S=pathToDocName(e,t);w.set(s,S);let D=g.get(S);D&&!D.aliases.includes(s)&&D.aliases.push(s)}continue}if(D.add(k.ino),k.isDirectory()){let O=contentRelativePath(t,E);if(s&&(!O||s.isDirExcluded(O)))continue;upsertFolderIndexEntry(S,t,E,k,e),await seedLastKnownHashes(e,t,s,g,S,w,D)}else if(k.isFile()&&isSupportedDocFile(O.name)){if(s){let g=relative(t,e);if(s.isExcluded(g))continue}let S=pathToDocName(E,t),D=pathToDocName(e,t);w.set(S,D);try{let t=contentHash(await readFile$1(e,`utf-8`));lastKnownHash.set(e,t);let s=extractDocExtension(e);if(s){let e=registerDocExtension(D,s);if(e.shadowed&&(console.warn(`[file-watcher] docName "${D}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(D,{size:k.size,modified:k.mtime.toISOString(),canonicalPath:e,inode:k.ino,aliases:[S]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(k.isDirectory()){let e=contentRelativePath(t,E);if(s&&(!e||s.isDirExcluded(e)))continue;upsertFolderIndexEntry(S,t,E,k),await seedLastKnownHashes(E,t,s,g,S,w,D)}else if(k.isFile()&&isSupportedDocFile(O.name)){if(D.has(k.ino))continue;if(D.add(k.ino),s){let e=relative(t,E);if(s.isExcluded(e))continue}try{let e=await readFile$1(E,`utf-8`);lastKnownHash.set(E,contentHash(e));let s=pathToDocName(E,t),S=extractDocExtension(E);if(S){let e=registerDocExtension(s,S);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(s,{size:k.size,modified:k.mtime.toISOString(),canonicalPath:E,inode:k.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${E}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${E}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)return;let s=e.kind===`rename`?e.newDocName:e.docName;if(!(isSystemDoc(s)||isConfigDoc(s)))switch(e.kind){case`create`:case`update`:case`conflict`:{let s=e.docName,g=t.get(s),S=extractDocExtension(e.path);S&®isterDocExtension(s,S),t.set(s,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:g?.inode??0,aliases:g?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,s]of t){let t=s.aliases.indexOf(e.docName);if(t!==-1){s.aliases.splice(t,1);break}}break;case`rename`:{let s=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let g=extractDocExtension(e.newPath);g&®isterDocExtension(e.newDocName,g),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:s?.canonicalPath??e.newPath,inode:s?.inode??0,aliases:s?.aliases??[]});break}default:assertNeverDiskEvent(e)}}function updateFolderIndexFromRawEvents(e,t,s,g){let S=[];for(let w of e){let e=contentRelativePath(t,w.path);if(!e)continue;if(w.type===`delete`){removeFolderIndexEntries(g,e)&&S.push({kind:`folder-delete`,path:w.path,relativePath:e});continue}let E;try{E=lstatSync(w.path)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder lstat failed for ${w.path} (${t})`);continue}let D=null,O=w.path;if(E.isDirectory())D=E;else if(E.isSymbolicLink())try{if(O=realpathSync(w.path),!isWithinContentDir(O,t))continue;let e=statSync(O);e.isDirectory()&&(D=e)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder symlink resolve failed for ${w.path} (${t})`),D=null}if(!D||s?.isDirExcluded(e))continue;let k=g.has(e);upsertFolderIndexEntry(g,t,w.path,D,O),k||(S.push({kind:`folder-create`,path:w.path,relativePath:e}),scanForUntrackedSubfolders(O,t,s,g,S))}return S}function scanForUntrackedSubfolders(e,t,s,g,S){let w=[e];for(;w.length>0;){let e=w.shift();if(e===void 0)continue;let E;try{E=readdirSync(e,{withFileTypes:!0})}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] folder rescan readdir failed for ${e} (${s})`);continue}for(let D of E){if(!D.isDirectory())continue;let E=join(e,D.name),O=contentRelativePath(t,E);if(!O||s?.isDirExcluded(O))continue;let k;try{k=lstatSync(E)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder rescan lstat failed for ${E} (${t})`);continue}k.isDirectory()&&(g.has(O)||(upsertFolderIndexEntry(g,t,E,k),S.push({kind:`folder-create`,path:E,relativePath:O})),w.push(E))}}}async function handleRawEvents(e,t,s,g,S,w,E){let D=e.filter(e=>eventEscapesContentDir(e.path,t)?(console.warn(`[file-watcher] Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),O=D.filter(e=>isSupportedDocFile(e.path)),k=D.filter(e=>isSupportedAssetFile(e.path,LINKABLE_ASSET_EXTENSIONS)),j=updateFolderIndexFromRawEvents(D,t,s,S);if(O.length===0&&k.length===0&&j.length===0)return;let F=O.length>0?await classifyEvents(O,t,s,E):[];for(let e of F){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let s=contentHash(e.content),g=e.path;try{g=realpathSync(e.path)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${s})`)}t=isSelfWrite(g,s)}else if(e.kind===`rename`){let s=contentHash(e.content),g=e.newPath;try{g=realpathSync(e.newPath)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${s})`)}t=isSelfWrite(g,s)}if(updateFileIndex(e,g),s&&!t)switch(e.kind){case`create`:s.incrementMdDir(dirname(e.docName));break;case`delete`:s.decrementMdDir(dirname(e.docName));break;case`rename`:s.decrementMdDir(dirname(e.oldDocName)),s.incrementMdDir(dirname(e.newDocName));break;case`update`:case`conflict`:break;default:assertNeverDiskEvent(e)}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let S=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(S),"disk.path.role":classifyFsPath(S)}},async()=>w(e))}for(let e of j)getLogger(`file-watcher`).debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1}),await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(e.path),"disk.path.role":classifyFsPath(e.path)}},async()=>w(e));for(let e of k){if(s){let g=relative(t,e.path);if(s.isExcluded(g))continue}let g=relative(t,e.path);await w(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:g}:{kind:`asset-create`,path:e.path,relativePath:g})}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,s,g,S,w){let E;try{E=await import(`@parcel/watcher`)}catch(e){return getLogger(`file-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[file-watcher] @parcel/watcher import failed; falling back to chokidar`),null}try{let D=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await E.subscribe(e,async(E,D)=>{if(E){console.error(`[file-watcher]`,E);return}try{await handleRawEvents(D.map(e=>({type:e.type,path:e.path})),e,t,s,g,S,w)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},D)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,s,g,S,w){let{watch:E}=await import(`./chokidar-BDjANGpQ.mjs`),D=E(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(s,g)=>{let S=relative(e,s);return S===``||S===`.`?!1:g?.isDirectory()?t.isDirExcluded(S):t.isExcluded(S)}:void 0});D.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let O=50,k=[],j=null;function F(E,D){k.push({type:E,path:D}),j||=setTimeout(()=>{let E=k;k=[],j=null,handleRawEvents(E,e,t,s,g,S,w).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return D.on(`add`,e=>F(`create`,e)),D.on(`change`,e=>F(`update`,e)),D.on(`unlink`,e=>F(`delete`,e)),D.on(`addDir`,e=>F(`create`,e)),D.on(`unlinkDir`,e=>F(`delete`,e)),{unsubscribe:()=>(j&&(clearTimeout(j),j=null,k=[]),D.close())}}async function startWatcher(e,t,s){let g;try{g=realpathSync(e)}catch{g=e}let S=new Map,w=new Map,E=new Map;await seedLastKnownHashes(g,g,s,S,w,E);let D=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),O,k;try{let e=await startParcelWatcher(g,s,S,w,t,E);e?(O=e,k=`parcel`):(O=await startChokidarWatcher(g,s,S,w,t,E),k=`chokidar`)}catch(e){throw clearInterval(D),e}let j=O.unsubscribe.bind(O);return getLogger(`file-watcher`).info({contentDir:g,backend:k},`watching for external .md changes`),{async unsubscribe(){return clearInterval(D),writeTracker.clear(),lastKnownHash.clear(),j()},getFileIndex(){return S},getFolderIndex(){return w},getAliasMap(){return E},pruneFileIndexNowExcluded(){if(!s)return 0;let e=0;for(let[t,w]of S){let E=relative(g,w.canonicalPath);s.isExcluded(E)&&(S.delete(t),e++)}return e},pruneFolderIndexNowExcluded(){if(!s)return 0;let e=0;for(let t of w.keys())s.isDirExcluded(t)&&(w.delete(t),e++);return e},rescanFromDisk(){return seedLastKnownHashes(g,g,s,S,w,E)}}}async function reconcileFileIndexAfterFilterRebuild(e){if(!e)return{prunedFiles:0,prunedFolders:0};let t=e.pruneFileIndexNowExcluded(),s=e.pruneFolderIndexNowExcluded();return await e.rescanFromDisk(),{prunedFiles:t,prunedFolders:s}}function normalizeBody(e){let{body:t}=stripFrontmatter(e);return normalizeBridge(t).trim()}function isWhitespace(e){return e===` `||e===`
|
|
787
787
|
`||e===` `||e===`\r`}function classifyDuplication(e,t){let s=normalizeBody(t);if(s.length===0)return{kind:`allow`,reason:`empty-base`};let g=normalizeBody(e);if(g===s)return{kind:`allow`,reason:`identical`};if(g.length<s.length*2)return{kind:`allow`,reason:`too-short`};let S=0,w=0;for(;S<g.length;){if(g.slice(S,S+s.length)!==s)return{kind:`allow`,reason:`not-integer-multiple`};for(S+=s.length,w++;S<g.length&&isWhitespace(g[S]??``);)S++}return w>=2?{kind:`block`,reason:`structural-duplication`,copies:w}:{kind:`allow`,reason:`single-copy`}}let _liveEntriesGauge=null;function liveEntriesGauge(){return _liveEntriesGauge||=getMeter().createUpDownCounter(`rename.log_entries_total`,{description:`Live rename-log entry count after each append / GC pass`}),_liveEntriesGauge}let _gcDroppedCounter=null;function gcDroppedCounter(){return _gcDroppedCounter||=getMeter().createCounter(`rename.log_gc_dropped_total`,{description:`Cumulative count of rename-log entries dropped by reachability GC`}),_gcDroppedCounter}const RENAME_LOG_HARD_CAP_BYTES=5*1024*1024,RENAME_LOG_MAX_LINE_BYTES=4*1024,RENAME_LOG_FILENAME=`renames.jsonl`;function createEmptyIndex(){return{byTo:new Map,byFrom:new Map}}function renameLogPath(e){return resolve(e,RENAME_LOG_FILENAME)}function validateEntry(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||typeof t.from!=`string`||t.from.length===0||typeof t.to!=`string`||t.to.length===0||t.from===t.to||typeof t.at!=`string`||t.at.length===0||typeof t.commitSha!=`string`||t.commitSha!==``&&!/^[0-9a-f]{40}$/.test(t.commitSha)||typeof t.branch!=`string`||t.branch.length===0||typeof t.groupId!=`string`||t.groupId.length===0||t.kind!==`file`&&t.kind!==`folder`||t.actor===null||typeof t.actor!=`object`)return null;let s=t.actor;return typeof s.writerId!=`string`||s.writerId.length===0||typeof s.displayName!=`string`?null:{v:1,from:t.from,to:t.to,at:t.at,commitSha:t.commitSha,branch:t.branch,groupId:t.groupId,kind:t.kind,actor:{writerId:s.writerId,displayName:s.displayName}}}function removeFromByFrom(e,t){let s=e.byFrom.get(t.from);if(!s)return;let g=s.filter(e=>e!==t);g.length===0?e.byFrom.delete(t.from):e.byFrom.set(t.from,g)}function indexRemove(e,t){e.byTo.delete(t.to),removeFromByFrom(e,t)}function indexInsert(e,t){let s=e.byTo.get(t.to);s&&removeFromByFrom(e,s),e.byTo.set(t.to,t);let g=e.byFrom.get(t.from);g?g.push(t):e.byFrom.set(t.from,[t])}function loadRenameLogIndex(e){let t=createEmptyIndex(),s=renameLogPath(e);if(!existsSync(s))return t;let g;try{g=readFileSync(s,`utf-8`)}catch(e){return console.warn(`[rename-log] WARN: failed to read ${s}, treating as empty:`,e),t}if(g.length===0)return t;let S=g.split(`
|
|
788
788
|
`),w=S[S.length-1];w!==``&&console.warn(`[rename-log] WARN: trailing line missing newline (${w.length} bytes); dropped`);let E=S.slice(0,-1);for(let e=0;e<E.length;e++){let s=E[e];if(s.length===0)continue;let g;try{g=JSON.parse(s)}catch(t){let g=s.slice(0,80),S=t.message;console.warn(`[rename-log] WARN: corrupt entry at line ${e+1} skipped (${S}): ${g}${s.length>80?`…`:``}`);continue}let S=validateEntry(g);if(!S){console.warn(`[rename-log] WARN: corrupt entry at line ${e+1} skipped`);continue}indexInsert(t,S)}return t.byTo.size>0&&liveEntriesGauge().add(t.byTo.size),t}function appendRenameLogEntry(e,t,s,g){let S=validateEntry(t);if(!S)throw Error(`[rename-log] refusing to append malformed entry`);let w=`${JSON.stringify(S)}\n`;if(Buffer.byteLength(w,`utf-8`)>RENAME_LOG_MAX_LINE_BYTES)throw Error(`[rename-log] entry exceeds max line size (${RENAME_LOG_MAX_LINE_BYTES} bytes)`);let E=renameLogPath(e),D=!1;if(existsSync(E))try{let e=statSync(E).size;e>5242880&&(D=!0,console.warn(`[rename-log] WARN: file size ${e} exceeds hard cap ${RENAME_LOG_HARD_CAP_BYTES}; forcing GC sweep`))}catch{}tracedAppendFileSync(E,w,{flag:`a`}),indexInsert(s,S),liveEntriesGauge().add(1),D&&g&&scheduleHardCapGc(g,s)}const gcPending=new Set;function scheduleHardCapGc(e,t){queueMicrotask(()=>{gcRenameLog(e,t).catch(e=>{console.warn(`[rename-log] WARN: hard-cap forced GC failed:`,e)})})}let _moduleIndex=null;function setRenameLogIndex(e,t){_moduleIndex={shadowDir:e,index:t}}function getOrLoadRenameLogIndex(e){if(_moduleIndex&&_moduleIndex.shadowDir===e)return _moduleIndex.index;let t=loadRenameLogIndex(e);return _moduleIndex={shadowDir:e,index:t},t}function serializeIndexToString(e){let t=[];for(let s of e.byTo.values())t.push(JSON.stringify(s));return t.length>0?`${t.join(`
|
|
789
789
|
`)}\n`:``}function parseGitTimeoutMs(){let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4}function expandPredecessors(e,t,s){let g=[],S=new Set,w=e,E=0;for(;;){if(g.length>=100){console.warn(`[rename-log] WARN: predecessor chain depth exceeded 100 while expanding "${e}"; truncating`);break}if(S.has(w)){console.warn(`[rename-log] WARN: cycle detected at "${w}" while expanding predecessors of "${e}"; truncating`);break}S.add(w);let D=s.byTo.get(w);if(!D||D.branch!==t)break;if(D.commitSha===``){E+=1;break}g.push({path:D.from,renameCommit:D.commitSha}),w=D.from}return g.reverse(),g.push({path:e,renameCommit:null}),{chain:g,skipped:E}}function createAncestorShaSetCache(){return new Map}function createSeedsCache(){return new Map}async function buildSeeds(e,t,s,g){return withSpan(`rename.buildSeeds`,void 0,async S=>{if(g){let e=g.get(`${s}:${t}`);if(e)return S.setAttribute(`rename.seeds_count`,e.length),S.setAttribute(`rename.cache_hit`,!0),e}let w=shadowGit(e),E;try{E=(await w.raw(`show`,`-s`,`--format=%aI`,t)).trim()}catch(e){return console.warn(`[rename-log] WARN: buildSeeds: git show failed for rename commit ${t}; falling back to single-seed:`,e),S.setAttribute(`rename.seeds_count`,1),[t]}if(!E)return S.setAttribute(`rename.seeds_count`,1),[t];let D;try{D=await w.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(creatordate:iso8601-strict) %(objectname)`,`refs/checkpoints/${s}/`)}catch(e){return console.warn(`[rename-log] WARN: buildSeeds: for-each-ref failed for branch ${s}; falling back to single-seed:`,e),S.setAttribute(`rename.seeds_count`,1),[t]}let O=[t];for(let e of D.split(`
|
|
@@ -846,7 +846,7 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
|
|
|
846
846
|
`,`
|
|
847
847
|
`).replaceAll(`\r`,`
|
|
848
848
|
`).split(`
|
|
849
|
-
`),g=[],S=null;for(let e of s)if(S)isFenceClose$1(e,S)&&(S=null);else{let s=matchFence$1(e);if(s)S=s;else{let s=extractExternalMarkdownLinksFromLine(e,t);g.push(...s.occurrences.map(({url:e,label:t,start:g,end:S})=>({url:e,label:t,snippet:snippetAround$1(s.text,g,S)})))}}return g}function serializeState(e){return{backward:Object.fromEntries([...e.backward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet}))])),forward:Object.fromEntries([...e.forward.entries()].map(([e,t])=>[e,[...t].sort()])),externalForward:Object.fromEntries([...e.externalForward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url))]))}}function buildExternalBackward(e){let t=new Map;for(let[s,g]of e)for(let[e,S]of g){let g=t.get(e);g||(g=new Map,t.set(e,g)),g.set(s,S)}return t}function deserializeState(e){let t=new Map(Object.entries(e.externalForward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.url,{label:e.label??null,snippet:e.snippet??null}]))]));return{backward:new Map(Object.entries(e.backward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.source,{anchor:e.anchor??null,snippet:e.snippet??null}]))])),forward:new Map(Object.entries(e.forward??{}).map(([e,t])=>[e,new Set(t)])),externalForward:t,externalBackward:buildExternalBackward(t)}}var BacklinkIndex=class{projectDir;contentDir;contentFilter;states=new Map;mtimesByBranch=new Map;activeBranch=`main`;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.states.set(this.activeBranch,createEmptyState$1())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=createEmptyState$1(),this.states.set(e,t)),t}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return resolve(getLocalDir(this.projectDir),`cache`,e,`backlinks.json`)}updateDocument(e,t,s=[],g=this.activeBranch){if(isSystemDoc(e)||isConfigDoc(e))return;let S=this.getState(g),w=S.forward.get(e)??new Set,E=S.externalForward.get(e)??new Map;for(let t of w){let s=S.backward.get(t);s&&(s.delete(e),s.size===0&&S.backward.delete(t))}for(let t of E.keys()){let s=S.externalBackward.get(t);s&&(s.delete(e),s.size===0&&S.externalBackward.delete(t))}let D=new Set,O=new Map;S.forward.set(e,D),S.externalForward.set(e,O);for(let s of t){if(!s.target)continue;D.add(s.target);let t=S.backward.get(s.target);t||(t=new Map,S.backward.set(s.target,t)),t.set(e,mergeLinkMeta(t.get(e),{anchor:s.anchor,snippet:s.snippet}))}for(let t of s){if(!t.url)continue;O.set(t.url,{label:t.label,snippet:t.snippet});let s=S.externalBackward.get(t.url);s||(s=new Map,S.externalBackward.set(t.url,s)),(!s.has(e)||!s.get(e)?.snippet&&t.snippet)&&s.set(e,{label:t.label,snippet:t.snippet})}}updateDocumentFromMarkdown(e,t,s=this.activeBranch){try{let{body:g}=stripFrontmatter(t),S=extractWikiLinksFromMarkdown(g),w=extractMarkdownLinksFromMarkdown(g,e),E=extractExternalWikiLinksFromMarkdown(g),D=extractExternalMarkdownLinksFromMarkdown(g,e),O=new Set(S.map(e=>e.target)),k=[...S,...w.filter(e=>!O.has(e.target))],j=new Set(E.map(e=>e.url)),F=[...E,...D.filter(e=>!j.has(e.url))];this.updateDocument(e,k,F,s)}catch(t){console.warn(`[backlinks] Failed to scan ${e} for link extraction:`,t),this.deleteDocument(e,s)}}deleteDocument(e,t=this.activeBranch){if(isSystemDoc(e)||isConfigDoc(e))return;let s=this.getState(t),g=s.forward.get(e)??new Set,S=s.externalForward.get(e)??new Map;for(let t of g){let g=s.backward.get(t);g&&(g.delete(e),g.size===0&&s.backward.delete(t))}for(let t of S.keys()){let g=s.externalBackward.get(t);g&&(g.delete(e),g.size===0&&s.externalBackward.delete(t))}s.forward.delete(e),s.externalForward.delete(e)}renameDocument(e,t,s,g=this.activeBranch){this.deleteDocument(e,g),this.updateDocumentFromMarkdown(t,s,g)}getBacklinks(e,t=this.activeBranch){let s=this.getState(t).backward.get(e);return s?[...s.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source)):[]}getBacklinkCount(e,t=this.activeBranch){return this.getState(t).backward.get(e)?.size??0}getForwardLinks(e,t=this.activeBranch){return[...this.getState(t).forward.get(e)??new Set].sort((e,t)=>e.localeCompare(t))}getForwardLinkEntries(e,t=this.activeBranch){let s=this.getState(t),g=this.getForwardLinks(e,t).map(t=>({kind:`doc`,target:t,anchor:s.backward.get(t)?.get(e)?.anchor??null,snippet:s.backward.get(t)?.get(e)?.snippet??null})),S=[...(s.externalForward.get(e)??new Map).entries()].map(([e,t])=>({kind:`external`,url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url));return[...g,...S]}getOrphans(e,t=`both`,s=this.activeBranch){let g=this.getState(s);return[...e].filter(e=>{let s=(g.backward.get(e)?.size??0)>0,S=(g.forward.get(e)?.size??0)>0;return t===`incoming`?!s:(t===`outgoing`||!s)&&!S}).sort((e,t)=>e.localeCompare(t))}getHubs(e=20,t=this.activeBranch){return[...this.getState(t).backward.entries()].map(([e,t])=>({docName:e,count:t.size})).sort((e,t)=>t.count===e.count?e.docName.localeCompare(t.docName):t.count-e.count).slice(0,e)}getDeadLinks(e,t,s=this.activeBranch){let g=this.getState(s),S=new Set(e),w=t?.length?new Set(t):null;return[...g.backward.entries()].filter(([e,t])=>{if(S.has(e))return!1;if(!w)return t.size>0;for(let e of t.keys())if(w.has(e))return!0;return!1}).map(([e,t])=>({target:e,sources:[...t.entries()].filter(([e])=>!w||w.has(e)).map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source))})).filter(e=>e.sources.length>0).sort((e,t)=>t.sources.length===e.sources.length?e.target.localeCompare(t.target):t.sources.length-e.sources.length)}getLinkGraph(e=this.activeBranch){let t=this.getState(e),s=new Map,g=[];for(let[e,S]of t.forward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let w of S)s.set(w,{kind:`doc`,id:w,docName:w,anchor:getRepresentativeAnchor(t.backward.get(w))}),g.push({source:e,target:w})}for(let[e,S]of t.externalForward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let[t,w]of S){let S=externalNodeId(t);s.set(S,{kind:`external`,id:S,url:t,label:w.label}),g.push({source:e,target:S})}}return{nodes:[...s.values()].sort((e,t)=>e.id.localeCompare(t.id)),links:g}}getLinkGraphNeighborhood(e,t,s=this.activeBranch){let g=this.getState(s),S=new Map;for(let e of g.externalForward.values())for(let[t,s]of e)S.has(t)||S.set(t,s.label);let w=new Set([e]),E=[{nodeId:e,degree:0}],D=0;for(;D<E.length;){let e=E[D++];if(e.degree>=t)continue;let s=externalUrlFromNodeId(e.nodeId),S=new Set;if(s)for(let e of g.externalBackward.get(s)?.keys()??[])S.add(e);else{for(let t of g.forward.get(e.nodeId)??new Set)S.add(t);for(let t of g.externalForward.get(e.nodeId)?.keys()??[])S.add(externalNodeId(t));for(let t of g.backward.get(e.nodeId)?.keys()??[])S.add(t)}for(let t of S)w.has(t)||(w.add(t),E.push({nodeId:t,degree:e.degree+1}))}let O=[];for(let[e,t]of g.forward)if(w.has(e))for(let s of t)w.has(s)&&O.push({source:e,target:s});for(let[e,t]of g.externalForward)if(w.has(e))for(let s of t.keys()){let t=externalNodeId(s);w.has(t)&&O.push({source:e,target:t})}return{nodes:[...w].sort().map(e=>{let t=externalUrlFromNodeId(e);return t?{kind:`external`,id:e,url:t,label:S.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(g.backward.get(e))}}),links:O}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);mkdirSync(dirname(t),{recursive:!0});let s=this.getState(e),g=this.mtimesByBranch.get(e),S={...serializeState(s),...g?{mtimes:Object.fromEntries(g)}:{}};await writeFile(t,JSON.stringify(S,null,2),`utf-8`)}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!existsSync(t))return!1;try{let s=await readFile$1(t,`utf-8`),g=JSON.parse(s);return this.states.set(e,deserializeState(g)),g.mtimes?this.mtimesByBranch.set(e,new Map(Object.entries(g.mtimes))):this.mtimesByBranch.delete(e),!0}catch(t){return console.warn(`[backlinks] Failed to load cache for ${e}:`,t),!1}}clear(e=this.activeBranch){this.states.set(e,createEmptyState$1()),this.mtimesByBranch.delete(e)}async rebuildFromDisk(e=this.activeBranch){let t=createEmptyState$1(),s=new Map,g=[];this.walkForPaths(this.contentDir,g);let S=new Set,w=g.filter(({docName:e})=>S.has(e)?!1:(S.add(e),!0)),E=50;for(let e=0;e<w.length;e+=50){let g=w.slice(e,e+50),S=await Promise.allSettled(g.map(async({docName:e,filePath:t})=>{let[s,g]=await Promise.all([stat$1(t),readFile$1(t,`utf-8`)]);return{docName:e,mtimeMs:s.mtimeMs,markdown:g}}));for(let e of S){if(e.status===`rejected`){console.warn(`[backlinks] Failed to rebuild entry:`,e.reason);continue}let{docName:g,mtimeMs:S,markdown:w}=e.value;s.set(g,S);let{body:E}=stripFrontmatter(w),D=extractWikiLinksFromMarkdown(E),O=extractMarkdownLinksFromMarkdown(E,g),k=extractExternalWikiLinksFromMarkdown(E),j=extractExternalMarkdownLinksFromMarkdown(E,g),F=new Set(D.map(e=>e.target)),L=[...D,...O.filter(e=>!F.has(e.target))],B=new Set(k.map(e=>e.url)),H=[...k,...j.filter(e=>!B.has(e.url))],q=new Set,ee=new Map;t.forward.set(g,q),t.externalForward.set(g,ee);for(let e of L){if(!e.target)continue;q.add(e.target);let s=t.backward.get(e.target);s||(s=new Map,t.backward.set(e.target,s)),s.set(g,mergeLinkMeta(s.get(g),{anchor:e.anchor,snippet:e.snippet}))}for(let e of H){if(!e.url)continue;ee.set(e.url,{label:e.label,snippet:e.snippet});let s=t.externalBackward.get(e.url);s||(s=new Map,t.externalBackward.set(e.url,s)),s.set(g,{label:e.label,snippet:e.snippet})}}}this.states.set(e,t),this.mtimesByBranch.set(e,s)}walkForPaths(e,t){let s;try{s=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[backlinks] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkForPaths(s,t)}else if(g.isFile()&&isSupportedDocFile(g.name)){let e=relative(this.contentDir,s);if(this.contentFilter?.isExcluded(e))continue;t.push({docName:stripDocExtension(e),filePath:s})}}}async reconcileWithDisk(e=this.activeBranch){if(!existsSync(this.contentDir))return{added:0,updated:0,deleted:0};let t=this.mtimesByBranch.get(e)??new Map,s=[];this.walkForPaths(this.contentDir,s);let g=new Set,S=s.filter(({docName:e})=>g.has(e)?!1:(g.add(e),!0)),w=new Set(S.map(e=>e.docName)),E=new Map,D=0,O=0,k=[],j=await Promise.allSettled(S.map(async({docName:e,filePath:t})=>({docName:e,filePath:t,mtimeMs:(await stat$1(t)).mtimeMs})));for(let e of j){if(e.status===`rejected`)continue;let{docName:s,filePath:g,mtimeMs:S}=e.value,w=t.get(s);if(w!==void 0&&w===S){E.set(s,S);continue}k.push({docName:s,filePath:g,mtimeMs:S,isNew:w===void 0})}let F=50;for(let t=0;t<k.length;t+=50){let s=k.slice(t,t+50),g=await Promise.allSettled(s.map(async({docName:e,filePath:t,mtimeMs:s,isNew:g})=>({docName:e,mtimeMs:s,isNew:g,markdown:await readFile$1(t,`utf-8`)})));for(let t of g){if(t.status===`rejected`){console.warn(`[backlinks] Failed to reconcile file:`,t.reason);continue}let{docName:s,mtimeMs:g,isNew:S,markdown:w}=t.value;this.updateDocumentFromMarkdown(s,w,e),E.set(s,g),S?D++:O++}}let L=0,B=new Set([...t.keys(),...this.getState(e).forward.keys()]);for(let t of B)w.has(t)||(this.deleteDocument(t,e),L++);return this.mtimesByBranch.set(e,E),{added:D,updated:O,deleted:L}}};function extractActorIdentity(e,t){let s=normalizeSummary(e.summary);if(s.kind===`invalid`)return{kind:`invalid-summary`};let g=parseAgentBodyFields(e),S=t?.()??null;return g.rawAgentId!==void 0&&g.writerId!==void 0?{kind:`agent`,writerId:g.writerId,displayName:g.displayName,colorSeed:g.colorSeed??g.rawAgentId,clientName:g.clientName,clientVersion:g.clientVersion,label:g.label,actor:{principalId:S?.id,agentType:resolveAgentType(g.clientName),clientName:g.clientName,clientVersion:g.clientVersion,label:g.label},summary:s}:S?{kind:`principal`,writerId:S.id,displayName:S.display_name,colorSeed:S.id,actor:{principalId:S.id},summary:s}:{kind:`anonymous`,summary:s}}const ANCESTOR_WALK_DEPTH_LIMIT$1=30;function isProjectRoot(e){try{return statSync(resolve(e,OK_PROJECT_MARKER)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function findEnclosingProjectRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT$1;){let e=!1;try{e=isProjectRoot(t)}catch{e=!1}if(e)return{rootPath:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}function parsePorcelainPaths(e){let t=[];for(let s of e.split(`
|
|
849
|
+
`),g=[],S=null;for(let e of s)if(S)isFenceClose$1(e,S)&&(S=null);else{let s=matchFence$1(e);if(s)S=s;else{let s=extractExternalMarkdownLinksFromLine(e,t);g.push(...s.occurrences.map(({url:e,label:t,start:g,end:S})=>({url:e,label:t,snippet:snippetAround$1(s.text,g,S)})))}}return g}function serializeState(e){return{backward:Object.fromEntries([...e.backward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet}))])),forward:Object.fromEntries([...e.forward.entries()].map(([e,t])=>[e,[...t].sort()])),externalForward:Object.fromEntries([...e.externalForward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url))]))}}function buildExternalBackward(e){let t=new Map;for(let[s,g]of e)for(let[e,S]of g){let g=t.get(e);g||(g=new Map,t.set(e,g)),g.set(s,S)}return t}function deserializeState(e){let t=new Map(Object.entries(e.externalForward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.url,{label:e.label??null,snippet:e.snippet??null}]))]));return{backward:new Map(Object.entries(e.backward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.source,{anchor:e.anchor??null,snippet:e.snippet??null}]))])),forward:new Map(Object.entries(e.forward??{}).map(([e,t])=>[e,new Set(t)])),externalForward:t,externalBackward:buildExternalBackward(t)}}var BacklinkIndex=class{projectDir;contentDir;contentFilter;states=new Map;mtimesByBranch=new Map;activeBranch=`main`;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.states.set(this.activeBranch,createEmptyState$1())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=createEmptyState$1(),this.states.set(e,t)),t}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return resolve(getLocalDir(this.projectDir),`cache`,e,`backlinks.json`)}updateDocument(e,t,s=[],g=this.activeBranch){if(isSystemDoc(e)||isConfigDoc(e))return;let S=this.getState(g),w=S.forward.get(e)??new Set,E=S.externalForward.get(e)??new Map;for(let t of w){let s=S.backward.get(t);s&&(s.delete(e),s.size===0&&S.backward.delete(t))}for(let t of E.keys()){let s=S.externalBackward.get(t);s&&(s.delete(e),s.size===0&&S.externalBackward.delete(t))}let D=new Set,O=new Map;S.forward.set(e,D),S.externalForward.set(e,O);for(let s of t){if(!s.target)continue;D.add(s.target);let t=S.backward.get(s.target);t||(t=new Map,S.backward.set(s.target,t)),t.set(e,mergeLinkMeta(t.get(e),{anchor:s.anchor,snippet:s.snippet}))}for(let t of s){if(!t.url)continue;O.set(t.url,{label:t.label,snippet:t.snippet});let s=S.externalBackward.get(t.url);s||(s=new Map,S.externalBackward.set(t.url,s)),(!s.has(e)||!s.get(e)?.snippet&&t.snippet)&&s.set(e,{label:t.label,snippet:t.snippet})}}updateDocumentFromMarkdown(e,t,s=this.activeBranch){try{let{body:g}=stripFrontmatter(t),S=extractWikiLinksFromMarkdown(g),w=extractMarkdownLinksFromMarkdown(g,e),E=extractExternalWikiLinksFromMarkdown(g),D=extractExternalMarkdownLinksFromMarkdown(g,e),O=new Set(S.map(e=>e.target)),k=[...S,...w.filter(e=>!O.has(e.target))],j=new Set(E.map(e=>e.url)),F=[...E,...D.filter(e=>!j.has(e.url))];this.updateDocument(e,k,F,s)}catch(t){console.warn(`[backlinks] Failed to scan ${e} for link extraction:`,t),this.deleteDocument(e,s)}}deleteDocument(e,t=this.activeBranch){if(isSystemDoc(e)||isConfigDoc(e))return;let s=this.getState(t),g=s.forward.get(e)??new Set,S=s.externalForward.get(e)??new Map;for(let t of g){let g=s.backward.get(t);g&&(g.delete(e),g.size===0&&s.backward.delete(t))}for(let t of S.keys()){let g=s.externalBackward.get(t);g&&(g.delete(e),g.size===0&&s.externalBackward.delete(t))}s.forward.delete(e),s.externalForward.delete(e)}renameDocument(e,t,s,g=this.activeBranch){this.deleteDocument(e,g),this.updateDocumentFromMarkdown(t,s,g)}getBacklinks(e,t=this.activeBranch){let s=this.getState(t).backward.get(e);return s?[...s.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source)):[]}getBacklinkCount(e,t=this.activeBranch){return this.getState(t).backward.get(e)?.size??0}getForwardLinks(e,t=this.activeBranch){return[...this.getState(t).forward.get(e)??new Set].sort((e,t)=>e.localeCompare(t))}getForwardLinkEntries(e,t=this.activeBranch){let s=this.getState(t),g=this.getForwardLinks(e,t).map(t=>({kind:`doc`,target:t,anchor:s.backward.get(t)?.get(e)?.anchor??null,snippet:s.backward.get(t)?.get(e)?.snippet??null})),S=[...(s.externalForward.get(e)??new Map).entries()].map(([e,t])=>({kind:`external`,url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url));return[...g,...S]}getOrphans(e,t=`both`,s=this.activeBranch){let g=this.getState(s);return[...e].filter(e=>{let s=(g.backward.get(e)?.size??0)>0,S=(g.forward.get(e)?.size??0)>0;return t===`incoming`?!s:(t===`outgoing`||!s)&&!S}).sort((e,t)=>e.localeCompare(t))}getHubs(e=20,t=this.activeBranch){return[...this.getState(t).backward.entries()].map(([e,t])=>({docName:e,count:t.size})).sort((e,t)=>t.count===e.count?e.docName.localeCompare(t.docName):t.count-e.count).slice(0,e)}getDeadLinks(e,t,s=this.activeBranch){let g=this.getState(s),S=new Set(e),w=t?.length?new Set(t):null;return[...g.backward.entries()].filter(([e,t])=>{if(S.has(e))return!1;if(!w)return t.size>0;for(let e of t.keys())if(w.has(e))return!0;return!1}).map(([e,t])=>({target:e,sources:[...t.entries()].filter(([e])=>!w||w.has(e)).map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source))})).filter(e=>e.sources.length>0).sort((e,t)=>t.sources.length===e.sources.length?e.target.localeCompare(t.target):t.sources.length-e.sources.length)}getLinkGraph(e=this.activeBranch){let t=this.getState(e),s=new Map,g=[];for(let[e,S]of t.forward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let w of S)s.set(w,{kind:`doc`,id:w,docName:w,anchor:getRepresentativeAnchor(t.backward.get(w))}),g.push({source:e,target:w})}for(let[e,S]of t.externalForward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let[t,w]of S){let S=externalNodeId(t);s.set(S,{kind:`external`,id:S,url:t,label:w.label}),g.push({source:e,target:S})}}return{nodes:[...s.values()].sort((e,t)=>e.id.localeCompare(t.id)),links:g}}getLinkGraphNeighborhood(e,t,s=this.activeBranch){let g=this.getState(s),S=new Map;for(let e of g.externalForward.values())for(let[t,s]of e)S.has(t)||S.set(t,s.label);let w=new Set([e]),E=[{nodeId:e,degree:0}],D=0;for(;D<E.length;){let e=E[D++];if(e.degree>=t)continue;let s=externalUrlFromNodeId(e.nodeId),S=new Set;if(s)for(let e of g.externalBackward.get(s)?.keys()??[])S.add(e);else{for(let t of g.forward.get(e.nodeId)??new Set)S.add(t);for(let t of g.externalForward.get(e.nodeId)?.keys()??[])S.add(externalNodeId(t));for(let t of g.backward.get(e.nodeId)?.keys()??[])S.add(t)}for(let t of S)w.has(t)||(w.add(t),E.push({nodeId:t,degree:e.degree+1}))}let O=[];for(let[e,t]of g.forward)if(w.has(e))for(let s of t)w.has(s)&&O.push({source:e,target:s});for(let[e,t]of g.externalForward)if(w.has(e))for(let s of t.keys()){let t=externalNodeId(s);w.has(t)&&O.push({source:e,target:t})}return{nodes:[...w].sort().map(e=>{let t=externalUrlFromNodeId(e);return t?{kind:`external`,id:e,url:t,label:S.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(g.backward.get(e))}}),links:O}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);mkdirSync(dirname(t),{recursive:!0});let s=this.getState(e),g=this.mtimesByBranch.get(e),S={...serializeState(s),...g?{mtimes:Object.fromEntries(g)}:{}};await writeFile(t,JSON.stringify(S,null,2),`utf-8`)}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!existsSync(t))return!1;try{let s=await readFile$1(t,`utf-8`),g=JSON.parse(s);return this.states.set(e,deserializeState(g)),g.mtimes?this.mtimesByBranch.set(e,new Map(Object.entries(g.mtimes))):this.mtimesByBranch.delete(e),!0}catch(t){return console.warn(`[backlinks] Failed to load cache for ${e}:`,t),!1}}clear(e=this.activeBranch){this.states.set(e,createEmptyState$1()),this.mtimesByBranch.delete(e)}async rebuildFromDisk(e=this.activeBranch){let t=createEmptyState$1(),s=new Map,g=[];await this.walkForPaths(this.contentDir,g);let S=new Set,w=g.filter(({docName:e})=>S.has(e)?!1:(S.add(e),!0)),E=50;for(let e=0;e<w.length;e+=50){let g=w.slice(e,e+50),S=await Promise.allSettled(g.map(async({docName:e,filePath:t})=>{let[s,g]=await Promise.all([stat$1(t),readFile$1(t,`utf-8`)]);return{docName:e,mtimeMs:s.mtimeMs,markdown:g}}));for(let e of S){if(e.status===`rejected`){console.warn(`[backlinks] Failed to rebuild entry:`,e.reason);continue}let{docName:g,mtimeMs:S,markdown:w}=e.value;s.set(g,S);let{body:E}=stripFrontmatter(w),D=extractWikiLinksFromMarkdown(E),O=extractMarkdownLinksFromMarkdown(E,g),k=extractExternalWikiLinksFromMarkdown(E),j=extractExternalMarkdownLinksFromMarkdown(E,g),F=new Set(D.map(e=>e.target)),L=[...D,...O.filter(e=>!F.has(e.target))],B=new Set(k.map(e=>e.url)),H=[...k,...j.filter(e=>!B.has(e.url))],q=new Set,ee=new Map;t.forward.set(g,q),t.externalForward.set(g,ee);for(let e of L){if(!e.target)continue;q.add(e.target);let s=t.backward.get(e.target);s||(s=new Map,t.backward.set(e.target,s)),s.set(g,mergeLinkMeta(s.get(g),{anchor:e.anchor,snippet:e.snippet}))}for(let e of H){if(!e.url)continue;ee.set(e.url,{label:e.label,snippet:e.snippet});let s=t.externalBackward.get(e.url);s||(s=new Map,t.externalBackward.set(e.url,s)),s.set(g,{label:e.label,snippet:e.snippet})}}}this.states.set(e,t),this.mtimesByBranch.set(e,s)}async walkForPaths(e,t){let s;try{s=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[backlinks] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkForPaths(s,t)}else if(g.isFile()&&isSupportedDocFile(g.name)){let e=relative(this.contentDir,s);if(this.contentFilter?.isExcluded(e))continue;t.push({docName:stripDocExtension(e),filePath:s})}}}async reconcileWithDisk(e=this.activeBranch){if(!existsSync(this.contentDir))return{added:0,updated:0,deleted:0};let t=this.mtimesByBranch.get(e)??new Map,s=[];await this.walkForPaths(this.contentDir,s);let g=new Set,S=s.filter(({docName:e})=>g.has(e)?!1:(g.add(e),!0)),w=new Set(S.map(e=>e.docName)),E=new Map,D=0,O=0,k=[],j=await Promise.allSettled(S.map(async({docName:e,filePath:t})=>({docName:e,filePath:t,mtimeMs:(await stat$1(t)).mtimeMs})));for(let e of j){if(e.status===`rejected`)continue;let{docName:s,filePath:g,mtimeMs:S}=e.value,w=t.get(s);if(w!==void 0&&w===S){E.set(s,S);continue}k.push({docName:s,filePath:g,mtimeMs:S,isNew:w===void 0})}let F=50;for(let t=0;t<k.length;t+=50){let s=k.slice(t,t+50),g=await Promise.allSettled(s.map(async({docName:e,filePath:t,mtimeMs:s,isNew:g})=>({docName:e,mtimeMs:s,isNew:g,markdown:await readFile$1(t,`utf-8`)})));for(let t of g){if(t.status===`rejected`){console.warn(`[backlinks] Failed to reconcile file:`,t.reason);continue}let{docName:s,mtimeMs:g,isNew:S,markdown:w}=t.value;this.updateDocumentFromMarkdown(s,w,e),E.set(s,g),S?D++:O++}}let L=0,B=new Set([...t.keys(),...this.getState(e).forward.keys()]);for(let t of B)w.has(t)||(this.deleteDocument(t,e),L++);return this.mtimesByBranch.set(e,E),{added:D,updated:O,deleted:L}}};function extractActorIdentity(e,t){let s=normalizeSummary(e.summary);if(s.kind===`invalid`)return{kind:`invalid-summary`};let g=parseAgentBodyFields(e),S=t?.()??null;return g.rawAgentId!==void 0&&g.writerId!==void 0?{kind:`agent`,writerId:g.writerId,displayName:g.displayName,colorSeed:g.colorSeed??g.rawAgentId,clientName:g.clientName,clientVersion:g.clientVersion,label:g.label,actor:{principalId:S?.id,agentType:resolveAgentType(g.clientName),clientName:g.clientName,clientVersion:g.clientVersion,label:g.label},summary:s}:S?{kind:`principal`,writerId:S.id,displayName:S.display_name,colorSeed:S.id,actor:{principalId:S.id},summary:s}:{kind:`anonymous`,summary:s}}const ANCESTOR_WALK_DEPTH_LIMIT$1=30;function isProjectRoot(e){try{return statSync(resolve(e,OK_PROJECT_MARKER)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function findEnclosingProjectRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT$1;){let e=!1;try{e=isProjectRoot(t)}catch{e=!1}if(e)return{rootPath:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}function parsePorcelainPaths(e){let t=[];for(let s of e.split(`
|
|
850
850
|
`)){if(s.length<4)continue;let e=s.slice(3),g=e.indexOf(` -> `),S=g>=0?e.slice(g+4):e;S.length>0&&t.push(S)}return t}function parseDiffPaths(e){return e.split(`
|
|
851
851
|
`).map(e=>e.trim()).filter(e=>e.length>0)}async function dirtyFilesOverlapWith(e,t){let{git:s}=createGitInstance(e),[g,S]=await Promise.all([s.raw([`status`,`--porcelain`]),s.raw([`diff`,`--name-only`,`HEAD..${t}`])]),w=new Set(parsePorcelainPaths(g));if(w.size===0)return{conflicts:!1,files:[]};let E=parseDiffPaths(S);if(E.length===0)return{conflicts:!1,files:[]};let D=new Set;for(let e of E)w.has(e)&&D.add(e);return D.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(D).sort()}}function isValidBranchInfoPath(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function computeBranchInfo(e,t,s,g){let{git:S}=createGitInstance(e);await S.raw([`rev-parse`,`--git-dir`]);let w=(async()=>{try{let e=(await S.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await S.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),E=w.then(async e=>{if(g===`folder`&&s===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await S.raw([`cat-file`,`-e`,`${t}:${s}`]),!0}catch{return!1}}),D=S.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),O=dirtyFilesOverlapWith(e,t).catch(e=>{if(isBranchResolutionError(e))return{conflicts:!1,files:[]};let s=e instanceof Error?e.message:String(e),g=s.length>500?`${s.slice(0,500)}…`:s;return console.warn(`[git-branch-info] action=dirty-overlap-failed branch=${t} error=${g}`),{conflicts:!1,files:[]}}),[k,j,F,L]=await Promise.all([w,E,D,O]);return k.detached?{detached:!0,currentBranch:null,currentHeadSha:k.currentHeadSha,shareTargetExists:j,dirtyConflicts:L,branchIsLocal:F}:{detached:!1,currentBranch:k.currentBranch,currentHeadSha:null,shareTargetExists:j,dirtyConflicts:L,branchIsLocal:F}}const BRANCH_INFO_HANDLER_TAG=`git-branch-info`;function isBranchResolutionError(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const BRANCH_IN_OTHER_WORKTREE_RE=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function isBranchInOtherWorktreeError(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(BRANCH_IN_OTHER_WORKTREE_RE);if(t===null)return{held:!1};let s=t[1];if(s===void 0||s.length===0)return{held:!1};let g;try{g=realpathSync(s)}catch{g=s}return{held:!0,path:g}}const CHECKOUT_HANDLER_TAG=`git-checkout`,isBranchNotFoundFetchError=isBranchNotFoundGitError;async function runCheckoutFlow(e,t){let{git:s}=createGitInstance(e),g=await s.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!g)try{await s.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:isBranchNotFoundFetchError(e)?`branch-not-found`:`fetch-failed`}}let S=await dirtyFilesOverlapWith(e,g?t:`origin/${t}`);if(S.conflicts)return{ok:!1,reason:`dirty-conflict`,files:S.files};try{return await s.raw([`checkout`,t]),{ok:!0}}catch(e){let s=isBranchInOtherWorktreeError(e);if(s.held)return console.warn(`[git-checkout] reason=branch-in-other-worktree branch=${t} held_at=${s.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:s.path};let g=e instanceof Error?e.message:String(e),S=g.length>500?`${g.slice(0,500)}…`:g;return console.warn(`[git-checkout] action=checkout-failed branch=${t} error=${S}`),{ok:!1,reason:`checkout-failed`}}}const defaultGitConfigReader=(e,t,s)=>{let g=spawnSync(`git`,[`config`,s===`worktree`?`--worktree`:s===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return g.status!==0||!g.stdout?null:g.stdout.trim()||null};function isLinkedWorktree(e){let t=spawnSync(`git`,[`rev-parse`,`--git-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||s.status!==0?!1:resolve(e,t.stdout.trim())!==resolve(e,s.stdout.trim())}function ensureWorktreeConfigExtension(e){let t=spawnSync(`git`,[`config`,`--local`,`--get`,`extensions.worktreeConfig`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&/^(true|yes|on|1)$/i.test(t.stdout.trim()))return;let s=spawnSync(`git`,[`config`,`--local`,`extensions.worktreeConfig`,`true`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(s.status!==0){let e=s.stderr?.trim()??``,t=s.error?` [${s.error.message}]`:``;throw Error(`failed to enable extensions.worktreeConfig: ${e}${t}`)}}async function resolveGitIdentity(e,t,s,g=defaultGitConfigReader){let S=g(e,`user.name`,`worktree`),w=g(e,`user.email`,`worktree`);if(S&&w)return{name:S,email:w};let E=g(e,`user.name`,`local`),D=g(e,`user.email`,`local`);if(E&&D)return{name:E,email:D};let O=g(e,`user.name`,`global`),k=g(e,`user.email`,`global`);if(O&&k)return{name:O,email:k};if(t&&s){let e=await t.get(s);if(e){let t=e.name??e.login,s=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:s}}}return null}function writeGitIdentity(e,t,s){let g=`--local`;isLinkedWorktree(e)&&(ensureWorktreeConfigExtension(e),g=`--worktree`);let S=(t,s)=>{let S=spawnSync(`git`,[`config`,g,t,s],{cwd:e,encoding:`utf-8`,timeout:5e3});if(S.status!==0){let e=S.stderr?.trim()??``,s=S.error?` [${S.error.message}]`:``;throw Error(`git config ${g} ${t} failed: ${e}${s}`)}};S(`user.name`,t),S(`user.email`,s)}const CONFIG_FILENAME=`config.yml`;function assertNotSymlink(e,t){let s;try{s=lstatSync(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(s.isSymbolicLink())throw Error(`Refusing to follow symlink at ${t} (${e}). An untrusted upstream may have committed this symlink to redirect writes outside the project. Remove the symlink and re-run.`)}function packageVersionMajorMinor(e){let[t=`0`,s=`0`]=e.split(`.`);return`${t.length>0?t:`0`}.${s.length>0?s:`0`}`}function quoteYamlScalar(e){return/^[A-Za-z0-9._\-/]+$/.test(e)?e:JSON.stringify(e)}function buildConfigYmlContent(e,t){let s=`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${CONFIG_SCHEMA_MAJOR_PATH}/config.project.schema.json
|
|
852
852
|
# Open Knowledge — project configuration
|
|
@@ -1699,17 +1699,16 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
|
|
|
1699
1699
|
`).filter(e=>e.length===40)}catch{}try{let e=(await J.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/${S}/`)).trim().split(`
|
|
1700
1700
|
`).filter(Boolean);te.push(...e)}catch{}if(ne&&te.length===0)try{let e=(await J.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/main/`)).trim().split(`
|
|
1701
1701
|
`).filter(Boolean);te.push(...e)}catch{}if(te.length===0&&Y.length===0&&ae.length===0)return EMPTY;let oe=[...Y,...ae],se=[];if(oe.length>0){let t=parseGitLogOutput(await J.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...oe)).map(e=>({...e,type:`checkpoint`}));if(L&&(t=await filterEntriesByChain(e,t,j,S,F,ee,q)),ne&&Y.length>0&&ae.length>0){let e=new Set(Y),s=t.filter(t=>e.has(t.sha)),g=t.filter(t=>!e.has(t.sha)),S=s.reduce((e,t)=>{let s=new Date(t.timestamp).getTime();return s<e?s:e},1/0);se=[...s,...g.filter(e=>new Date(e.timestamp).getTime()<S)]}else se=t}let ce=[...te];for(let e of oe)ce.push(e);let ue=[];if(ce.length>0&&(ue=parseGitLogOutput(await J.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...ce,...L?[`--`,L]:[])),H))for(let t=0;t<j.length-1;t++){let s=j[t];if(s.renameCommit!==null)try{let t=await buildSeeds(e,s.renameCommit,S,q);if(t.length===0)continue;let g=F(s.path),w=await logSeededReachable(e,[`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`],t,g);ue=[...ue,...parseGitLogOutput(w)]}catch(e){console.warn(`[timeline] predecessor walk failed for step ${t} (${s.path}); skipping:`,e)}}let de=[...se,...ue],fe=new Set,me=[];for(let e of de)fe.has(e.sha)||(fe.add(e.sha),me.push(e));let ge=me;me.length>0&&j.length>0&&(ge=filterEntriesByOkActorDocs(me,j,await Promise.all(j.map(async t=>{if(t.renameCommit===null)return null;let s=await buildSeeds(e,t.renameCommit,S,q);return s.length===0?new Set:buildAncestorShaSet(e,s,S,ee)})))),ge.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let _e=ge;_e=_e.filter(e=>e.type!==`park`),D.length>0&&(_e=_e.filter(e=>D.includes(e.type))),O.length>0&&(_e=_e.filter(e=>matchesAuthor(e,O))),k.length>0&&(_e=_e.filter(e=>!matchesAuthor(e,k)));let ve=_e.length;return{entries:_e.slice(E,E+w).map(({rawBody:e,...t})=>t),total:ve,hasMore:E+w<ve}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),EMPTY}}async function getFolderTimeline(e,t,s=`.`,g){if(!existsSync(e.workTree)||!existsSync(e.gitDir)||t.includes(`..`)||t.includes(`\0`))return EMPTY;let S=g?.branch??`main`,w=Math.max(1,g?.limit??50),E=Math.max(0,g?.offset??0),D=s===`.`?``:s.replace(/^\.\//,``),O=t.replace(/^\.?\/+/,``).replace(/\/+$/,``),k=[D,O,`.ok`].filter(Boolean).join(`/`),j=shadowGit(e);try{let e=[];for(let t of[`refs/wip/${S}/`,`refs/checkpoints/${S}/`])try{let s=(await j.raw(`for-each-ref`,`--format=%(refname)`,t)).trim().split(`
|
|
1702
|
-
`).filter(Boolean);e.push(...s)}catch{}if(e.length===0)return EMPTY;let t=await j.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...e,`--`,k),s=O?`${O}/.ok/`:`.ok/`,g=new Set,D=[];for(let e of parseGitLogOutput(t)){if(g.has(e.sha)||!isFolderArtifactSubject(e.message)||!e.contributors.some(e=>e.docs.some(e=>e.startsWith(s))))continue;g.add(e.sha);let{rawBody:t,...S}=e;D.push(S)}let F=D.length;return{entries:D.slice(E,E+w),total:F,hasMore:E+w<F}}catch(e){return console.warn(`[timeline] getFolderTimeline failed, returning empty result:`,e),EMPTY}}let _httpDurationHist=null;function httpDurationHist(){return _httpDurationHist||=getMeter().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),_httpDurationHist}let _hintEmittedCounter=null;function hintEmittedCounter(){return _hintEmittedCounter||=getMeter().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of preview-attach hints emitted on write-tool responses when no editor is attached to __system__. Covers both attach-preview-once (URL exists, no browser) and start-ui (no UI running anywhere) variants — the tool side disambiguates via the warning action; the metric name is retained as-is so existing dashboards keep working.`}),_hintEmittedCounter}let _agentPatchFmTouchCounter=null;function agentPatchFmTouchCounter(){return _agentPatchFmTouchCounter||=getMeter().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:`Count of agent-patch calls whose find string targets the frontmatter region. Measures incidence during the soft-deprecation window before agent-patch FM-intersecting calls are enforced as 400. Bounded label: result ∈ {rejected, pre_deprecation_passthrough}.`}),_agentPatchFmTouchCounter}function findLooksLikeFrontmatter(e){return!!(/(^|\n)---(\s|\n|$)/.test(e)||/^\s*[\w-]+:\s+\S/.test(e))}let _renameAttributionCounter=null;function renameAttributionCounter(){return _renameAttributionCounter||=getMeter().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),_renameAttributionCounter}let _agentWriteGateFiredCounter=null;function agentWriteGateFiredCounter(){return _agentWriteGateFiredCounter||=getMeter().createCounter(`ok.agent_write.gate_fired_total`,{description:`Count of agent writes that ran the Site A content-divergence gate (denominator for the divergence rate). Bounded label: handler ∈ {agent-write-md, agent-patch, rollback}.`}),_agentWriteGateFiredCounter}let _agentWriteContentDivergenceCounter=null;function agentWriteContentDivergenceCounter(){return _agentWriteContentDivergenceCounter||=getMeter().createCounter(`ok.agent_write.content_divergence_total`,{description:`Count of agent writes whose converged Y.Text diverged from the composed intent (numerator for the divergence rate). Bounded labels: handler ∈ {agent-write-md, agent-patch, rollback}, divergence_type.`}),_agentWriteContentDivergenceCounter}function recordContentDivergenceGate(e,t){agentWriteGateFiredCounter().add(1,{handler:e}),t!==void 0&&agentWriteContentDivergenceCounter().add(1,{handler:e,divergence_type:t.divergenceType})}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$4=getLogger(`api`);function ytextHasConflictMarkers(e){return/^<{7} /m.test(e)&&/^={7}$/m.test(e)&&/^>{7} /m.test(e)}function safeDocPath(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let s=t===`.`?``:t.replace(/^\.\//,``),g=getDocExtension(e);return{path:s?`${s}/${e}${g}`:`${e}${g}`}}const GENERIC_PASTE_NAMES=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i,SAFE_FILENAME_CHARS=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,STRIP_ON_SIGHT=/[/\\\x00-\x1f\x7f]/g;function sanitizeFilename(e){let t=e.replace(STRIP_ON_SIGHT,``);if(t=t.replace(SAFE_FILENAME_CHARS,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let s=255,g=new TextEncoder;if(g.encode(t).length>255){let e=t.lastIndexOf(`.`),s=e>=0?t.slice(e):``,S=e>=0?t.slice(0,e):t;for(;g.encode(S+s).length>255&&S.length>0;)S=S.slice(0,-1);t=(S||`upload`)+s,g.encode(t).length>255&&(t=`upload`)}return t}function resolveUploadDestDir(e,t,s){let g=t.trim();return g===``||g===`./`?resolve(s,dirname(e)):g===`/`?s:g.startsWith(`./`)?resolve(s,dirname(e),g.slice(2)):resolve(s,g)}function readTempFileHead(e,t){let s=openSync(e,`r`);try{let e=Buffer.alloc(t),g=readSync(s,e,0,t,0);return e.subarray(0,g)}finally{closeSync(s)}}const MAX_DEDUP_SCAN_CANDIDATES=1e3;async function streamingHashFile(e){let t=createHash(`sha256`);return await pipeline(createReadStream(e),t),t.digest(`hex`)}async function findDuplicateAsset(e,t,s){let g;try{g=await readdir(e)}catch{return null}let S=getLogger(`upload`),w=0;for(let E of g){let g=extname(E).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(g))continue;let D=resolve(e,E),O;try{O=await stat$1(D)}catch{continue}if(!O.isFile()||O.size!==s)continue;if(w++,w>MAX_DEDUP_SCAN_CANDIDATES)return S.warn({event:`upload-dedup-skip`,reason:`scan-cap-exceeded`,destDir:e,scanned:MAX_DEDUP_SCAN_CANDIDATES,expectedSize:s},`[upload-dedup] candidate scan exceeded ${MAX_DEDUP_SCAN_CANDIDATES} same-size siblings — degrading to no-dedup for this upload`),null;let k;try{k=await streamingHashFile(D)}catch(e){let t=e.code;t!==`ENOENT`&&S.warn({event:`upload-dedup-skip`,reason:`read-failed`,code:t,entry:E},`[upload-dedup] skipped candidate — read failed`);continue}if(k===t)return E}return null}function readUploadBody(e,t){return new Promise((s,g)=>{let S;try{S=(0,import_lib.default)({headers:e.headers,limits:{files:1,fields:10,fieldSize:2*1024}})}catch(e){g(new UploadWriteError(`urn:ok:error:malformed-upload`,e));return}let w=!1,E=`upload`,D=``,O=``,k,j,F=!1,L=(e,t)=>{if(!w){if(w=!0,k)try{unlinkSync(k)}catch{}g(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},B=classifyUploadErrno;S.on(`field`,(e,t)=>{e===`parentDocName`&&(O=t)}),S.on(`file`,(e,g,S)=>{F=!0,E=S.filename||`upload`,D=S.mimeType||``;let H;try{H=mintTempUploadPath(t)}catch(e){L(B(e),e),g.resume();return}k=H;let q=new HashingPassThrough;pipeline(g,q,createWriteStream(H)).then(()=>{w||(w=!0,s({filename:E,mimeType:D,parentDocName:O,tempPath:H,sha:q.digest(),byteLength:q.byteLength()}))}).catch(e=>{j=e,L(B(e),e)})}),S.on(`error`,e=>{L(`urn:ok:error:malformed-upload`,e)}),S.on(`close`,()=>{w||j||F||(w=!0,s({filename:``,mimeType:``,parentDocName:O,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{w||j||e.complete||L(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(S)})}function safeSubdir(e,t){let s=resolve(e,t);if(s!==e&&!s.startsWith(`${e}/`))throw Error(`Invalid directory: ${t}`);return s}function synthesizeShowAllAssetExt(e){let t=extname(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}const DEFAULT_SHOWALL_MAX_ENTRIES=5e4;function getShowAllMaxEntries(){let e=process.env.OK_SHOWALL_MAX_ENTRIES;if(e===void 0)return DEFAULT_SHOWALL_MAX_ENTRIES;let t=Number(e);return Number.isInteger(t)&&t>0?t:DEFAULT_SHOWALL_MAX_ENTRIES}let showAllWalkInvocations=0,showAllWalkAborts=0;function __getShowAllWalkStatsForTesting(){return{invocations:showAllWalkInvocations,aborts:showAllWalkAborts}}function __resetShowAllWalkStatsForTesting(){showAllWalkInvocations=0,showAllWalkAborts=0}function showAllWantsNdjson(e){let t=e.headers.accept;return typeof t==`string`&&t.includes(`application/x-ndjson`)}async function*streamShowAllEntries(e){let{contentDir:t,contentFilter:s,dirFilter:g,getDocExtension:S,maxEntries:w,signal:E}=e,D=e.maxDepth??1/0;showAllWalkInvocations+=1;let O=0,k=!1,j=!1,F=e=>g?e===g||e.startsWith(`${g}/`):!0,L;try{L=await realpath(t)}catch{L=t}let B=e=>e===L?!0:e.startsWith(`${L}/`);async function H(e,t){let g;try{g=await readdir(e,{withFileTypes:!0})}catch(t){return console.warn(`[document-list][showAll] probe readdir failed for ${e}:`,t),!1}for(let S of g){let g=t?`${t}/${S.name}`:S.name;if(S.isDirectory()){if(s.isDirExcluded(g,{bypassFilters:!0}))continue;try{if(!B(await realpath(`${e}/${S.name}`)))continue}catch{continue}return!0}if(S.isFile()&&!s.isExcluded(g,{bypassFilters:!0}))return!0}return!1}async function*q(e,t,g){let L;try{L=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[document-list][showAll] readdir failed for ${e}:`,t);return}for(let ee of L){if(E?.aborted){j=!0;return}if(O>=w){k=!0;return}let L=t?`${t}/${ee.name}`:ee.name;if(ee.isDirectory()){if(s.isDirExcluded(L,{bypassFilters:!0}))continue;let t=`${e}/${ee.name}`,S;try{S=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!B(S)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${S}`);continue}if(F(L)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}O+=1;let s=g>=D?await H(t,L):void 0;yield{kind:`folder`,path:L,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null,...s===void 0?{}:{hasChildren:s}}}g<D&&(yield*q(t,L,g+1));continue}if(!ee.isFile()||s.isExcluded(L,{bypassFilters:!0})||!F(L))continue;let J=null;try{J=await stat$1(`${e}/${ee.name}`)}catch(t){console.warn(`[document-list][showAll] stat failed for ${e}/${ee.name}:`,t);continue}if(isSupportedDocFile(ee.name)){let e=L.replace(/\.(md|mdx)$/i,``),t=S(e);O+=1,yield{kind:`document`,docName:e,docExt:t,size:J.size,modified:J.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let Y=synthesizeShowAllAssetExt(ee.name),te=mediaKindForSidebarAssetExtension(Y);O+=1,yield{kind:`asset`,docName:L,docExt:Y,path:L,assetExt:Y,mediaKind:te,referencedBy:[],size:J.size,modified:J.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null}}}return yield*q(g?`${t}/${g}`:t,g??``,1),j&&(showAllWalkAborts+=1),{truncated:k}}async function walkContentDirForShowAll(e){let{documents:t,...s}=e,g=streamShowAllEntries(s),S=await g.next();for(;!S.done;)t.push(S.value),S=await g.next();return S.value}function isValidRelativeContentPath(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function isReservedProjectStatePath(e){return e===`.ok`||e.startsWith(`.ok/`)||e===`.git`||e.startsWith(`.git/`)}function isReservedSyntheticFolderPath(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function listAffectedDocNames(e,t,s){let g=[...e.keys()].filter(e=>t===`file`?e===s:e===s||e.startsWith(`${s}/`));return g.sort((e,t)=>e.localeCompare(t)),g}function remapDocNameForRename(e,t,s,g){return t===`file`||e===s?g:`${g}${e.slice(s.length)}`}function requireNonEmptyDocName(e,t,s){return e!==void 0&&e.length>0?e:(errorResponse(t,400,`urn:ok:error:invalid-request`,"`docName` must be a non-empty document name.",{handler:s}),null)}function assertNoSymlinkEscape(e,t){let s;try{s=realpathSync(t)}catch(e){throw e.code===`ENOENT`?new SymlinkEscapeError(`content directory does not exist`):e}let g=e;for(;;)try{if(!isWithinContentDir(realpathSync(g),s))throw new SymlinkEscapeError(`path resolves outside content directory`);return}catch(e){let s=e.code;if(s===`ELOOP`)throw new SymlinkEscapeError(`symlink cycle in path`);if(s!==`ENOENT`)throw e;let S=dirname(g);if(S===g||S!==t&&!S.startsWith(`${t}${sep}`))throw e;g=S}}function resolveContentEntryPath(e,t,s){if(!isValidRelativeContentPath(s))throw Error(`path must be a relative content path`);let g=resolve(e),S=resolve(g,t===`file`?isSupportedDocFile(s)?s:`${s}${getDocExtension(s)}`:s);if(S!==g&&!S.startsWith(`${g}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(S,g),S}function splitContentPath(e){let t=e.lastIndexOf(`/`);return t===-1?{parent:``,basename:e}:{parent:e.slice(0,t),basename:e.slice(t+1)}}function joinContentPath(e,t){return e?`${e}/${t}`:t}function duplicateBasename(e,t){return t===1?`${e} copy`:`${e} copy ${t}`}var DuplicateNameExhaustedError=class extends Error{constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};function isAlreadyExistsError(e){let t=e.code;return t===`EEXIST`||t===`ERR_FS_CP_EEXIST`}function classifyDuplicatePathFilesystemProblem(e){let t=e.code;return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function docNameExistsWithAnySupportedExtension(e,t){return SUPPORTED_DOC_EXTENSIONS.some(s=>existsSync(resolve(e,`${t}${s}`)))}function resolveDuplicateDocPath(e,t,s){if(!isValidRelativeContentPath(t))throw Error(`path must be a relative content path`);let g=resolve(e),S=resolve(g,`${t}${s}`);if(S!==g&&!S.startsWith(`${g}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(S,g),S}function nextAvailableDuplicateDocName(e,t){let{parent:s,basename:g}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let S=joinContentPath(s,duplicateBasename(g,t));if(!docNameExistsWithAnySupportedExtension(e,S))return{docName:S,attempt:t}}throw new DuplicateNameExhaustedError(t)}function nextAvailableDuplicateFolderPath(e,t){let{parent:s,basename:g}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let S=joinContentPath(s,duplicateBasename(g,t));if(!existsSync(resolveContentEntryPath(e,`folder`,S)))return{folderPath:S,attempt:t}}throw new DuplicateNameExhaustedError(t)}function collectMarkdownCopies(e,t){let s=resolveContentEntryPath(e,`folder`,t),g=[];function S(e,t){for(let s of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,s.name),E=t?`${t}/${s.name}`:s.name;if(s.isDirectory()){S(w,E);continue}!s.isFile()||!isSupportedDocFile(E)||g.push({docName:stripDocExtension(E),fullPath:w,content:readFileSync(w,`utf-8`)})}}return S(s,t),g.sort((e,t)=>e.docName.localeCompare(t.docName)),g}function collectFolderPaths(e,t){let s=resolveContentEntryPath(e,`folder`,t),g=[t];function S(e,t){for(let s of readdirSync(e,{withFileTypes:!0})){if(!s.isDirectory())continue;let w=resolve(e,s.name),E=t?`${t}/${s.name}`:s.name;g.push(E),S(w,E)}}return S(s,t),g.sort((e,t)=>e.localeCompare(t)),g}function probeAndRegisterSourceFileExtension(e,t){if(!isValidRelativeContentPath(t))return;let s=resolve(e);for(let e of SUPPORTED_DOC_EXTENSIONS){let g=resolve(s,`${t}${e}`);if(!(g!==s&&!g.startsWith(`${s}${sep}`))&&existsSync(g)){registerDocExtension(t,e);return}}}function toGitRelativePath(e,t){let s=resolve(e),g=resolve(t);return g!==s&&!g.startsWith(`${s}${sep}`)?null:relative(s,g).split(sep).join(`/`)}function stringsDifferOnlyByCase(e,t){return e!==t&&e.toLowerCase()===t.toLowerCase()}function pathsDifferOnlyByCase(e,t){return stringsDifferOnlyByCase(resolve(e),resolve(t))}function isCaseOnlySelfCollision(e,t){if(!pathsDifferOnlyByCase(e,t)||!existsSync(e)||!existsSync(t))return!1;try{let s=statSync(e),g=statSync(t);return s.dev===g.dev&&s.ino===g.ino}catch{return!1}}function createCaseOnlyRenameTempPath(e){let t=dirname(e);for(let e=0;e<10;e+=1){let e=resolve(t,`.ok-case-rename-${randomUUID()}`);if(!existsSync(e))return e}throw Error(`Unable to allocate temporary path for case-only rename`)}function renamePathOnDisk(e,t){if(tracedMkdirSync(dirname(t),{recursive:!0}),!pathsDifferOnlyByCase(e,t)){tracedRenameSync(e,t);return}let s=createCaseOnlyRenameTempPath(e);tracedRenameSync(e,s);try{tracedRenameSync(s,t)}catch(t){try{let t=existsSync(s),g=existsSync(e);t&&!g?tracedRenameSync(s,e):console.warn(`[renamePathOnDisk] skipped case-only rollback due to unexpected state:`,{tempExists:t,sourceExists:g})}catch(e){console.warn(`[renamePathOnDisk] failed to roll back temporary case-only rename:`,e)}throw t}}async function renameTrackedPathInGit(e,t,s){if(!e)return!1;let g=toGitRelativePath(e,t),S=toGitRelativePath(e,s);return!g||!S?!1:await withParentLock(async()=>{let w=esm_default({baseDir:e,timeout:{block:15e3}}),E=``;try{E=(await w.raw(`ls-files`,`--`,g)).trim()}catch(e){return console.warn(`[renameTrackedPathInGit] git ls-files failed, falling back to fs rename:`,e),!1}if(!E)return!1;mkdirSync(dirname(s),{recursive:!0});let D=!1;try{if(pathsDifferOnlyByCase(t,s)){let s=toGitRelativePath(e,createCaseOnlyRenameTempPath(t));if(!s)return!1;await w.raw(`mv`,`--`,g,s);try{await w.raw(`mv`,`--`,s,S)}catch(e){try{await w.raw(`mv`,`--`,s,g)}catch(e){console.warn(`[renameTrackedPathInGit] case-only git rename failed and rollback also failed; git index and disk may have diverged:`,e),D=!0}throw e}}else await w.raw(`mv`,`--`,g,S);return!0}catch(e){if(D)throw e;return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}const workspaceSearchCaches=new Map;function extractHeadings(e){let t=e;if(e.startsWith(`---
|
|
1702
|
+
`).filter(Boolean);e.push(...s)}catch{}if(e.length===0)return EMPTY;let t=await j.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...e,`--`,k),s=O?`${O}/.ok/`:`.ok/`,g=new Set,D=[];for(let e of parseGitLogOutput(t)){if(g.has(e.sha)||!isFolderArtifactSubject(e.message)||!e.contributors.some(e=>e.docs.some(e=>e.startsWith(s))))continue;g.add(e.sha);let{rawBody:t,...S}=e;D.push(S)}let F=D.length;return{entries:D.slice(E,E+w),total:F,hasMore:E+w<F}}catch(e){return console.warn(`[timeline] getFolderTimeline failed, returning empty result:`,e),EMPTY}}let _httpDurationHist=null;function httpDurationHist(){return _httpDurationHist||=getMeter().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),_httpDurationHist}let _hintEmittedCounter=null;function hintEmittedCounter(){return _hintEmittedCounter||=getMeter().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of preview-attach hints emitted on write-tool responses when no editor is attached to __system__. Covers both attach-preview-once (URL exists, no browser) and start-ui (no UI running anywhere) variants — the tool side disambiguates via the warning action; the metric name is retained as-is so existing dashboards keep working.`}),_hintEmittedCounter}let _agentPatchFmTouchCounter=null;function agentPatchFmTouchCounter(){return _agentPatchFmTouchCounter||=getMeter().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:`Count of agent-patch calls whose find string targets the frontmatter region. Measures incidence during the soft-deprecation window before agent-patch FM-intersecting calls are enforced as 400. Bounded label: result ∈ {rejected, pre_deprecation_passthrough}.`}),_agentPatchFmTouchCounter}function findLooksLikeFrontmatter(e){return!!(/(^|\n)---(\s|\n|$)/.test(e)||/^\s*[\w-]+:\s+\S/.test(e))}let _renameAttributionCounter=null;function renameAttributionCounter(){return _renameAttributionCounter||=getMeter().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),_renameAttributionCounter}let _agentWriteGateFiredCounter=null;function agentWriteGateFiredCounter(){return _agentWriteGateFiredCounter||=getMeter().createCounter(`ok.agent_write.gate_fired_total`,{description:`Count of agent writes that ran the Site A content-divergence gate (denominator for the divergence rate). Bounded label: handler ∈ {agent-write-md, agent-patch, rollback}.`}),_agentWriteGateFiredCounter}let _agentWriteContentDivergenceCounter=null;function agentWriteContentDivergenceCounter(){return _agentWriteContentDivergenceCounter||=getMeter().createCounter(`ok.agent_write.content_divergence_total`,{description:`Count of agent writes whose converged Y.Text diverged from the composed intent (numerator for the divergence rate). Bounded labels: handler ∈ {agent-write-md, agent-patch, rollback}, divergence_type.`}),_agentWriteContentDivergenceCounter}function recordContentDivergenceGate(e,t){agentWriteGateFiredCounter().add(1,{handler:e}),t!==void 0&&agentWriteContentDivergenceCounter().add(1,{handler:e,divergence_type:t.divergenceType})}function resumeSyncOnAuthEvent(e,t){e.type===`complete`&&t?.()?.notifyCredentialsChanged().catch(()=>{})}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$4=getLogger(`api`);function ytextHasConflictMarkers(e){return/^<{7} /m.test(e)&&/^={7}$/m.test(e)&&/^>{7} /m.test(e)}function safeDocPath(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let s=t===`.`?``:t.replace(/^\.\//,``),g=getDocExtension(e);return{path:s?`${s}/${e}${g}`:`${e}${g}`}}const GENERIC_PASTE_NAMES=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i,SAFE_FILENAME_CHARS=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,STRIP_ON_SIGHT=/[/\\\x00-\x1f\x7f]/g;function sanitizeFilename(e){let t=e.replace(STRIP_ON_SIGHT,``);if(t=t.replace(SAFE_FILENAME_CHARS,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let s=255,g=new TextEncoder;if(g.encode(t).length>255){let e=t.lastIndexOf(`.`),s=e>=0?t.slice(e):``,S=e>=0?t.slice(0,e):t;for(;g.encode(S+s).length>255&&S.length>0;)S=S.slice(0,-1);t=(S||`upload`)+s,g.encode(t).length>255&&(t=`upload`)}return t}function resolveUploadDestDir(e,t,s){let g=t.trim();return g===``||g===`./`?resolve(s,dirname(e)):g===`/`?s:g.startsWith(`./`)?resolve(s,dirname(e),g.slice(2)):resolve(s,g)}function readTempFileHead(e,t){let s=openSync(e,`r`);try{let e=Buffer.alloc(t),g=readSync(s,e,0,t,0);return e.subarray(0,g)}finally{closeSync(s)}}const MAX_DEDUP_SCAN_CANDIDATES=1e3;async function streamingHashFile(e){let t=createHash(`sha256`);return await pipeline(createReadStream(e),t),t.digest(`hex`)}async function findDuplicateAsset(e,t,s){let g;try{g=await readdir(e)}catch{return null}let S=getLogger(`upload`),w=0;for(let E of g){let g=extname(E).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(g))continue;let D=resolve(e,E),O;try{O=await stat$1(D)}catch{continue}if(!O.isFile()||O.size!==s)continue;if(w++,w>MAX_DEDUP_SCAN_CANDIDATES)return S.warn({event:`upload-dedup-skip`,reason:`scan-cap-exceeded`,destDir:e,scanned:MAX_DEDUP_SCAN_CANDIDATES,expectedSize:s},`[upload-dedup] candidate scan exceeded ${MAX_DEDUP_SCAN_CANDIDATES} same-size siblings — degrading to no-dedup for this upload`),null;let k;try{k=await streamingHashFile(D)}catch(e){let t=e.code;t!==`ENOENT`&&S.warn({event:`upload-dedup-skip`,reason:`read-failed`,code:t,entry:E},`[upload-dedup] skipped candidate — read failed`);continue}if(k===t)return E}return null}function readUploadBody(e,t){return new Promise((s,g)=>{let S;try{S=(0,import_lib.default)({headers:e.headers,limits:{files:1,fields:10,fieldSize:2*1024}})}catch(e){g(new UploadWriteError(`urn:ok:error:malformed-upload`,e));return}let w=!1,E=`upload`,D=``,O=``,k,j,F=!1,L=(e,t)=>{if(!w){if(w=!0,k)try{unlinkSync(k)}catch{}g(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},B=classifyUploadErrno;S.on(`field`,(e,t)=>{e===`parentDocName`&&(O=t)}),S.on(`file`,(e,g,S)=>{F=!0,E=S.filename||`upload`,D=S.mimeType||``;let H;try{H=mintTempUploadPath(t)}catch(e){L(B(e),e),g.resume();return}k=H;let q=new HashingPassThrough;pipeline(g,q,createWriteStream(H)).then(()=>{w||(w=!0,s({filename:E,mimeType:D,parentDocName:O,tempPath:H,sha:q.digest(),byteLength:q.byteLength()}))}).catch(e=>{j=e,L(B(e),e)})}),S.on(`error`,e=>{L(`urn:ok:error:malformed-upload`,e)}),S.on(`close`,()=>{w||j||F||(w=!0,s({filename:``,mimeType:``,parentDocName:O,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{w||j||e.complete||L(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(S)})}function safeSubdir(e,t){let s=resolve(e,t);if(s!==e&&!s.startsWith(`${e}/`))throw Error(`Invalid directory: ${t}`);return s}function synthesizeShowAllAssetExt(e){let t=extname(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}const DEFAULT_SHOWALL_MAX_ENTRIES=5e4;function getShowAllMaxEntries(){let e=process.env.OK_SHOWALL_MAX_ENTRIES;if(e===void 0)return DEFAULT_SHOWALL_MAX_ENTRIES;let t=Number(e);return Number.isInteger(t)&&t>0?t:DEFAULT_SHOWALL_MAX_ENTRIES}let showAllWalkInvocations=0,showAllWalkAborts=0;function __getShowAllWalkStatsForTesting(){return{invocations:showAllWalkInvocations,aborts:showAllWalkAborts}}function __resetShowAllWalkStatsForTesting(){showAllWalkInvocations=0,showAllWalkAborts=0}function showAllWantsNdjson(e){let t=e.headers.accept;return typeof t==`string`&&t.includes(`application/x-ndjson`)}async function*streamShowAllEntries(e){let{contentDir:t,contentFilter:s,dirFilter:g,getDocExtension:S,maxEntries:w,signal:E}=e,D=e.maxDepth??1/0;showAllWalkInvocations+=1;let O=0,k=!1,j=!1,F=e=>g?e===g||e.startsWith(`${g}/`):!0,L;try{L=await realpath(t)}catch{L=t}let B=e=>e===L?!0:e.startsWith(`${L}/`);async function H(e,t){let g;try{g=await readdir(e,{withFileTypes:!0})}catch(t){return console.warn(`[document-list][showAll] probe readdir failed for ${e}:`,t),!1}for(let S of g){let g=t?`${t}/${S.name}`:S.name;if(S.isDirectory()){if(s.isDirExcluded(g,{bypassFilters:!0}))continue;try{if(!B(await realpath(`${e}/${S.name}`)))continue}catch{continue}return!0}if(S.isFile()&&!s.isExcluded(g,{bypassFilters:!0}))return!0}return!1}async function*q(e,t,g){let L;try{L=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[document-list][showAll] readdir failed for ${e}:`,t);return}for(let ee of L){if(E?.aborted){j=!0;return}if(O>=w){k=!0;return}let L=t?`${t}/${ee.name}`:ee.name;if(ee.isDirectory()){if(s.isDirExcluded(L,{bypassFilters:!0}))continue;let t=`${e}/${ee.name}`,S;try{S=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!B(S)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${S}`);continue}if(F(L)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}O+=1;let s=g>=D?await H(t,L):void 0;yield{kind:`folder`,path:L,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null,...s===void 0?{}:{hasChildren:s}}}g<D&&(yield*q(t,L,g+1));continue}if(!ee.isFile()||s.isExcluded(L,{bypassFilters:!0})||!F(L))continue;let J=null;try{J=await stat$1(`${e}/${ee.name}`)}catch(t){console.warn(`[document-list][showAll] stat failed for ${e}/${ee.name}:`,t);continue}if(isSupportedDocFile(ee.name)){let e=L.replace(/\.(md|mdx)$/i,``),t=S(e);O+=1,yield{kind:`document`,docName:e,docExt:t,size:J.size,modified:J.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let Y=synthesizeShowAllAssetExt(ee.name),te=mediaKindForSidebarAssetExtension(Y);O+=1,yield{kind:`asset`,docName:L,docExt:Y,path:L,assetExt:Y,mediaKind:te,referencedBy:[],size:J.size,modified:J.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null}}}return yield*q(g?`${t}/${g}`:t,g??``,1),j&&(showAllWalkAborts+=1),{truncated:k}}async function walkContentDirForShowAll(e){let{documents:t,...s}=e,g=streamShowAllEntries(s),S=await g.next();for(;!S.done;)t.push(S.value),S=await g.next();return S.value}function isValidRelativeContentPath(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function isReservedProjectStatePath(e){return e===`.ok`||e.startsWith(`.ok/`)||e===`.git`||e.startsWith(`.git/`)}function isReservedSyntheticFolderPath(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function listAffectedDocNames(e,t,s){let g=[...e.keys()].filter(e=>t===`file`?e===s:e===s||e.startsWith(`${s}/`));return g.sort((e,t)=>e.localeCompare(t)),g}function remapDocNameForRename(e,t,s,g){return t===`file`||e===s?g:`${g}${e.slice(s.length)}`}function requireNonEmptyDocName(e,t,s){return e!==void 0&&e.length>0?e:(errorResponse(t,400,`urn:ok:error:invalid-request`,"`docName` must be a non-empty document name.",{handler:s}),null)}function assertNoSymlinkEscape(e,t){let s;try{s=realpathSync(t)}catch(e){throw e.code===`ENOENT`?new SymlinkEscapeError(`content directory does not exist`):e}let g=e;for(;;)try{if(!isWithinContentDir(realpathSync(g),s))throw new SymlinkEscapeError(`path resolves outside content directory`);return}catch(e){let s=e.code;if(s===`ELOOP`)throw new SymlinkEscapeError(`symlink cycle in path`);if(s!==`ENOENT`)throw e;let S=dirname(g);if(S===g||S!==t&&!S.startsWith(`${t}${sep}`))throw e;g=S}}function resolveContentEntryPath(e,t,s){if(!isValidRelativeContentPath(s))throw Error(`path must be a relative content path`);let g=resolve(e),S=resolve(g,t===`file`?isSupportedDocFile(s)?s:`${s}${getDocExtension(s)}`:s);if(S!==g&&!S.startsWith(`${g}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(S,g),S}function splitContentPath(e){let t=e.lastIndexOf(`/`);return t===-1?{parent:``,basename:e}:{parent:e.slice(0,t),basename:e.slice(t+1)}}function joinContentPath(e,t){return e?`${e}/${t}`:t}function duplicateBasename(e,t){return t===1?`${e} copy`:`${e} copy ${t}`}var DuplicateNameExhaustedError=class extends Error{constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};function isAlreadyExistsError(e){let t=e.code;return t===`EEXIST`||t===`ERR_FS_CP_EEXIST`}function classifyDuplicatePathFilesystemProblem(e){let t=e.code;return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function docNameExistsWithAnySupportedExtension(e,t){return SUPPORTED_DOC_EXTENSIONS.some(s=>existsSync(resolve(e,`${t}${s}`)))}function resolveDuplicateDocPath(e,t,s){if(!isValidRelativeContentPath(t))throw Error(`path must be a relative content path`);let g=resolve(e),S=resolve(g,`${t}${s}`);if(S!==g&&!S.startsWith(`${g}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(S,g),S}function nextAvailableDuplicateDocName(e,t){let{parent:s,basename:g}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let S=joinContentPath(s,duplicateBasename(g,t));if(!docNameExistsWithAnySupportedExtension(e,S))return{docName:S,attempt:t}}throw new DuplicateNameExhaustedError(t)}function nextAvailableDuplicateFolderPath(e,t){let{parent:s,basename:g}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let S=joinContentPath(s,duplicateBasename(g,t));if(!existsSync(resolveContentEntryPath(e,`folder`,S)))return{folderPath:S,attempt:t}}throw new DuplicateNameExhaustedError(t)}function collectMarkdownCopies(e,t){let s=resolveContentEntryPath(e,`folder`,t),g=[];function S(e,t){for(let s of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,s.name),E=t?`${t}/${s.name}`:s.name;if(s.isDirectory()){S(w,E);continue}!s.isFile()||!isSupportedDocFile(E)||g.push({docName:stripDocExtension(E),fullPath:w,content:readFileSync(w,`utf-8`)})}}return S(s,t),g.sort((e,t)=>e.docName.localeCompare(t.docName)),g}function collectFolderPaths(e,t){let s=resolveContentEntryPath(e,`folder`,t),g=[t];function S(e,t){for(let s of readdirSync(e,{withFileTypes:!0})){if(!s.isDirectory())continue;let w=resolve(e,s.name),E=t?`${t}/${s.name}`:s.name;g.push(E),S(w,E)}}return S(s,t),g.sort((e,t)=>e.localeCompare(t)),g}function probeAndRegisterSourceFileExtension(e,t){if(!isValidRelativeContentPath(t))return;let s=resolve(e);for(let e of SUPPORTED_DOC_EXTENSIONS){let g=resolve(s,`${t}${e}`);if(!(g!==s&&!g.startsWith(`${s}${sep}`))&&existsSync(g)){registerDocExtension(t,e);return}}}function toGitRelativePath(e,t){let s=resolve(e),g=resolve(t);return g!==s&&!g.startsWith(`${s}${sep}`)?null:relative(s,g).split(sep).join(`/`)}function stringsDifferOnlyByCase(e,t){return e!==t&&e.toLowerCase()===t.toLowerCase()}function pathsDifferOnlyByCase(e,t){return stringsDifferOnlyByCase(resolve(e),resolve(t))}function isCaseOnlySelfCollision(e,t){if(!pathsDifferOnlyByCase(e,t)||!existsSync(e)||!existsSync(t))return!1;try{let s=statSync(e),g=statSync(t);return s.dev===g.dev&&s.ino===g.ino}catch{return!1}}function createCaseOnlyRenameTempPath(e){let t=dirname(e);for(let e=0;e<10;e+=1){let e=resolve(t,`.ok-case-rename-${randomUUID()}`);if(!existsSync(e))return e}throw Error(`Unable to allocate temporary path for case-only rename`)}function renamePathOnDisk(e,t){if(tracedMkdirSync(dirname(t),{recursive:!0}),!pathsDifferOnlyByCase(e,t)){tracedRenameSync(e,t);return}let s=createCaseOnlyRenameTempPath(e);tracedRenameSync(e,s);try{tracedRenameSync(s,t)}catch(t){try{let t=existsSync(s),g=existsSync(e);t&&!g?tracedRenameSync(s,e):console.warn(`[renamePathOnDisk] skipped case-only rollback due to unexpected state:`,{tempExists:t,sourceExists:g})}catch(e){console.warn(`[renamePathOnDisk] failed to roll back temporary case-only rename:`,e)}throw t}}async function renameTrackedPathInGit(e,t,s){if(!e)return!1;let g=toGitRelativePath(e,t),S=toGitRelativePath(e,s);return!g||!S?!1:await withParentLock(async()=>{let w=esm_default({baseDir:e,timeout:{block:15e3}}),E=``;try{E=(await w.raw(`ls-files`,`--`,g)).trim()}catch(e){return console.warn(`[renameTrackedPathInGit] git ls-files failed, falling back to fs rename:`,e),!1}if(!E)return!1;mkdirSync(dirname(s),{recursive:!0});let D=!1;try{if(pathsDifferOnlyByCase(t,s)){let s=toGitRelativePath(e,createCaseOnlyRenameTempPath(t));if(!s)return!1;await w.raw(`mv`,`--`,g,s);try{await w.raw(`mv`,`--`,s,S)}catch(e){try{await w.raw(`mv`,`--`,s,g)}catch(e){console.warn(`[renameTrackedPathInGit] case-only git rename failed and rollback also failed; git index and disk may have diverged:`,e),D=!0}throw e}}else await w.raw(`mv`,`--`,g,S);return!0}catch(e){if(D)throw e;return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}const workspaceSearchCaches=new Map;function extractHeadings(e){let t=e;if(e.startsWith(`---
|
|
1703
1703
|
`)||e.startsWith(`---\r
|
|
1704
1704
|
`)){let s=e.indexOf(`
|
|
1705
1705
|
---`,3);s!==-1&&(t=e.slice(s+4))}let s=[],g=new Map,S=createCodeFenceTracker();for(let e of t.split(`
|
|
1706
1706
|
`)){if(S(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),S=getHeadingSlug(e,g);S&&s.push({level:t[1].length,text:e,slug:S})}}return s}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function createApiExtension(e){let{hocuspocus:t,sessionManager:s,contentDir:g,serverInstanceId:S,getFileIndex:w,getFolderIndex:E,onReferencedAssetsCacheInvalidator:D,getAliasMap:O,rescanFiles:k,enableTestRoutes:j=!1,shadowRef:F,flushGitCommit:L,flushContributors:B,takeStoreFailure:H,takeStoreDivergence:q,markAgentWriteStore:ee,getCurrentBranch:J,getDiskAckSVs:Y,contentRoot:te,backlinkIndex:ne,tagIndex:ae,signalChannel:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,onAgentWrite:ue,getSyncEngine:de,localOpCliArgs:fe=[`open-knowledge`],projectDir:me,getPrincipal:ge,contentFilter:_e,installedAgentsProbe:ve,forceUnloadDocument:ye,ready:Ce,recentlyRemovedDocs:we,serializeDoc:Te,semanticSearch:De,embeddingsSecretsFile:je,ephemeral:Me=!1}=e,Pe=createConcurrencyGuard(),Ie=new Map,Re=null;function ze(){let e=E?.();return e instanceof Map?e:null}function Be(e){let t=ze();if(t)try{upsertFolderIndexEntry(t,g,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function Ve(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)Be(resolve(g,t.slice(0,e).join(`/`)))}function Ue(e){let t=ze();t&&removeFolderIndexEntries(t,e)}function We(e,t){let s=ze();if(!s)return;let S=[];for(let[g,w]of s.entries()){if(g!==e&&!g.startsWith(`${e}/`))continue;s.delete(g);let E=g.slice(e.length);S.push([`${t}${E}`,w])}if(S.length===0){let e=resolveContentEntryPath(g,`folder`,t);existsSync(e)&&Be(e);return}for(let[e,t]of S)s.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(g,e)})}function Ge(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
|
|
1707
1707
|
`)}function Ke(){Re=null}D?.(Ke);let Xe=createInstalledAgentsProbe({probe:ve??createOsProbe(process.platform)});function $e(e){if(!isSafeDocName(e))return null;let t=resolve(g),s=resolve(t,`${e}${getDocExtension(e)}`);return!s.startsWith(`${t}/`)&&s!==t?null:s}function nt(e){let t=$e(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function rt(e,t){return t.has(e)?nt(e):e}let it={cluster:void 0,category:void 0,tags:void 0};function at(e){try{let s=t.documents.get(e);if(s){let e=readFmMap(s.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,s=typeof e.category==`string`?e.category:void 0,g;return Array.isArray(e.tags)?g=e.tags.length>0?e.tags:void 0:typeof e.tags==`string`&&e.tags&&(g=[e.tags]),{cluster:t,category:s,tags:g}}}}catch{}try{let t=$e(e);if(!t||!existsSync(t))return it;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):it}catch{return it}}function st(e,t){return t.has(e)?at(e):it}function vt(e){if(ne)try{if(ne.getBacklinks(e).length>0)return;let t=performance.now(),s=findHubCandidates(e,w()),g=performance.now()-t;return g>5&&log$4.debug({docName:e,elapsedMs:g,candidateCount:s.length},`[orphan-hint] findHubCandidates slow`),s.length===0?void 0:[{type:`orphan`,parentCandidates:s,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${s.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function Tt(e){return O?.().get(e)??e}function Et(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function Dt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function jt(e,s){let g=`onStoreDocument-${e}`;(t.debouncer.isDebounced(g)?t.debouncer.executeNow(g):Promise.resolve()).then(()=>L?.()).catch(e=>{log$4.warn({err:e},`[${s}] post-write flush failed`)})}async function Mt(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(ee?.(e),await t.debouncer.executeNow(s));let g=H?.(e)??null;return g?{kind:`failure`,failure:g}:q?.(e)?{kind:`divergence`}:null}function Ft(e,t,s){let g=classifyUploadErrno({code:t.code});errorResponse(e,uploadStatusFor(g),g,`Write applied in memory but failed to persist to disk (${t.code??`unknown error`}): ${t.message}. The content was NOT saved and will be lost if the server restarts.`,{handler:s})}function It(e,t){errorResponse(e,409,`urn:ok:error:disk-divergence`,`The document changed on disk after your edit was prepared; your edit was NOT applied, to avoid overwriting the newer on-disk content. Re-read the document and retry.`,{handler:t})}function Lt(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,hint:'An out-of-band edit was reconciled into this document before your edit was applied on top; the document now reflects that edit plus yours. Re-read it (e.g. `exec("cat <path>")`) to see the combined result before continuing.'}}function Rt(){let e=new Set;for(let[t,s]of w()){e.add(t);for(let t of s.aliases)e.add(t)}return e}function zt(){let e=Promise.resolve();return async function(t){let s=e,g=()=>{};e=new Promise(e=>{g=e}),await s;try{return await t()}finally{g()}}}let Bt=zt(),Vt=e=>e.endsWith(`.`)?e:`${e}.`;function Ht(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Vt(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Vt(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:Vt(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Vt(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Vt(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Vt(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Vt(e.message)}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}}async function Ut(e){let g=new Map;for(let s of e){let e=t.documents.get(s);e&&g.set(s,e.getText(`source`).toString())}for(let t of e)await s.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let s of e){let e=t.documents.get(s);deleteReconciledBase(s),e&&(t.closeConnections(s),await(ye??t.unloadDocument.bind(t))(e))}return g}function Wt(e,t){for(let{fromDocName:s,toDocName:S}of e){let e=safeContentPath(S,g),w=t.get(s);typeof w==`string`&&tracedWriteFileSync(e,w,`utf-8`);let E=typeof w==`string`?w:existsSync(e)?readFileSync(e,`utf-8`):null;typeof E==`string`&®isterWrite(e,contentHash(E))}}function Kt(e,t){return e.map(e=>{let s=t.get(e);if(typeof s==`string`)return{docName:e,content:s};let S=safeContentPath(e,g);if(!existsSync(S))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(S,`utf-8`)}})}function $t(e){let s=t.documents.get(e);if(s)return s.getText(`source`).toString();let S=resolveContentEntryPath(g,`file`,e);return existsSync(S)?readFileSync(S,`utf-8`):null}function en(e,t){let s=resolveContentEntryPath(g,`file`,e);tracedMkdirSync(dirname(s),{recursive:!0}),tracedWriteFileSync(s,t,`utf-8`),registerWrite(s,contentHash(t)),setReconciledBase(e,t);let S=w();S instanceof Map&&updateFileIndex({kind:`update`,path:s,docName:e,content:t},S)}function jr(e,s,g=[]){let S=t.documents.get(e);if(!S)throw Error(`Document is not loaded: ${e}`);let w={markdown:``,rewrites:0};return S.transact(()=>{w=Fr(S.getText(`source`).toString(),e,s.get(e)??e,s,g),w.rewrites!==0&&composeAndWriteRawBody(S,w.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),w}function Mr(e,t,s){let g=e,S=0;for(let{fromPath:e,toPath:w}of s){let s=rewriteAssetReferencesForRename(g,t,e,w);g=s.markdown,S+=s.rewrites}return{markdown:g,rewrites:S}}function Fr(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=Mr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Ir(e,s){let g=t.documents.get(e);if(!g)throw Error(`Document is not loaded: ${e}`);let S={markdown:``,rewrites:0};return g.transact(()=>{S=Mr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Lr(e){let t=[];if(e.length===0)return t;let s=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let g of s){let s=$t(g);if(typeof s!=`string`)continue;let S=Mr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function zr(e){let s=de?.(),g=new Set(s?s.getConflicts().map(e=>e.file):[]);for(let s of e){let e=t.documents.get(s),S=`${s}${getDocExtension(s)}`,w=e!==void 0&&isDocInConflict(e),E=g.has(S);if(w||E)throw new DocInConflictError({file:S})}}function Br(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Ir(S.docName,s):S;e.rewrites!==0&&(en(S.docName,e.markdown),ne?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function Vr(e){if(extname(e))return{path:e,ambiguous:!1};let t=e.lastIndexOf(`/`),s=t===-1?``:e.slice(0,t),S=t===-1?e:e.slice(t+1),w=s?resolveContentEntryPath(g,`folder`,s):g,E;try{E=readdirSync(w,{withFileTypes:!0})}catch(t){let s=t.code;if(s===`ENOENT`||s===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let D=E.filter(e=>e.isFile()&&e.name.startsWith(`${S}.`)).map(e=>s?`${s}/${e.name}`:e.name).filter(e=>isSupportedAssetFile(e,LINKABLE_ASSET_EXTENSIONS));return D.length===1?{path:D[0],ambiguous:!1}:{path:e,ambiguous:D.length>1}}function Hr(e){let t=[];try{if(!statSync(e).isDirectory())return t}catch(e){let s=e.code;if(s===`ENOENT`||s===`ENOTDIR`)return t;throw e}function s(e){for(let S of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,S.name),E=relative(g,w).split(sep).join(`/`);if(isReservedProjectStatePath(E))continue;if(S.isDirectory()){if(_e?.isDirExcluded(E))continue;s(w);continue}if(!S.isFile()||!isSupportedDocFile(E)||_e?.isExcluded(E))continue;let D=stripDocExtension(E);registerDocExtension(D,extname(E)),t.push(D)}}return s(e),t.sort((e,t)=>e.localeCompare(t)),t}function Ur(e,t,s){let S=[];function w(e){for(let E of readdirSync(e,{withFileTypes:!0})){let D=resolve(e,E.name),O=relative(g,D).split(sep).join(`/`);if(!isReservedProjectStatePath(O)){if(E.isDirectory()){if(_e?.isDirExcluded(O))continue;w(D);continue}!E.isFile()||isSupportedDocFile(O)||_e?.isExcluded(O)||(O===t?S.push({fromPath:O,toPath:s}):O.startsWith(`${t}/`)&&S.push({fromPath:O,toPath:`${s}${O.slice(t.length)}`}))}}}return w(e),S.sort((e,t)=>e.fromPath.localeCompare(t.fromPath)),S}async function Wr(e,t){return Bt(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async s=>{if(!ne)throw new BacklinkIndexRequiredError;let S=extname(t)?t:`${t}${extname(e)}`;if(isSupportedDocFile(e)||isSupportedDocFile(S))throw new ManagedRenameInvalidRequestError(`Asset operations do not support markdown documents.`);if(!isSupportedAssetFile(e,LINKABLE_ASSET_EXTENSIONS)||!isSupportedAssetFile(S,LINKABLE_ASSET_EXTENSIONS))throw new ManagedRenameInvalidRequestError(`Asset operations require supported asset extensions.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(S))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(_e?.isPathIgnored(S))throw new ManagedRenameInvalidRequestError(`Destination asset is excluded by the project content config.`);let w=resolveContentEntryPath(g,`folder`,e),E=resolveContentEntryPath(g,`folder`,S);if(w===E)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,S))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(w))throw new ManagedRenameSourceNotFoundError(`asset`,`Asset does not exist.`);if(existsSync(E))throw new ManagedRenameDestinationExistsError;if(!statSync(w).isFile())throw new ManagedRenameSourceTypeMismatchError(`asset`,`Source path is not an asset file.`);let D=[{fromPath:e,toPath:S}],O=Lr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),zr(O.map(e=>e.docName)),await renameTrackedPathInGit(me,w,E)||renamePathOnDisk(w,E);let k=Br(O,D);return ne.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${S}:`,t)}),oe?.(`files`),k.length>0&&(oe?.(`backlinks`),oe?.(`graph`)),k.sort((e,t)=>e.docName.localeCompare(t.docName)),s.setAttribute(`rename.rewrite_count`,k.length),{renamedAssets:D,rewrittenDocs:k}}))}async function Gr(e,s,S,E){return Bt(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":S}},async D=>{if(!ne)throw new BacklinkIndexRequiredError;let O=resolveContentEntryPath(g,S,e),k=resolveContentEntryPath(g,S,s);if(O===k)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(O))throw new ManagedRenameSourceNotFoundError(S);if(existsSync(k)&&!isCaseOnlySelfCollision(O,k))throw new ManagedRenameDestinationExistsError;let j=statSync(O);if(S===`file`&&!j.isFile()||S===`folder`&&!j.isDirectory())throw new ManagedRenameSourceTypeMismatchError(S);let L=S===`folder`?Ur(O,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[stripDocExtension(e)]:Hr(O)).map(t=>({from:t,to:S===`file`?stripDocExtension(s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=Lr(L);zr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(me,O,k)||renamePathOnDisk(O,k),We(e,s),oe?.(`files`)),g.push(...Br(t,L)),g.length>0&&(ne.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),oe?.(`backlinks`),oe?.(`graph`)),g.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:L,rewrittenDocs:g}}let H=buildRenameMap(B),q=B.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),ee=new Set;for(let{from:e}of B)for(let t of ne.getBacklinks(e))H.has(t.source)||ee.add(t.source);let Y=[...ee].sort((e,t)=>e.localeCompare(t)),te=new Map,ae=new Set,se=new Set,ce=[];for(let e of[...H.keys(),...Y]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){ce.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=$t(e);typeof s==`string`?(te.set(e,s),H.has(e)||ae.add(e)):H.has(e)||ce.push(e)}if(L.length>0){let e=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=te.get(t)??$t(t);typeof e==`string`&&Fr(e,t,H.get(t)??t,H,L).rewrites!==0&&(te.has(t)||te.set(t,e),se.add(t),H.has(t)||ae.add(t))}}zr(se);for(let{from:e}of B)if(typeof te.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ue=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[...B],snapshots:Kt([...te.keys()],te)}),de=[],fe=[...ae].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(me??g,ue,async()=>{for(let e of ce)ne.deleteDocument(e);for(let e of fe){let s=t.documents.get(e)?jr(e,H,L):Fr(te.get(e)??``,e,e,H,L);s.rewrites>0&&(en(e,s.markdown),de.push({docName:e,rewrites:s.rewrites})),ne.updateDocumentFromMarkdown(e,s.markdown)}if(we)for(let{from:e,to:t}of B)isSystemDoc(e)||isConfigDoc(e)||(we.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let D=resolveContentEntryPath(g,S,e),O=resolveContentEntryPath(g,S,s);await renameTrackedPathInGit(me,D,O)||renamePathOnDisk(D,O),S===`folder`&&We(e,s);let k=await Ut([...H.keys()]);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(F?.current){let e=F.current;withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},t=>{let s=randomUUID(),g=new Date().toISOString(),w=J?.()??`main`,D=getOrLoadRenameLogIndex(e.gitDir),O=E?.actor?{writerId:E.actor.writerId,displayName:E.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},k=0;for(let{from:t,to:j}of B){let F={v:1,from:t,to:j,at:g,commitSha:``,branch:w,groupId:s,kind:S,actor:O};appendRenameLogEntry(e.gitDir,F,D,e),k+=1,E?.actor?recordContributor(j,E.actor.writerId,E.actor.displayName,E.actor.colorSeed,formatRenameSubject(t,j),E.actor.actorMetadata,void 0,[{from:t,to:j}]):recordContributor(j,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(t,j),void 0,void 0,[{from:t,to:j}])}t.setAttribute(`rename.entries_appended`,k)})}let j=S===`file`&&isSupportedDocFile(s)?extname(s):null;for(let{from:e,to:t}of B){let s=getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,j??s)}let q=[...B].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of q){let s=resolveContentEntryPath(g,`file`,e),S=resolveContentEntryPath(g,`file`,t),E=Fr(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Wt([{fromDocName:e,toDocName:t}],new Map([[e,E.markdown]])),setReconciledBase(t,E.markdown);let D=w();D instanceof Map&&updateFileIndex({kind:`rename`,oldPath:s,newPath:S,oldDocName:e,newDocName:t,content:E.markdown},D),ne.renameDocument(e,t,E.markdown),E.rewrites>0&&de.push({docName:t,rewrites:E.rewrites})}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),ne.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),oe?.(`files`),oe?.(`backlinks`),oe?.(`graph`),de.sort((e,t)=>e.docName.localeCompare(t.docName)),D.setAttribute(`rename.rewrite_count`,de.length),{renamed:q,renamedAssets:L,rewrittenDocs:de}}))}function Kr(e){let t=parseAgentBodyFields(e),s=t.writerId??`claude-1`;return{rawAgentId:t.rawAgentId,agentId:s,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??s,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function qr(e){return{principalId:ge?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Jr(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function Yr(e){return{value:e.value}}function Xr(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Zr(e,t,s,g){if(s.length!==0)switch(e.kind){case`agent`:{let g=e.summary.kind===`value`,S=g?e.summary:normalizeSummary(t),w=Jr(S),E=g||!w.response?w.response:Yr(w.response);for(let t=0;t<s.length;t++){let{docName:g,subject:S}=s[t];recordContributor(g,e.writerId,e.displayName,e.colorSeed,S,e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),Xr(S,!g);for(let{docName:e}of s)jt(e,`rename-path`);return E}case`principal`:{let t=Jr(e.summary);for(let g=0;g<s.length;g++){let{docName:S,subject:w}=s[g];recordContributor(S,e.writerId,e.displayName,e.colorSeed,w,e.actor,g===0?t.stored:void 0)}Xr(e.summary,!1);for(let{docName:e}of s)jt(e,`rename-path`);return t.response}case`anonymous`:g.onAnonymous?.();return;default:{let t=e;throw Error(`Unhandled actor kind in ${g.context}: ${String(t.kind)}`)}}}function Qr(e,t,s){let g=t.replace(/\/$/,``),S=g===``?``:`${g}/`;return e===`template`?`${S}.ok/templates/${s}`:e===`folder-frontmatter`?`${S}.ok/frontmatter`:g===``?`.`:g}function ji(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=Jr(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Hi(e){if(B)try{await B()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let Ui=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=Tt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Kr(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write`});return}let H=normalizeSummary(E.summary),q=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),J=new Date().toISOString(),Y=typeof E.content==`string`?E.content:`Hello from the agent! ${J}`,{response:te,stored:ne}=Jr(H);try{let t=iconFromClientName(F),s=AGENT_ICON_COLORS[t]??colorFromSeed(j??O);ce?.setPresence(O,{displayName:k,icon:t,color:s,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(q.dc.document.getText(`source`),O,j,F),q.dc.document.transact(()=>{applyAgentMarkdownWrite(q.dc.document,`${Y}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),q.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${Y.slice(0,50)}`})},q.origin),recordContributor(D,O,k,j,void 0,qr({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),Xr(H)}finally{ce?.touchMode(O,`idle`)}let ae=await Mt(D);if(ae?.kind===`failure`){Ft(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){It(w,`agent-write`);return}jt(D,`agent-write`),ue?.();let oe=Lt(ee);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:J,...te?{summary:te}:{},...oe?{warning:oe}:{}},{handler:`agent-write`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$4.error({err:e},`[agent-write] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),Gi=withValidation(AgentWriteMdRequestSchema,async(S,w,E)=>{try{let S=E.position??`append`,D=requireNonEmptyDocName(E.docName,w,`agent-write-md`);if(D===null)return;let O=Tt(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Kr(E);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`agent-write-md`});return}E.extension!==void 0&&!docNameExistsWithAnySupportedExtension(g,O)&®isterDocExtension(O,E.extension);let q=normalizeSummary(E.summary),{response:ee,stored:J}=Jr(q),Y=await s.getSession(O,k,{displayName:j,colorSeed:F,clientName:L}),te=reconcileDiskBeforeAgentWrite(t,O,g,e.resolveEmbed),ne=new Date().toISOString(),ae;try{let t=iconFromClientName(L),s=AGENT_ICON_COLORS[t]??colorFromSeed(F??k);ce?.setPresence(k,{displayName:j,icon:t,color:s,currentDoc:O,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),k,F,L),Y.dc.document.transact(()=>{ae=applyAgentMarkdownWrite(Y.dc.document,E.markdown,S,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0),Y.dc.document.getMap(`agent-flash`).set(k,{agentId:k,timestamp:Date.now(),type:`insert`,description:`Added (${j}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),ae!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:S,intendedBytes:ae.intendedBytes,actualBytes:ae.actualBytes,byteDelta:ae.byteDelta,"agent.id":k,"agent.client_name":L})),recordContentDivergenceGate(`agent-write-md`,ae),recordContributor(O,k,j,F,void 0,qr({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),Xr(q)}finally{ce?.touchMode(k,`idle`)}let oe=await Mt(O);if(oe?.kind===`failure`){Ft(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){It(w,`agent-write-md`);return}jt(O,`agent-write-md`),se?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),ue?.();let de=vt(O),fe=Et(O),me=Dt();me===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let ge=Lt(te);successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:fe,systemSubscriberCount:me,...de?{hints:de}:{},...ee?{summary:ee}:{},...ae===void 0?ge?{warning:ge}:{}:{warning:toContentDivergenceWarning(ae)}},{handler:`agent-write-md`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write-md`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write-md`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write-md`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$4.error({err:e},`[agent-write-md] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:e})}},{handler:`agent-write-md`,method:`POST`}),Ki=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=Tt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Kr(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let H=E.patch??{},q=Object.keys(H),ee=normalizeSummary(E.summary),{response:J,stored:Y}=Jr(ee),te=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ne=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),ae=new Date().toISOString(),oe,de=!1,fe=!1,me=[];try{let e=iconFromClientName(F),t=AGENT_ICON_COLORS[e]??colorFromSeed(j??O);ce?.setPresence(O,{displayName:k,icon:e,color:t,currentDoc:D,mode:`writing`,ts:Date.now()}),withSpanSync(`ok.frontmatter_patch`,{attributes:{"doc.name":D,"frontmatter_patch.keys":q.length}},()=>{te.dc.document.transact(()=>{let{fenced:e,body:t}=detectFmRegion(te.dc.document.getText(`source`).toString()),s=applyPatchToFm(e,H);if(!s.ok){oe=s.error;return}for(let e of Object.keys(H))me.push(e);if(s.nextFenced!==e){let g=e===``&&t!==``&&!t.startsWith(`
|
|
1708
1708
|
`),S=s.nextFenced+(g?`
|
|
1709
|
-
`:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),fe=!0}de=!0},te.origin)})}finally{ce?.touchMode(O,`idle`)}if(oe){let e;switch(oe.kind){case`invalid_value`:e={[oe.key]:oe.reason};break;case`reserved_key`:e={[oe.key]:`'${oe.key}' is reserved`};break;case`unknown_key`:e={[oe.key]:`'${oe.key}' is not a recognized key`};break;case`duplicate_target`:e={[oe.key]:`'${oe.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${oe.expected.join(`, `)}; got: ${oe.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${oe.bytes} > ${oe.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${oe.reason}`};break;default:e={__region__:`unhandled frontmatter edit error (${String(oe)})`}}errorResponse(w,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(de&&me.length>0){if(recordContributor(D,O,k,j,void 0,qr({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),Xr(ee),fe){let e=await Mt(D);if(e?.kind===`failure`){Ft(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){It(w,`frontmatter-patch`);return}}jt(D,`frontmatter-patch`)}se?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),ue?.();let ge=Et(D),_e=Dt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=Lt(ne);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:ge,systemSubscriberCount:_e,appliedKeys:me,...J?{summary:J}:{},...ve?{warning:ve}:{}},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$4.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Yi(e){let t=e.getMap(`lifecycle`),s=t.get(`status`);if(typeof s!=`string`||s.length===0)return null;let g=t.get(`reason`);return{status:s,reason:typeof g==`string`?g:``}}let Xi=withValidation(EmptyRequestSchema,async(e,s)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(S)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let w=Tt(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`document-read`});return}let E=t.documents.get(w);if(E){successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:E.getText(`source`).toString(),lifecycle:Yi(E)},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(g,`file`,w))){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document not found: ${w}.`,{handler:`document-read`});return}let D=await t.openDirectConnection(w);try{let e=D.document;if(!e){errorResponse(s,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:e.getText(`source`).toString(),lifecycle:Yi(e)},{handler:`document-read`})}finally{await D.disconnect()}}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Zi=withValidation(EmptyRequestSchema,async(e,t)=>{try{Ce&&await Ce.catch(e=>{log$4.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=s.searchParams.get(`dir`),D=s.searchParams.get(`showAll`)===`true`,O=s.searchParams.get(`depth`)===`1`?1:1/0;if(S)try{safeSubdir(g,S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(D&&_e&&showAllWantsNdjson(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let s=createStreamingErrorWriter(t,`document-list`),w=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let s=()=>{t.off(`drain`,s),t.off(`close`,s),e()};t.once(`drain`,s),t.once(`close`,s)})};try{let t=getShowAllMaxEntries(),s=streamShowAllEntries({contentDir:g,contentFilter:_e,dirFilter:S,getDocExtension,maxEntries:t,maxDepth:O,signal:e.signal}),E=0,D=await s.next();for(;!D.done;)await w(`${JSON.stringify(D.value)}\n`),E+=1,D=await s.next();let{truncated:k}=D.value;k&&log$4.info({handler:`document-list`,maxEntries:t,count:E},`[document-list][showAll] stream truncated at entry cap`),await w(`${JSON.stringify({type:`complete`,truncated:k,count:E})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?s(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):log$4.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(D&&_e){let e=`showAll:${O===1?`d1:`:``}${S??``}`,s=Ie.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:_e,dirFilter:S,documents:e,getDocExtension,maxEntries:s,maxDepth:O,signal:t.signal});return e.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),w&&log$4.info({handler:`document-list`,maxEntries:s,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:w}})();s={promise:w,controller:t,waiters:0};let E=s;Ie.set(e,E),w.finally(()=>{Ie.get(e)===E&&Ie.delete(e)})}let w=s;w.waiters+=1;let E=!1,D=()=>{t.writableEnded||E||(E=!0,--w.waiters,w.waiters<=0&&(w.controller.abort(),Ie.get(e)===w&&Ie.delete(e)))};t.on(`close`,D);try{let{documents:e,truncated:s}=await w.promise;if(E)return;successResponse(t,200,DocumentListSuccessSchema,s?{documents:e,truncated:s}:{documents:e},{handler:`document-list`})}catch(e){if(E)return;errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,D)}return}let k=w(),j=E?.()??new Map,F=[];for(let[e,t]of j)S&&!e.startsWith(`${S}/`)&&e!==S||F.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let[e,t]of k){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);F.push({kind:`document`,docName:e,docExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let w of t.aliases){if(S&&!w.startsWith(`${S}/`)&&w!==S)continue;let E=relative(g,t.canonicalPath);F.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}}let L=[];try{let e=Ge(k);Re?.signature!==e&&(Re={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:k,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:_e?e=>_e.isPathIgnored(e):void 0})}),L=Re?.assets??[]}catch(e){Re=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}for(let e of L)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||F.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});F.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),successResponse(t,200,DocumentListSuccessSchema,{documents:F},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),ka=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:s,backlinks:ne.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:nt(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),_s=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let g={};for(let e of s.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(g[t]=ne.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:g},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),xs=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let g=Rt();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ne.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:rt(e.target,g),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),Cs=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`docName`);if(g&&!isSafeDocName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let S=s.searchParams.get(`degrees`);if(S&&!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let w,E;if(S&&g){let e=Number.parseInt(S,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:w,links:E}=ne.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ne.getLinkGraph());let D=Rt();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=st(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:rt(e.docName,D),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:E},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),Ts=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ne.getOrphans([...w().keys()],s).map(e=>({docName:e,title:nt(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),Ds=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),g=s?Number.parseInt(s,10):20,S=Number.isFinite(g)&&g>0?g:20,w=Rt();successResponse(t,200,HubsSuccessSchema,{hubs:ne.getHubs(S).map(e=>({docName:e.docName,title:rt(e.docName,w),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),Os=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(s.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let g=s.length?[...new Set(s.map(e=>Tt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ne.getDeadLinks(Rt(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:nt(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),ks=withValidation(AgentPatchRequestSchema,async(S,w,E)=>{try{let{find:S,replace:D,offset:O}=E,k=requireNonEmptyDocName(E.docName,w,`agent-patch`);if(k===null)return;let j=Tt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Kr(E);if(findLooksLikeFrontmatter(S)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H}),te=reconcileDiskBeforeAgentWrite(t,j,g,e.resolveEmbed),ne=new Date().toISOString(),ae=!1,oe=!1,de=!1,fe;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ce?.setPresence(F,{displayName:L,icon:t,color:s,currentDoc:j,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),F,B,H),Y.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),g=prependFrontmatter(t,s),w=O==null?g.indexOf(S):g.slice(O,O+S.length)===S?O:-1;if(w===-1){O==null?ae=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":j,findLength:S.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(w<t.length){de=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));fe=applyAgentMarkdownWrite(Y.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),Y.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},Y.origin),fe!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:fe.intendedBytes,actualBytes:fe.actualBytes,byteDelta:fe.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!de){let{stored:e}=Jr(J);recordContributor(j,F,L,B,void 0,qr({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),Xr(J),recordContentDivergenceGate(`agent-patch`,fe)}}finally{ce?.touchMode(F,`idle`)}if(oe){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ae){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(de){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let me=await Mt(j);if(me?.kind===`failure`){Ft(w,me.failure,`agent-patch`);return}if(me?.kind===`divergence`){It(w,`agent-patch`);return}jt(j,`agent-patch`),se?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),ue?.();let ge=Et(j),_e=Dt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=Jr(J),ye=Lt(te);successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:ge,systemSubscriberCount:_e,...ve?{summary:ve}:{},...fe===void 0?ye?{warning:ye}:{}:{warning:toContentDivergenceWarning(fe)}},{handler:`agent-patch`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-patch`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-patch`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$4.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),As=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=Tt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Kr(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(g,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:L}=S,B=S.scope===`session`||S.scope===`file`?`session`:`last`;if(!s.hasSession(w,L)){errorResponse(g,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let H=await s.getSession(w,L),q=!1;try{let t=iconFromClientName(k),s=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);ce?.setPresence(E,{displayName:D,icon:t,color:s,currentDoc:w,mode:`writing`,ts:Date.now()}),q=applyAgentUndo(H,B,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:w}:void 0),q&&recordContributor(w,L,D,O,void 0,qr({clientName:k,clientVersion:j,label:F}))}finally{ce?.touchMode(E,`idle`)}if(q){let e=await Mt(w);if(e?.kind===`failure`){Ft(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){It(g,`agent-undo`);return}jt(w,`agent-undo`)}se?.setFocus(L,{agentName:L,currentDoc:w,writeKind:`undo`,ts:Date.now()}),successResponse(g,200,AgentUndoSuccessSchema,{docName:w,scope:B,undone:q},{handler:`agent-undo`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(g,e,`agent-undo`);return}log$4.error({err:e},`[agent-undo] handler failed`),errorResponse(g,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),Ns=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(g===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(s,g),{handler:`agent-activity`})}catch(e){log$4.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),Ps=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=validateAgentId(g.searchParams.get(`agentId`)),w=g.searchParams.get(`docName`),E=g.searchParams.get(`stackIndex`);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!w||w.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let D=Tt(w);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!E||Number.isNaN(Number(E))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let O=Number(E);if(!Number.isInteger(O)||O<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let k=s.getLiveSession(D,S);if(!k){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let j=k.um;if(O>=j.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${O} out of range (stack has ${j.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let F=j.undoStack[O];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(F,k.dc.document.getText(`source`),D),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$4.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),Is=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=Tt(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$4.error({err:e,docName:E},`[test-reset] safeContentPath rejected docName`),errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(E),t.closeConnections(E);let O=`onStoreDocument-${E}`;t.debouncer.isDebounced(O)&&await t.debouncer.executeNow(O);let k=t.documents.get(E);if(k&&await(ye??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ne&&(ne.deleteDocument(E),ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),oe?.(`backlinks`),oe?.(`graph`)),w.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(g,`.okignore`),s=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(s){let e=s.getText(`source`);e.length>0&&s.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),_e&&await _e.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}oe?.(`files`),successResponse(S,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ne.rebuildFromDisk(),ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),oe?.(`backlinks`),oe?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),$s=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!k){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}k(),oe?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),ec=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Kr(s),E=F?.current;if(!E){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let D=/^[a-zA-Z0-9_-]+$/,O=[];if(Array.isArray(s.writers))try{O=s.writers.map(e=>{let t=e.id??`unknown`;if(!D.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}O.length===0&&(O=e===void 0?[SERVICE_WRITER]:[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}]);let k=te??`.`,j=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),L=await saveVersion(E,k,O,`main`,j.kind===`value`?j.value:void 0);getLogger(`history`).info({checkpointRef:L.checkpointRef},`checkpoint`);try{await gcRenameLog(E,getOrLoadRenameLogIndex(E.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:L.checkpointRef},{handler:`save-version`})}catch(e){log$4.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{let s=F?.current;if(!s){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`docName`)??``,w=g.searchParams.get(`folder`),E=g.searchParams.get(`branch`)??J?.()??`main`;if(!S&&w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(E.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(w!==null&&!S){let e=Cl(w,t,`folder`,`history`);if(!e)return;let S=Number(g.searchParams.get(`limit`)??`50`),D=Math.min(200,Number.isFinite(S)?S:50),O=Number(g.searchParams.get(`offset`)??`0`),k=Math.max(0,Number.isFinite(O)?O:0);successResponse(t,200,HistorySuccessSchema,{...await getFolderTimeline(s,e.folderRel,te??`.`,{branch:E,limit:D,offset:k})},{handler:`history`});return}let D=te??`.`,O=safeDocPath(S,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history`});return}let k=Number(g.searchParams.get(`limit`)??`50`),j=Number(g.searchParams.get(`offset`)??`0`),L=Math.min(200,Number.isFinite(k)?k:50),B=Number.isFinite(j)?j:0,H=g.searchParams.get(`type`)??void 0,q=g.searchParams.get(`author`)??void 0,ee=g.searchParams.get(`excludeAuthor`)??void 0,Y=Date.now();try{let e=await getDocumentHistory(s,{docName:S,branch:E,limit:L,offset:B,type:H,author:q,excludeAuthor:ee},D),g=Date.now()-Y;getLogger(`timeline`).info({docName:S,entries:e.entries.length,durationMs:g},`query`),successResponse(t,200,HistorySuccessSchema,{...e},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function nc(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let g=F?.current;if(!g){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,w=te??`.`,E=safeDocPath(S,w);if(`error`in E){errorResponse(t,400,`urn:ok:error:invalid-request`,E.error,{handler:`history-version`});return}let D=shadowGit(g),O=J?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(g,S,s,O,getOrLoadRenameLogIndex(g.gitDir),e=>{let t=safeDocPath(e,w);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let E=await D.raw(`show`,`${s}:${e}`),[k=``,j=``]=(await D.raw(`log`,`-1`,`--format=%aI%x00%an`,s)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:s,content:E,timestamp:k,author:j},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let rc=withValidation(EmptyRequestSchema,async(e,s)=>{let g=F?.current;if(!g){errorResponse(s,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`diff`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),w=S.searchParams.get(`docName`)??``,E=S.searchParams.get(`from`)??``,D=S.searchParams.get(`to`)??``;if(!D||!/^[0-9a-f]{40}$/i.test(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`'to' must be a valid 40-char commit SHA.`,{handler:`diff`});return}let O=te??`.`,k=safeDocPath(w,O);if(`error`in k){errorResponse(s,400,`urn:ok:error:invalid-request`,k.error,{handler:`diff`});return}let j=shadowGit(g),L=J?.()??`main`,B=getOrLoadRenameLogIndex(g.gitDir),H=createAncestorShaSetCache(),q=e=>{let t=safeDocPath(e,O);return`error`in t?`${e}.md`:t.path};try{let e=await resolveDocPathAtCommit(g,w,D,L,B,q,H);if(e===null){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document did not exist at the target version.`,{handler:`diff`});return}let S=await j.raw(`show`,`${D}:${e}`),O;if(E&&/^[0-9a-f]{40}$/i.test(E)){let e=await resolveDocPathAtCommit(g,w,E,L,B,q,H);if(e===null){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document did not exist at the source version.`,{handler:`diff`});return}O=await j.raw(`show`,`${E}:${e}`)}else{let e=t.documents.get(w);if(!e){errorResponse(s,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`diff`});return}O=e.getText(`source`).toString()}let k=stripFrontmatter(O).body,F=stripFrontmatter(S).body,ee=diffLines(k,F),J=[],Y=0,te=0;for(let e of ee){let t=e.value.replace(/\n$/,``).split(`
|
|
1710
|
-
`),s=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)J.push({type:s,text:e});e.added&&(Y+=t.length),e.removed&&(te+=t.length)}successResponse(s,200,DiffSuccessSchema,{lines:J,additions:Y,deletions:te},{handler:`diff`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`diff`,cause:e})}},{handler:`diff`,method:`GET`,skipBodyParse:!0}),ic=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,ge);if(w.kind===`invalid-summary`){errorResponse(g,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let E=t.documents.get(S.docName);if(E&&isDocInConflict(E)){respondDocInConflict(g,new DocInConflictError({file:`${S.docName}${getDocExtension(S.docName)}`}),`rollback`);return}let D=F?.current;if(!D){errorResponse(g,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:O,commitSha:k}=S,j=te??`.`,L=safeDocPath(O,j);if(`error`in L){errorResponse(g,400,`urn:ok:error:invalid-request`,L.error,{handler:`rollback`});return}let B=shadowGit(D),H=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,J?.()??`main`,s,e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path},S);if(E===null){errorResponse(g,404,`urn:ok:error:doc-not-found`,`Commit ${k.slice(0,7)} does not contain document ${O} at any known historical path.`,{handler:`rollback`});return}let F=await B.raw(`show`,`${k}:${E}`),L=new Date().toISOString();await safetyCheckpoint(D,j,{action:`rollback`,context:{docName:O,targetSha:k}});let q=t.documents.get(O);if(!q){errorResponse(g,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let ee=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,Y;q.transact(()=>{replaceRawBody(q,F,ee),Y=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),Y!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:Y.intendedBytes,actualBytes:Y.actualBytes,byteDelta:Y.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,Y);let te;switch(w.kind){case`agent`:{let e=k.slice(0,8),t=w.summary.kind===`value`,s=t?w.summary:normalizeSummary(`Restored to ${e}`),g=Jr(s);te=t||!g.response?g.response:Yr(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),Xr(s,!t);break}case`principal`:{let e=Jr(w.summary);te=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),Xr(w.summary,!1);break}case`anonymous`:log$4.debug({docName:O,commitSha:k.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(w.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:w.kind});let ne=await Mt(O);if(ne?.kind===`failure`){Ft(g,ne.failure,`rollback`);return}if(ne?.kind===`divergence`){It(g,`rollback`);return}jt(O,`rollback`);let ae=Date.now()-H;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ae},`rollback`),w.kind===`agent`&&se?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()}),successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:L,...te?{summary:te}:{},...Y===void 0?{}:{warning:toContentDivergenceWarning(Y)}},{handler:`rollback`})}catch(e){errorResponse(g,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),ac=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$4.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),oc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$4.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),sc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Ce&&await Ce.catch(e=>{log$4.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=Y?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function cc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let s=ge?.()??null;if(!s){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,s,{handler:`principal`})}async function lc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.getPresenceMap()??{},s=Date.now(),g={};for(let[t,S]of Object.entries(e))s-S.ts<2e4&&(g[t]=S);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:g},{handler:`metrics-agent-presence`})}catch(e){log$4.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function uc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let s=embedProbeRing.read();successResponse(t,200,EmbedDetectSuccessSchema,{entries:s,count:s.length,detection:deriveDetection(s[0])},{handler:`embed-detect`})}async function dc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let s=resolve(g),S=s,w=!0;try{S=realpathSync(s)}catch(e){let g=e?.code;if(g===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:s}),w=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:s,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:g??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:S,pathSeparator:sep,symlinkResolved:w},{handler:`workspace`})}let fc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let S=assetContentTypeForPath(s),w=extname(s).slice(1).toLowerCase();if(!S||!ASSET_EXTENSIONS.has(w)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let E=realpathSync(g),D=resolve(E,s),O;try{O=realpathSync(D)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let k;try{k=statSync(O)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let j=toContentRelativePath(E,O);if(j!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(_e?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F=SANDBOXED_HTML_EXTENSIONS.has(w),L={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)||F?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`?L[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:F&&(L[`Content-Security-Policy`]=SANDBOXED_HTML_CSP),t.writeHead(200,L);try{await pipeline(createReadStream(O),t)}catch(e){log$4.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:s,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),pc=1048576,mc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let S=realpathSync(g),w=resolve(S,s),E;try{E=realpathSync(w)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(E,S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let D;try{D=statSync(E)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!D.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(S,E)!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(D.size>pc){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${pc}-byte text-viewer cap.`,{handler:`asset-text`});return}let O=(await readFile$1(E)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(O)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),hc=1440*60*1e3,gc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!F?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(F.current.gitDir,`rescue`);if(existsSync(g))try{let t=readdirSync(g).filter(e=>isSupportedDocFile(e));for(let S of t){let t=resolve(g,S),w=statSync(t);if(e-w.mtimeMs>864e5){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}s.push({docName:stripDocExtension(S),timestamp:w.mtime.toISOString(),size:w.size,source:`flat`})}}catch(e){log$4.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=J?.()??`main`,t=await listRescueCheckpoints(F.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$4.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,s,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),_c=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,ge);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let S=s.path;if(!isSupportedDocFile(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(S.includes(`..`)||S.startsWith(`/`)||S.includes(`\0`)||S.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let E=resolve(g),D=resolve(E,S);if(!D.startsWith(`${E}/`)&&D!==E){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let O=stripDocExtension(S);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`create-page`});return}let k=typeof s.template==`string`?s.template.trim():``,j=``,F;if(k.length>0){if(!/^[A-Za-z0-9_-]+$/.test(k)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let s=S.includes(`/`)?S.slice(0,S.lastIndexOf(`/`)):``,g=resolveTemplatesAvailable(E,s),w=g.find(e=>e.name===k);if(!w){let e=g.length===0?`(none)`:g.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${k}" does not resolve for folder "${s||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let D=resolve(E,w.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${w.path}.`,{handler:`create-page`,cause:e});return}let{body:L}=stripFrontmatter(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=w.scope}mkdirSync(dirname(D),{recursive:!0});try{writeFileSync(D,j,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let L=stripDocExtension(S);switch(we?.delete(L),_e&&_e.incrementMdDir(dirname(L)),registerWrite(D,contentHash(j)),e.kind){case`agent`:case`principal`:recordContributor(L,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}let B=typeof w==`function`?w():null;B instanceof Map&&updateFileIndex({kind:`create`,path:D,docName:L,content:j},B),ne&&(ne.updateDocumentFromMarkdown(L,j),ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),oe?.(`backlinks`),oe?.(`graph`)),oe?.(`files`),F!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:k,templateScope:F,docName:L})),successResponse(t,200,CreatePageSuccessSchema,{docName:L},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),vc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,ge).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=s.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(_e?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let S=resolveContentEntryPath(g,`folder`,e);if(existsSync(S)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(S,{recursive:!0}),Ve(e),oe?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),yc=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,ge);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:E}=S,D=E===`file`?stripDocExtension(S.path):S.path;if(!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(D===`.ok`||D.startsWith(`.ok/`)||E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||E===`folder`&&isReservedSyntheticFolderPath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}E===`file`&&probeAndRegisterSourceFileExtension(g,D);let O=resolveContentEntryPath(g,E,D);if(!existsSync(O)){if(E===`file`){let e=resolveContentEntryPath(g,`folder`,D);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${E}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${E} does not exist.`,{handler:`duplicate-path`});return}let k=statSync(O);if(E===`file`&&!k.isFile()||E===`folder`&&!k.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${E}.`,{handler:`duplicate-path`});return}let j=E===`file`?[D]:Hr(resolveContentEntryPath(g,`folder`,D)),F=de?.(),L=new Set(F?F.getConflicts().map(e=>e.file):[]);for(let e of j){let g=stripDocExtension(e),S=t.documents.get(g),w=`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),D=L.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let B=typeof w==`function`?w():null,H,q=[];if(E===`file`){let e=extname(O);if(H=nextAvailableDuplicateDocName(g,D).docName,isSystemDoc(H)||isConfigDoc(H)||_e?.isExcluded(`${H}${e}`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=resolveDuplicateDocPath(g,H,e),S=readFileSync(O,`utf-8`),w=dirname(t),E=existsSync(w);try{tracedMkdirSync(w,{recursive:!0}),tracedWriteFileSync(t,S,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!E)try{tracedRmdirSync(w)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:w,err:e})}throw e}let k=!1;try{registerDocExtension(H,e),we?.delete(H),_e&&(_e.incrementMdDir(dirname(H)),k=!0),registerWrite(t,contentHash(S)),B instanceof Map&&updateFileIndex({kind:`create`,path:t,docName:H,content:S},B),ne?.updateDocumentFromMarkdown(H,S),q=[H]}catch(e){try{tracedRmSync(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw forgetDocExtension(H),_e&&k&&_e.decrementMdDir(dirname(H)),B instanceof Map&&updateFileIndex({kind:`delete`,path:t,docName:H},B),e}}else{if(H=nextAvailableDuplicateFolderPath(g,D).folderPath,_e?.isDirExcluded(H)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(g,`folder`,H);try{tracedCpSync(O,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(g,H))Ve(e);let e=collectMarkdownCopies(g,H);q=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(t.docName,e),we?.delete(t.docName),_e&&_e.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),B instanceof Map&&updateFileIndex({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content},B),ne?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of q)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}ne&&q.length>0&&(ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),oe?.(`backlinks`),oe?.(`graph`)),oe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:E,path:H,duplicatedDocNames:q},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=classifyDuplicatePathFilesystemProblem(e);if(t){errorResponse(s,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),bc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s||s.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let g=$e(s);if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(g)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:s,headings:extractHeadings(readFileSync(g,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),xc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,ge);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:w,fromPath:E,toPath:D}=S;if(!isValidRelativeContentPath(E)||!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(w===`file`&&(isSystemDoc(E)||isSystemDoc(D)||isConfigDoc(E)||isConfigDoc(D))){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||D===`.ok`||D.startsWith(`.ok/`)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(E===D){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}if(w===`asset`){let t;try{t=await Wr(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=Ht(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=Zr(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$4.debug({kind:`asset`,fromPath:E,toPath:D,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(renameAttributionCounter().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),B)try{await B()}catch(e){console.warn(`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...g?{summary:g}:{}},{handler:`rename-path`});return}let O=w===`file`?[stripDocExtension(E)]:Hr(resolveContentEntryPath(g,`folder`,E)),k=de?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]);for(let e of O){let g=stripDocExtension(e),S=t.documents.get(g),D=w===`file`?E:`${g}${getDocExtension(e)}`,O=S!==void 0&&isDocInConflict(S),k=j.has(D);if(O||k){respondDocInConflict(s,new DocInConflictError({file:D}),`rename-path`);return}}if(w===`file`&&probeAndRegisterSourceFileExtension(g,E),_e&&(w===`file`?_e.isExcluded(isSupportedDocFile(D)?D:`${D}${getDocExtension(E)}`):_e.isDirExcluded(D))){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${w===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let F=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,L;try{L=await Gr(E,D,w,F?{actor:F}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,Vt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(L.renamed.length===0&&L.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}L.renamedAssets.length>0&&Ke();let H;if(L.renamed.length>0&&(H=Zr(e,`Renamed ${E} → ${D}`,L.renamed.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$4.debug({kind:w,fromPath:E,toPath:D,affectedDocs:L.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${w}`,attribution_kind:e.kind}),B)try{await B()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:L.renamed,renamedAssets:L.renamedAssets,rewrittenDocs:L.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=Ht(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Sc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Kr(S);let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let D=e===`asset`?Vr(E):{path:E,ambiguous:!1};if(D.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let O=D.path;if(e===`asset`&&(isSupportedDocFile(O)||isReservedProjectStatePath(O))){errorResponse(s,400,isReservedProjectStatePath(O)?`urn:ok:error:reserved-doc-name`:`urn:ok:error:invalid-request`,isReservedProjectStatePath(O)?`.ok and .git are reserved directories.`:`Asset operations do not support markdown documents.`,{handler:`delete-path`});return}let k=e===`asset`?resolveContentEntryPath(g,`folder`,O):resolveContentEntryPath(g,e,O);if(!existsSync(k)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${e} does not exist.`,{handler:`delete-path`});return}let j=statSync(k);if(e===`file`&&!j.isFile()||e===`asset`&&!j.isFile()||e===`folder`&&!j.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${e}.`,{handler:`delete-path`});return}let F=e===`asset`?[]:e===`file`?[E]:Hr(resolveContentEntryPath(g,`folder`,E)),L=de?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let g of F){let S=stripDocExtension(g),w=t.documents.get(S),E=e===`file`?g:`${S}${getDocExtension(S)}`,D=w!==void 0&&isDocInConflict(w),O=B.has(E);if(D||O){respondDocInConflict(s,new DocInConflictError({file:E}),`delete-path`);return}}if(await Ut(F),we)for(let e of F)isSystemDoc(e)||isConfigDoc(e)||(we.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));e===`file`||e===`asset`?tracedUnlinkSync(k):(tracedRmSync(k,{recursive:!0,force:!1}),Ue(E)),Ke();let H=w();if(H instanceof Map)for(let e of F)updateFileIndex({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e},H);oe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:F},{handler:`delete-path`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Cc=withValidation(TrashCleanupRequestSchema,async(e,t,s)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":s.kind,"ok.cleanup.path":normalizeFsPath(s.path),"ok.cleanup.path.role":classifyFsPath(s.path)}},async()=>{try{if(extractActorIdentity(s,ge).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:S}=s;if(!isValidRelativeContentPath(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let E=e===`folder`&&isReservedSyntheticFolderPath(S),D=e===`asset`&&isReservedProjectStatePath(S),O=e===`asset`&&isSupportedDocFile(S);if(e===`file`&&(isSystemDoc(S)||isConfigDoc(S))||E||D||O){errorResponse(t,400,O?`urn:ok:error:invalid-request`:`urn:ok:error:reserved-doc-name`,O?`Asset operations do not support markdown documents.`:`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(e===`asset`){Ke(),oe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let k=w(),j=e===`file`?k.has(S)?[S]:[]:listAffectedDocNames(k,e,S);if(Ke(),j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Ut(j),we)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(we.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));let F=w();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e},F);e===`folder`&&Ue(S),oe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:j},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),wc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=t,w,E=getDocExtension(t);try{let s=readFileSync(resolve(g,`${t}${E}`),`utf-8`);e=extractPageTitle(s,t),w=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}s.push({docName:t,title:e,docExt:E,size:S.size,modified:S.modified,icon:w})}s.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:s},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Tc=withValidation(EmptyRequestSchema,async(e,s)=>{try{let g=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!g){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(g)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(g)||isConfigDoc(g)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${g}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(s,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:w(),docName:g}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function Ec(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let s;try{s=await readUploadBody(e,me??g)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:S,tempPath:w,sha:E,byteLength:D,parentDocName:O}=s,k=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},j=validateBody(UploadRequestSchema,{parentDocName:O},t,{handler:`upload-asset`});if(!j.ok){k();return}let{parentDocName:F}=j.value,{agentId:L,agentName:B}=Kr(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(D===0){k(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(F.includes(`\0`)||F.includes(`..`)||F.startsWith(`/`)){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let H=resolve(g),q=resolveUploadDestDir(F,`./`,H);if(!isWithinContentDir(q,H)){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(q,H)}catch(e){if(k(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$4.error({err:e,destDir:q},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(q,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){k();let s=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(s),s,uploadTitleFor(s),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(q),s;try{s=realpathSync(H)}catch{s=H}if(!isWithinContentDir(e,s)){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ee=await fileTypeFromFile(w),J=ee?.mime,Y=ee?.ext;if(!J){let e=readTempFileHead(w,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(J=`image/svg+xml`,Y=`svg`)}{let s=await findDuplicateAsset(q,E,D);if(s){k();let S=relative(g,resolve(q,s));log$4.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:L,agentName:B,dedup:!0,mime:J??null,size:D,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let te;if(!S||S===`upload`||GENERIC_PASTE_NAMES.test(S)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=S?extname(S).slice(1):``,s=Y??t??``;te=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else te=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,q,te),S=relative(g,resolve(q,s));log$4.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:L,agentName:B,dedup:!1,mime:J??null,size:D,destPath:S,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!1},{handler:`upload-asset`})}catch(s){let g=s instanceof UploadWriteError?s.reason:`urn:ok:error:storage-error`;log$4.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:L,agentName:B,filename:te,size:D,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Dc=`/api/local-op/clone`,Oc=`/api/local-op/open`,kc=`/api/local-op/ok-init`,Ac=600*1e3,jc=45e3,Mc=`local-op-clone`,Nc=withValidation(LocalOpCloneRequestSchema,Pc,{handler:Mc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Mc})});async function Pc(e,t,s){let{url:g,dir:S,branch:w}=s;if(!isAllowedGitUrl(g)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:Mc,cause:Error(`url=${g}`)});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:Mc,cause:Error(`dir=${S}`)});return}if(!Pe.tryAcquire(Dc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Mc,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Mc),D=null,O=runCloneSubprocess({cliArgs:fe,url:g,dir:S,branch:w,timeoutMs:Ac,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$4.warn({stderr:redactShareSubprocessStderr(e.message),url:g,dir:S},`[local-op/clone] clone failed`);let t=classifyCloneError(e.message??``);E(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(redactShareSubprocessStderr(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await O.done,D&&!t.writableEnded&&!t.destroyed){let e=await Fc(D);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:D})}\n`):E(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?E(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$4.error({err:e,handler:Mc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Pe.release(Dc)}})(),t.on(`close`,()=>{O.cancel()})}async function Fc(e,t){let s=resolve(expandTilde(e)),g=getLocalDir(s),S=readUiLock(g);if(S&&S.port>0)return{port:S.port};let[w,...E]=fe,D=e=>{let s=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...E,e,...s]},O=async e=>{let t=spawn(w,D(e),{cwd:s,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$4.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$4.error({cwd:s,cliCmd:e,err:t.message},`[local-op/open] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let Ic=`local-op-open`,Lc=withValidation(LocalOpOpenRequestSchema,async(e,t,s)=>{let{dir:g,port:S}=s;if(!isSafeLocalPath(g)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`dir must be within the user home directory.`,{handler:Ic,cause:Error(`dir=${g}`)});return}if(!Pe.tryAcquire(Oc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A server-open operation is already in progress.`,{handler:Ic,extraHeaders:{"Retry-After":`5`}});return}try{let e=await Fc(g,S);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:Ic}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:Ic,cause:Error(e.error)})}finally{Pe.release(Oc)}},{handler:Ic,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ic})}),Rc=`local-op-ok-init`,zc=withValidation(LocalOpOkInitRequestSchema,async(e,t,s)=>{let{projectPath:g}=s;if(!isAbsolute(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:Rc,cause:Error(`projectPath=${g}`)});return}let S;try{S=realpathSync(g)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:Rc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Rc,cause:Error(`projectPath=${g}`)});return}let w=resolveGitDirDetailed(S).kind;if(w!==`directory`&&w!==`linked`){console.warn(`[ok-init] action=init project=${basename(S)} result=not-a-git-worktree kind=${w}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${w}).`},{handler:Rc});return}if(isProjectRoot(S)){console.warn(`[ok-init] action=init project=${basename(S)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Rc});return}if(!Pe.tryAcquire(kc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Rc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(S)}),console.warn(`[ok-init] action=init project=${basename(S)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Rc})}catch(e){let s=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(S)} result=failed reason=${s}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:s},{handler:Rc})}finally{Pe.release(kc)}},{handler:Rc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Rc})}),Bc=`/api/local-op/auth/login`,Vc=`/api/local-op/auth/status`,Hc=`/api/local-op/auth/repos`,Uc=`/api/local-op/auth/signout`,Wc=null,Gc=`local-op-auth-login`,Kc=withValidation(LocalOpAuthHostRequestSchema,qc,{handler:Gc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Gc})});async function qc(e,t,s){let g=s.host??`github.com`;if(!Pe.tryAcquire(Bc)){let e=Wc;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:Gc,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),Wc=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,Gc),w=runDeviceFlowSubprocess({cliArgs:fe,host:g,timeoutMs:Ac,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});Wc=w;let E=()=>{w.cancel(),Wc===w&&(Wc=null,Pe.release(Bc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}Wc===w&&(Wc=null,Pe.release(Bc))})}let Jc=`local-op-auth-status`,Yc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Pe.tryAcquire(Vc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Jc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=fe,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,g.kill(`SIGTERM`)},3e4),D=[];g.stdout.on(`data`,e=>D.push(e)),g.on(`close`,()=>{if(clearTimeout(E),w){s(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(D).toString(`utf-8`))}),g.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
|
|
1711
|
-
`).map(e=>e.trim()).filter(Boolean),E=null;for(let e=w.length-1;e>=0;e--)try{E=JSON.parse(w[e]);break}catch{}E===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:Jc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:Jc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Jc,cause:e})}finally{Pe.release(Vc)}},{handler:Jc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Jc})}),Xc=`local-op-auth-repos`,Zc=withValidation(LocalOpAuthHostRequestSchema,Qc,{handler:Xc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Xc})});async function Qc(e,t,s){let g=s.host??`github.com`;if(!Pe.tryAcquire(Hc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Xc,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,Xc),[w,...E]=fe,D=[...E,`auth`,`repos`,`--json`,`--host`,g],O=!1,k=``,j=spawn(w,D,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),F=setTimeout(()=>{j.kill(`SIGTERM`)},Ac);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
|
|
1712
|
-
`);k=s.pop()??``;for(let e of s){if(!e.trim())continue;let s=null;try{s=JSON.parse(e)}catch{}if(s&&s.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof s.message==`string`?s.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),j.stderr.on(`data`,e=>{log$4.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),j.on(`close`,e=>{clearTimeout(F),O||(O=!0,e!==0&&!t.writableEnded&&S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Pe.release(Hc))}),j.on(`error`,e=>{clearTimeout(F),O||(O=!0,t.writableEnded||(S(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Pe.release(Hc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Pe.release(Hc))})}let $c=`local-op-auth-signout`,nl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Pe.tryAcquire(Uc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:$c,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=fe,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,{stdio:`ignore`,env:{...process.env}}),w=setTimeout(()=>{g.kill(`SIGTERM`)},3e4);g.on(`close`,()=>{clearTimeout(w),t()}),g.on(`error`,e=>{clearTimeout(w),s(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:$c})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:$c,cause:e})}finally{Pe.release(Uc)}},{handler:$c,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:$c})}),il=`/api/local-op/auth/set-identity`,al=`local-op-auth-set-identity`,cl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!me){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:al});return}if(!Pe.tryAcquire(il)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:al,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(me,g,S),de?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:al})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:al,cause:e})}finally{Pe.release(il)}},{handler:al,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:al})});async function ll(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=de?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let ul=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=de?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let S=s.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:S},{handler:`sync-trigger`}),g.trigger(S)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?de?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function dl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=de?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let fl=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=de?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:S,strategy:w,content:E}=s;try{await g.resolveConflict(S,w,E),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?de?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function pl(e,s){if(!checkLocalOpSecurity(e,s,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(s,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!me){errorResponse(s,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`file`);if(!S){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=stripDocExtension(S),E=t.documents.get(w)?.getMap(`lifecycle`).get(`status`)===`conflict`,D=de?.(),O=D?D.getConflicts().some(e=>e.file===S):!1;if(!E&&!O){errorResponse(s,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:S}});return}let k=g.searchParams.get(`source`),j=esm_default({baseDir:me,timeout:{block:15e3}});async function F(e){try{return{present:!0,content:await j.raw([`show`,`:${e}:${S}`])}}catch(t){let s=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(s))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:S,detail:s,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,g,w]=await Promise.all([F(1),F(2),F(3)]),E=e.present?e.content:``,D=w.present?w.content:``,O=g.present&&w.present?`both-modified`:!g.present&&w.present?`delete-modify`:g.present&&!w.present?`modify-delete`:`both-modified`,j=g.present?g.content:``,L=null;if(k===`ytext`){let e=stripDocExtension(S),s=t.documents.get(e);if(s){let t=s.getMap(`lifecycle`).get(`status`);if(L=typeof t==`string`&&t.length>0?t:null,O!==`delete-modify`){let t=Te?Te(e):null;t!==null&&!ytextHasConflictMarkers(t)?j=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(s,200,SyncConflictContentSuccessSchema,{file:S,base:E,ours:j,theirs:D,kind:O,lifecycleStatus:L},{handler:`sync-conflict-content`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function ml(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let s=new URL(e.url??`/`,`http://localhost`),S=s.searchParams.get(`rootDir`)??void 0,w=s.searchParams.get(`packId`),E=coercePackId(w);if(w!==null&&w!==``&&E===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${w}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:g,rootDir:S,packId:E})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let hl=withValidation(SeedApplyRequestSchema,async(e,t,s)=>{let S=s.plan;if(!S||typeof S!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let w=S,E=s.packId,D=coercePackId(E);if(typeof E==`string`&&E.length>0&&D===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${E}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(w,{projectDir:g,packId:D})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function gl(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let _l=withValidation(InstallSkillRequestSchema,async(e,t,s)=>{if(s.out!==void 0&&!isSafeLocalPath(s.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...s.noOpen===void 0?{}:{noOpen:s.noOpen},...s.out===void 0?{}:{out:s.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function vl(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Xe.probeAll)}catch(e){t.headersSent||(log$4.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}let yl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ae){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:ae.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function xl(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!ae){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let g;try{g=decodeURIComponent(s)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=ae.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:nt(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:g,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Cl(e,t,s=`path`,S=`folder-config`){let w=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${s}: must be project-root-relative.`,{handler:S}),null;let E=resolve(g),D=w===``?E:resolve(E,w);return D!==E&&!D.startsWith(`${E}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:S}),null):{folderRel:w,resolvedContentDir:E}}let Tl=/^[A-Za-z0-9_-]+$/;function El(e,t,s=`template`){return!e||!Tl.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:s}),!1):!0}function Dl(e,t,s){let g=t===``?[]:t.split(`/`);for(let t=g.length;t>=0;t--){let S=t===0?``:g.slice(0,t).join(`/`),w=S===``?e:resolve(e,S);if(w!==e&&!w.startsWith(`${e}${sep}`))continue;let E=resolve(w,`.ok`,`templates`,`${s}.md`);if(existsSync(E))return{abs:E,folder:S,scope:t===g.length?`local`:`inherited`}}return null}function Ol(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[s,g]of Object.entries(e))g!==void 0&&(t[s]=g);return t}async function kl(e,t){if(e.method===`GET`)return jl(e,t);if(e.method===`PUT`)return Ml(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let jl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Cl(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!s)return;let g=await enrichDirectory(s.folderRel,{projectDir:s.resolvedContentDir}),S=resolve(resolve(s.resolvedContentDir,s.folderRel,`.ok`),`frontmatter.yml`),w=null;if(existsSync(S))try{let e=(0,import_dist$1.parse)(await readFile$1(S,`utf-8`));w=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${S}: ${t}`),w=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:g,frontmatter_local:w},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Ml=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(Me){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,ge);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let g=Cl(s.path,t,`path`,`folder-config-put`);if(!g)return;let S=[];if(s.frontmatter!==void 0){let w=applyFolderFrontmatterPatch({anchorDir:g.resolvedContentDir,folderRel:g.folderRel,patch:s.frontmatter});if(!w.ok){let e=w.error.code===`WRITE_ERROR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push({path:w.path,action:w.action}),w.action!==`noop`&&(ji(e,Qr(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Hi(`folder-config-put`))}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:S},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function Pl(e,s,g,S){if(!s)return!1;let w=e===``?`.ok/templates/${s}`:`${e.replace(/\/$/,``)}/.ok/templates/${s}`,E=t.documents.get(w);return E&&isDocInConflict(E)?(respondDocInConflict(S,new DocInConflictError({file:`${w}.md`}),g),!0):!1}let Fl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=resolveProjectTemplates(resolve(g));successResponse(t,200,TemplatesListSuccessSchema,{templates:e.templates.map(e=>{let{scope:t,...s}=e;return s}),truncated:e.truncated},{handler:`templates-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function Il(e,t){if(e.method===`GET`)return zl(e,t);if(e.method===`PUT`)return Bl(e,t);if(e.method===`POST`)return Hl(e,t);if(e.method===`DELETE`)return Vl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Ll=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Rl=e=>{let t=e.match(Ll),s={},g=e;if(t){try{let e=(0,import_dist$1.parse)(t[1]??``);e&&typeof e==`object`&&!Array.isArray(e)&&(s=e)}catch{}g=e.slice(t[0].length)}return{frontmatter:s,body:g}},zl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!El(g,t,`template-get`))return;let S=Cl(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=Dl(E,w,g);if(!D){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${g}" not found for folder "${w||`.`}". Walked leaf → root.`});return}let{abs:O,folder:k,scope:j}=D,{frontmatter:F,body:L}=Rl(await readFile$1(O,`utf-8`));successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:F,body:L}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),Bl=withValidation(TemplatePutRequestSchema,async(e,t,s)=>{try{if(Me){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(s,ge);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let g=s.name;if(!El(g,t,`template-put`))return;let S=Cl(s.folder,t,`folder`,`template-put`);if(!S||Pl(S.folderRel,g,`template-put`,t))return;let w=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g,body:typeof s.body==`string`?s.body:``,frontmatter:Ol(s.frontmatter)});if(!w.ok){let e=w.error.code===`WRITE_ERROR`||w.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write template.`:`Invalid template request.`,{handler:`template-put`,detail:w.error.code,cause:Error(w.error.message)});return}ji(e,Qr(`template`,S.folderRel,g),`${w.created?`template-create`:`template-edit`}: ${w.path}`),await Hi(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:w.path,created:w.created,warnings:w.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Vl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!El(g,t,`template-delete`))return;let S=Cl(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S)return;let w=s.searchParams,E=extractActorIdentity({agentId:w.get(`agentId`)??void 0,agentName:w.get(`agentName`)??void 0,colorSeed:w.get(`colorSeed`)??void 0,clientName:w.get(`clientName`)??void 0,clientVersion:w.get(`clientVersion`)??void 0,label:w.get(`label`)??void 0,summary:w.get(`summary`)??void 0},ge);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Pl(S.folderRel,g,`template-delete`,t))return;let D=applyTemplateDelete({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}D.existed&&(ji(E,Qr(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Hi(`template-delete`)),successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),Hl=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,ge);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!El(s.fromName,t,`template-move`)||!El(s.toName,t,`template-move`))return;let g=Cl(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Cl(s.toFolder,t,`folder`,`template-move`);if(!S||Pl(g.folderRel,s.fromName,`template-move`,t))return;let w=await applyTemplateMove({projectDir:g.resolvedContentDir,fromFolder:g.folderRel,fromName:s.fromName,toFolder:S.folderRel,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(me,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=Dl(g.resolvedContentDir,g.folderRel,s.fromName);if(e?.scope===`inherited`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${s.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${g.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:w.error.message});return}if(w.error.code===`TEMPLATE_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,w.error.message,{handler:`template-move`,detail:w.error.code});return}let e=w.error.code===`WRITE_ERROR`||w.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:w.error.code,cause:Error(w.error.message)});return}let E=null;if(s.body!==void 0||s.frontmatter!==void 0){let e;if(typeof s.body==`string`)e=s.body;else try{e=Rl(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`)).body}catch{e=null}if(e===null)E={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:s.toName,body:e,frontmatter:Ol(s.frontmatter)});t.ok||(E=t.error)}}if(ji(e,Qr(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Hi(`template-move`),oe?.(`files`),E){let e=E.code===`WRITE_ERROR`||E.code===`READ_FAILED`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${w.toPath}", but updating its content failed.`,{handler:`template-move`,detail:E.code,cause:Error(E.message)});return}successResponse(t,200,TemplateMoveSuccessSchema,{from:w.fromPath,to:w.toPath,committed:w.committed},{handler:`template-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`});function Ul(e){let t=new Map;for(let s of e){let e=s.path.split(`/`).filter(Boolean);e.pop();for(let g=1;g<=e.length;g++){let S=e.slice(0,g).join(`/`);t.set(S,Math.max(t.get(S)??0,s.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function Wl(e,t){let s=t.trim().toLowerCase();if(!s||!e)return;let g=e.toLowerCase().indexOf(s);if(g<0)return;let S=Math.max(0,g-80),w=Math.min(e.length,g+s.length+120),E=S>0?`…`:``,D=w<e.length?`…`:``;return`${E}${e.slice(S,w).replace(/\s+/g,` `).trim()}${D}`}function Gl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Kl(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let s=t.filter(e=>e===`page`||e===`folder`||e===`content`);return s.length>0?s:void 0}function ql(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}async function Jl(e,t,s,g){let S=g.documents.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!De?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:S,capable:!1};De.embedCorpus(g.documents);let w,E=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await De.queryScores(e,g.documents);E=performance.now()-t,s&&s.size>0&&(w={scores:s})}let D=De.getStatus();return{input:w,status:{capable:D.capable,applied:!1,coverage:{embedded:D.embeddedCount,total:S}},queryEmbedMs:E,pageTotal:S,capable:D.capable}}function Yl(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Wl(e.document.content,t):void 0}}async function Xl(e){let t=performance.now(),s=await $l(),g=await Jl(e.query,e.intent,e.semanticParam,s),S=searchWorkspaceCorpus(s,e.query,{intent:e.intent,scopes:e.scopes,limit:e.limit,semantic:g.input}).map(t=>Yl(t,e.query)),w;if(g.status){let e=S.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),t=e>0;w={...g.status,applied:t},recordSemanticQuery({outcome:g.capable?t?`applied`:g.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,capable:g.capable,embedded:g.status.coverage.embedded,total:g.pageTotal,queryEmbedMs:g.queryEmbedMs,vectorContributors:e})}return{query:e.query,intent:e.intent,results:S,elapsedMs:Math.max(0,performance.now()-t),...w?{semantic:w}:{}}}async function Zl(){let e=[];for(let[t,s]of w()){if(isSystemDoc(t)||isConfigDoc(t)||isHiddenDocName(t))continue;let g=``,S=t;try{g=await readFile$1(s.canonicalPath,`utf-8`),S=extractPageTitle(g,t)}catch(e){console.warn(`[search] Failed to index ${t}:`,e)}e.push(createWorkspaceSearchDocument({kind:`page`,path:t,title:S,content:g,modifiedTs:Date.parse(s.modified)}))}return[...e,...Ul(e)]}function Ql(){return[...w()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}${t.modified}${t.size}${t.canonicalPath}${t.inode}${t.aliases.join(`,`)}`).join(``)}async function $l(){let e=`${g}${me??``}`,t=Ql(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return s.corpus;if(s?.fingerprint===t&&s.pending)return s.pending;let S=Zl().then(e=>createWorkspaceSearchCorpus(e));workspaceSearchCaches.set(e,{fingerprint:t,pending:S});try{let s=await S;return workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:s}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function eu(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{$l().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}eu();async function tu(e,t){if(e.method===`GET`)return nu(e,t);if(e.method===`POST`)return ru(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let nu=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Gl(s.searchParams.get(`intent`)),E=Kl(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),D=ql(s.searchParams.get(`semantic`)),O=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await Xl({query:S,intent:w,scopes:E,limit:O,semanticParam:D}),{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),ru=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Gl(s.intent),w=Kl(s.scopes??s.scope),E=typeof s.limit==`number`?s.limit:void 0,D=ql(s.semantic);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await Xl({query:g,intent:S,scopes:w,limit:E,semanticParam:D}),{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),iu=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function au(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$4.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function ou(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$4.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let su=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!me){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidSharePath(s.kind===`doc`?s.docPath:s.folderPath,s.kind)){emitShareConstructUrlLog(`invalid-path`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=readGitHeadBranch(me);if(e===null){if(readOriginGitHubRepo(me).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let S=readOriginGitHubRepo(me);if(S.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(S.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(me,e)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=toGitRelativePath(me,g);if(w===null)throw Error(`content dir is not contained within the project dir`);let E=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;w!==``&&E&&getLogger(`share`).warn({action:`construct-url`,kind:s.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let D;if(s.kind===`doc`)D=buildGitHubBlobUrl(S.owner,S.repo,e,s.docPath);else{let t=s.folderPath===``?w:s.folderPath;D=buildGitHubTreeUrl(S.owner,S.repo,e,t)}let O=`${SHARE_BASE_URL}${encodeShareUrl(D)}`;emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:O,sharedUrl:D,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),cu=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!me){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`branch`),S=s.searchParams.get(`path`),w=s.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!isValidBranchName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoPath(S,w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(me,g,S,w),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),lu=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,ge).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!me){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(me,s.branch)),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function uu(e){let[t,...s]=fe,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,S.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),D=[],O=[];S.stdout.on(`data`,e=>D.push(e)),S.stderr.on(`data`,e=>O.push(e)),S.on(`close`,t=>{if(clearTimeout(E),w){s(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let g=Buffer.concat(D).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(O).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:g,code:t})}),S.on(`error`,e=>{clearTimeout(E),s(e)})})}let du=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Pe.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await uu([`share`,`owners`,`--json`]),s=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,s.ok?`ok`:s.error,s.ok?{count:s.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,s,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{Pe.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),fu=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`owner`)??``,S=s.searchParams.get(`name`)??``;if(!isValidShareOwnerName(g)||!isValidShareRepoName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!Pe.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await uu([`share`,`name-check`,`--owner`,g,`--name`,S,`--json`]),s=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,s.ok?`ok`:s.error,s.ok?{available:s.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,s,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{Pe.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),pu=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!me){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(s.owner)||!isValidShareRepoName(s.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!Pe.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,s.owner,`--name`,s.name,`--visibility`,s.visibility,`--project-dir`,me,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await uu(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&de?.()?.refreshRemote().catch(()=>{}),successResponse(t,200,SharePublishResponseSchema,S,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{Pe.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),mu=withValidation(ClientLogsRequestSchema,async(e,t,s)=>{try{let e=getLogger(`renderer`);for(let t of s.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}successResponse(t,200,ClientLogsSuccessSchema,{accepted:s.entries.length},{handler:`client-logs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`client-logs`})}),hu=me?getLocalDir(me):null;async function gu(e,t){if(e.method===`DELETE`){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-config`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-config`});return}hu&&clearArmedPaneTarget(hu),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:hu?readServerLock(hu)?.port??0:0,paneTarget:hu?readArmedPaneTarget(hu):null,singleFile:Me};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}successResponse(t,200,ApiConfigSuccessSchema,g,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD, DELETE`}})}let _u=`local-op-embeddings-set-key`,vu=`local-op-embeddings-clear-key`,yu=`/api/local-op/embeddings`,bu=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Pe.tryAcquire(yu)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:_u,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(je).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:_u,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:_u,cause:e})}finally{Pe.release(yu)}},{handler:_u,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:_u})}),xu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Pe.tryAcquire(yu)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:vu,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(je),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:vu,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:vu,cause:e})}finally{Pe.release(yu)}},{handler:vu,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:vu})}),Su=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(De){let t=De.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(je).get()?`file`:process.env.OK_EMBEDDINGS_API_KEY?`env`:null,D=E!==null,O=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(O+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:D,keySource:E,ready:s,capable:g,embedded:S,total:O},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Cu={"/api/config":gu,"/api/asset":fc,"/api/asset-text":mc,"/api/document":Xi,"/api/documents":Zi,"/api/backlinks":ka,"/api/backlink-counts":_s,"/api/forward-links":xs,"/api/link-graph":Cs,"/api/dead-links":Os,"/api/orphans":Ts,"/api/hubs":Ds,"/api/tags":yl,"/api/pages":wc,"/api/folder-config":kl,"/api/template":Il,"/api/templates":Fl,"/api/search":tu,"/api/semantic-status":Su,"/api/suggest-links":Tc,"/api/page-headings":bc,"/api/create-page":_c,"/api/create-folder":vc,"/api/duplicate-path":yc,"/api/rename-path":xc,"/api/delete-path":Sc,"/api/trash/cleanup":Cc,"/api/upload":Ec,"/api/agent-write":Ui,"/api/agent-write-md":Gi,"/api/frontmatter-patch":Ki,"/api/agent-patch":ks,"/api/agent-undo":As,"/api/agent-activity":Ns,"/api/agent-burst-diff":Ps,"/api/save-version":ec,"/api/history":tc,"/api/diff":rc,"/api/rollback":ic,"/api/metrics/reconciliation":ac,"/api/metrics/parse-health":oc,"/api/metrics/agent-presence":lc,"/api/__embed-detect":uc,"/api/server-info":sc,"/api/share/construct-url":su,"/api/git/branch-info":cu,"/api/git/checkout":lu,"/api/share/publish/owners":du,"/api/share/publish/name-check":fu,"/api/share/publish":pu,"/api/principal":cc,"/api/rescue":gc,"/api/workspace":dc,"/api/sync/status":ll,"/api/sync/trigger":ul,"/api/sync/conflicts":dl,"/api/sync/conflict-content":pl,"/api/sync/resolve-conflict":fl,"/api/local-op/clone":Nc,"/api/local-op/open":Lc,"/api/local-op/ok-init":zc,"/api/local-op/auth/login":Kc,"/api/local-op/auth/status":Yc,"/api/local-op/auth/repos":Zc,"/api/local-op/auth/signout":nl,"/api/local-op/auth/set-identity":cl,"/api/local-op/embeddings/set-key":bu,"/api/local-op/embeddings/clear-key":xu,"/api/installed-agents":vl,"/api/spawn-cursor":ou,"/api/handoff":au,"/api/install-skill":_l,"/api/skill/install-state":iu,"/api/seed/plan":ml,"/api/seed/apply":hl,"/api/seed/packs":gl,"/api/client-logs":mu};j&&(Cu[`/api/test-reset`]=Is,Cu[`/api/test-rescan-backlinks`]=Rs,Cu[`/api/test-rescan-files`]=$s);let wu=new Set([`/api/upload`,`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/agent-write`,`/api/agent-write-md`,`/api/frontmatter-patch`,`/api/agent-patch`,`/api/agent-undo`,`/api/save-version`,`/api/rollback`,`/api/sync/trigger`,`/api/sync/resolve-conflict`,`/api/git/checkout`,`/api/test-reset`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/install-skill`,`/api/folder-config`,`/api/template`,`/api/seed/apply`,`/api/client-logs`]),Tu=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let s=e.url?.split(`?`)[0];if(!s)return;let g=t=>{let s=e.headers[t];if(s!==void 0)return Array.isArray(s)?s.join(`, `):s};if(recordEmbedProbe({ts:Date.now(),url:s,method:e.method??``,ua:g(`user-agent`),origin:g(`origin`),referer:g(`referer`),host:g(`host`),remote:e.socket?.remoteAddress,secChUa:g(`sec-ch-ua`),secChUaMobile:g(`sec-ch-ua-mobile`),secChUaPlatform:g(`sec-ch-ua-platform`),secFetchSite:g(`sec-fetch-site`),secFetchDest:g(`sec-fetch-dest`),secFetchMode:g(`sec-fetch-mode`),secFetchUser:g(`sec-fetch-user`)}),s.startsWith(`/api/`)){let s=e.headers.origin;if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(wu.has(s)||Tu.some(e=>s.startsWith(e))){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(Me&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:Cu[s]||(E=`/api/*`);let D=getTracer(),O=Date.now();await context.with(S,()=>D.startActiveSpan(`HTTP ${w} ${E}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_URL_PATH]:s,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async g=>{try{let S=Cu[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await nc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await xl(e,t,g))}E||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${w} ${s}`});let D=t.statusCode;g.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,D),D>=500&&g.setStatus({code:SpanStatusCode.ERROR,message:`status ${D}`})}catch(e){throw g.recordException(e),g.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E,cause:e}),e}finally{g.end();let e=(Date.now()-O)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function isWithinDir(e,t){return e===t?!0:e.startsWith(`${t}${sep}`)}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}function seedBasenameIndex(e){let t=e.contentDir,s=new Set;function g(S){let w;try{w=readdirSync(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=relative(t,w);if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=lstatSync(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=realpathSync(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=statSync(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}g(t)}const log$3=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$3.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$3.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$3.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,s,g=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:S}=await import(`./git-handle-CvT4CaVU-BqccGnFS.mjs`),w=S(this.projectDir,{credentialArgs:g});switch(t){case`mine`:await w.git.raw([`checkout`,`--ours`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`theirs`:await w.git.raw([`checkout`,`--theirs`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`content`:{if(s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),g=resolve(t,e);if(g!==t&&!g.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(g,s,`utf-8`),await w.git.raw([`add`,`--`,e]);break}case`delete`:await w.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await w.git.raw([`commit`,`--no-edit`]),log$3.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=(await w.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
|
|
1709
|
+
`:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),fe=!0}de=!0},te.origin)})}finally{ce?.touchMode(O,`idle`)}if(oe){let e;switch(oe.kind){case`invalid_value`:e={[oe.key]:oe.reason};break;case`reserved_key`:e={[oe.key]:`'${oe.key}' is reserved`};break;case`unknown_key`:e={[oe.key]:`'${oe.key}' is not a recognized key`};break;case`duplicate_target`:e={[oe.key]:`'${oe.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${oe.expected.join(`, `)}; got: ${oe.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${oe.bytes} > ${oe.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${oe.reason}`};break;default:e={__region__:`unhandled frontmatter edit error (${String(oe)})`}}errorResponse(w,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(de&&me.length>0){if(recordContributor(D,O,k,j,void 0,qr({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),Xr(ee),fe){let e=await Mt(D);if(e?.kind===`failure`){Ft(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){It(w,`frontmatter-patch`);return}}jt(D,`frontmatter-patch`)}se?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),ue?.();let ge=Et(D),_e=Dt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=Lt(ne);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:ge,systemSubscriberCount:_e,appliedKeys:me,...J?{summary:J}:{},...ve?{warning:ve}:{}},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$4.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Yi(e){let t=e.getMap(`lifecycle`),s=t.get(`status`);if(typeof s!=`string`||s.length===0)return null;let g=t.get(`reason`);return{status:s,reason:typeof g==`string`?g:``}}let Xi=withValidation(EmptyRequestSchema,async(e,s)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(S)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let w=Tt(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`document-read`});return}let E=t.documents.get(w);if(E){successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:E.getText(`source`).toString(),lifecycle:Yi(E)},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(g,`file`,w))){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document not found: ${w}.`,{handler:`document-read`});return}let D=await t.openDirectConnection(w);try{let e=D.document;if(!e){errorResponse(s,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:e.getText(`source`).toString(),lifecycle:Yi(e)},{handler:`document-read`})}finally{await D.disconnect()}}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Zi=withValidation(EmptyRequestSchema,async(e,t)=>{try{Ce&&await Ce.catch(e=>{log$4.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=s.searchParams.get(`dir`),D=s.searchParams.get(`showAll`)===`true`,O=s.searchParams.get(`depth`)===`1`?1:1/0;if(S)try{safeSubdir(g,S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(D&&_e&&showAllWantsNdjson(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let s=createStreamingErrorWriter(t,`document-list`),w=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let s=()=>{t.off(`drain`,s),t.off(`close`,s),e()};t.once(`drain`,s),t.once(`close`,s)})};try{let t=getShowAllMaxEntries(),s=streamShowAllEntries({contentDir:g,contentFilter:_e,dirFilter:S,getDocExtension,maxEntries:t,maxDepth:O,signal:e.signal}),E=0,D=await s.next();for(;!D.done;)await w(`${JSON.stringify(D.value)}\n`),E+=1,D=await s.next();let{truncated:k}=D.value;k&&log$4.info({handler:`document-list`,maxEntries:t,count:E},`[document-list][showAll] stream truncated at entry cap`),await w(`${JSON.stringify({type:`complete`,truncated:k,count:E})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?s(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):log$4.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(D&&_e){let e=`showAll:${O===1?`d1:`:``}${S??``}`,s=Ie.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:_e,dirFilter:S,documents:e,getDocExtension,maxEntries:s,maxDepth:O,signal:t.signal});return e.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),w&&log$4.info({handler:`document-list`,maxEntries:s,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:w}})();s={promise:w,controller:t,waiters:0};let E=s;Ie.set(e,E),w.finally(()=>{Ie.get(e)===E&&Ie.delete(e)})}let w=s;w.waiters+=1;let E=!1,D=()=>{t.writableEnded||E||(E=!0,--w.waiters,w.waiters<=0&&(w.controller.abort(),Ie.get(e)===w&&Ie.delete(e)))};t.on(`close`,D);try{let{documents:e,truncated:s}=await w.promise;if(E)return;successResponse(t,200,DocumentListSuccessSchema,s?{documents:e,truncated:s}:{documents:e},{handler:`document-list`})}catch(e){if(E)return;errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,D)}return}let k=w(),j=E?.()??new Map,F=[];for(let[e,t]of j)S&&!e.startsWith(`${S}/`)&&e!==S||F.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let[e,t]of k){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);F.push({kind:`document`,docName:e,docExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let w of t.aliases){if(S&&!w.startsWith(`${S}/`)&&w!==S)continue;let E=relative(g,t.canonicalPath);F.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}}let L=[];try{let e=Ge(k);Re?.signature!==e&&(Re={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:k,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:_e?e=>_e.isPathIgnored(e):void 0})}),L=Re?.assets??[]}catch(e){Re=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}for(let e of L)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||F.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});F.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),successResponse(t,200,DocumentListSuccessSchema,{documents:F},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),ka=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:s,backlinks:ne.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:nt(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),_s=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let g={};for(let e of s.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(g[t]=ne.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:g},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),xs=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let g=Rt();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ne.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:rt(e.target,g),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),Cs=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`docName`);if(g&&!isSafeDocName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let S=s.searchParams.get(`degrees`);if(S&&!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let w,E;if(S&&g){let e=Number.parseInt(S,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:w,links:E}=ne.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ne.getLinkGraph());let D=Rt();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=st(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:rt(e.docName,D),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:E},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),Ts=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ne.getOrphans([...w().keys()],s).map(e=>({docName:e,title:nt(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),Ds=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),g=s?Number.parseInt(s,10):20,S=Number.isFinite(g)&&g>0?g:20,w=Rt();successResponse(t,200,HubsSuccessSchema,{hubs:ne.getHubs(S).map(e=>({docName:e.docName,title:rt(e.docName,w),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),Os=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(s.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let g=s.length?[...new Set(s.map(e=>Tt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ne.getDeadLinks(Rt(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:nt(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),ks=withValidation(AgentPatchRequestSchema,async(S,w,E)=>{try{let{find:S,replace:D,offset:O}=E,k=requireNonEmptyDocName(E.docName,w,`agent-patch`);if(k===null)return;let j=Tt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Kr(E);if(findLooksLikeFrontmatter(S)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H}),te=reconcileDiskBeforeAgentWrite(t,j,g,e.resolveEmbed),ne=new Date().toISOString(),ae=!1,oe=!1,de=!1,fe;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ce?.setPresence(F,{displayName:L,icon:t,color:s,currentDoc:j,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),F,B,H),Y.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),g=prependFrontmatter(t,s),w=O==null?g.indexOf(S):g.slice(O,O+S.length)===S?O:-1;if(w===-1){O==null?ae=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":j,findLength:S.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(w<t.length){de=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));fe=applyAgentMarkdownWrite(Y.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),Y.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},Y.origin),fe!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:fe.intendedBytes,actualBytes:fe.actualBytes,byteDelta:fe.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!de){let{stored:e}=Jr(J);recordContributor(j,F,L,B,void 0,qr({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),Xr(J),recordContentDivergenceGate(`agent-patch`,fe)}}finally{ce?.touchMode(F,`idle`)}if(oe){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ae){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(de){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let me=await Mt(j);if(me?.kind===`failure`){Ft(w,me.failure,`agent-patch`);return}if(me?.kind===`divergence`){It(w,`agent-patch`);return}jt(j,`agent-patch`),se?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),ue?.();let ge=Et(j),_e=Dt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=Jr(J),ye=Lt(te);successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:ge,systemSubscriberCount:_e,...ve?{summary:ve}:{},...fe===void 0?ye?{warning:ye}:{}:{warning:toContentDivergenceWarning(fe)}},{handler:`agent-patch`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-patch`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-patch`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$4.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),As=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=Tt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Kr(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(g,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:L}=S,B=S.scope===`session`||S.scope===`file`?`session`:`last`;if(!s.hasSession(w,L)){errorResponse(g,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let H=await s.getSession(w,L),q=!1;try{let t=iconFromClientName(k),s=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);ce?.setPresence(E,{displayName:D,icon:t,color:s,currentDoc:w,mode:`writing`,ts:Date.now()}),q=applyAgentUndo(H,B,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:w}:void 0),q&&recordContributor(w,L,D,O,void 0,qr({clientName:k,clientVersion:j,label:F}))}finally{ce?.touchMode(E,`idle`)}if(q){let e=await Mt(w);if(e?.kind===`failure`){Ft(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){It(g,`agent-undo`);return}jt(w,`agent-undo`)}se?.setFocus(L,{agentName:L,currentDoc:w,writeKind:`undo`,ts:Date.now()}),successResponse(g,200,AgentUndoSuccessSchema,{docName:w,scope:B,undone:q},{handler:`agent-undo`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(g,e,`agent-undo`);return}log$4.error({err:e},`[agent-undo] handler failed`),errorResponse(g,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),Ns=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(g===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(s,g),{handler:`agent-activity`})}catch(e){log$4.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),Ps=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=validateAgentId(g.searchParams.get(`agentId`)),w=g.searchParams.get(`docName`),E=g.searchParams.get(`stackIndex`);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!w||w.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let D=Tt(w);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!E||Number.isNaN(Number(E))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let O=Number(E);if(!Number.isInteger(O)||O<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let k=s.getLiveSession(D,S);if(!k){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let j=k.um;if(O>=j.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${O} out of range (stack has ${j.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let F=j.undoStack[O];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(F,k.dc.document.getText(`source`),D),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$4.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),Is=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=Tt(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$4.error({err:e,docName:E},`[test-reset] safeContentPath rejected docName`),errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(E),t.closeConnections(E);let O=`onStoreDocument-${E}`;t.debouncer.isDebounced(O)&&await t.debouncer.executeNow(O);let k=t.documents.get(E);if(k&&await(ye??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ne&&(ne.deleteDocument(E),ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),oe?.(`backlinks`),oe?.(`graph`)),w.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(g,`.okignore`),s=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(s){let e=s.getText(`source`);e.length>0&&s.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),_e&&await _e.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}oe?.(`files`),successResponse(S,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ne.rebuildFromDisk(),ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),oe?.(`backlinks`),oe?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),$s=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!k){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await k(),oe?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),ec=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Kr(s),E=F?.current;if(!E){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let D=/^[a-zA-Z0-9_-]+$/,O=[];if(Array.isArray(s.writers))try{O=s.writers.map(e=>{let t=e.id??`unknown`;if(!D.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}O.length===0&&(O=e===void 0?[SERVICE_WRITER]:[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}]);let k=te??`.`,j=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),L=await saveVersion(E,k,O,`main`,j.kind===`value`?j.value:void 0);getLogger(`history`).info({checkpointRef:L.checkpointRef},`checkpoint`);try{await gcRenameLog(E,getOrLoadRenameLogIndex(E.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:L.checkpointRef},{handler:`save-version`})}catch(e){log$4.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{let s=F?.current;if(!s){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`docName`)??``,w=g.searchParams.get(`folder`),E=g.searchParams.get(`branch`)??J?.()??`main`;if(!S&&w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(E.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(w!==null&&!S){let e=_l(w,t,`folder`,`history`);if(!e)return;let S=Number(g.searchParams.get(`limit`)??`50`),D=Math.min(200,Number.isFinite(S)?S:50),O=Number(g.searchParams.get(`offset`)??`0`),k=Math.max(0,Number.isFinite(O)?O:0);successResponse(t,200,HistorySuccessSchema,{...await getFolderTimeline(s,e.folderRel,te??`.`,{branch:E,limit:D,offset:k})},{handler:`history`});return}let D=te??`.`,O=safeDocPath(S,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history`});return}let k=Number(g.searchParams.get(`limit`)??`50`),j=Number(g.searchParams.get(`offset`)??`0`),L=Math.min(200,Number.isFinite(k)?k:50),B=Number.isFinite(j)?j:0,H=g.searchParams.get(`type`)??void 0,q=g.searchParams.get(`author`)??void 0,ee=g.searchParams.get(`excludeAuthor`)??void 0,Y=Date.now();try{let e=await getDocumentHistory(s,{docName:S,branch:E,limit:L,offset:B,type:H,author:q,excludeAuthor:ee},D),g=Date.now()-Y;getLogger(`timeline`).info({docName:S,entries:e.entries.length,durationMs:g},`query`),successResponse(t,200,HistorySuccessSchema,{...e},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function nc(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let g=F?.current;if(!g){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,w=te??`.`,E=safeDocPath(S,w);if(`error`in E){errorResponse(t,400,`urn:ok:error:invalid-request`,E.error,{handler:`history-version`});return}let D=shadowGit(g),O=J?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(g,S,s,O,getOrLoadRenameLogIndex(g.gitDir),e=>{let t=safeDocPath(e,w);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let E=await D.raw(`show`,`${s}:${e}`),[k=``,j=``]=(await D.raw(`log`,`-1`,`--format=%aI%x00%an`,s)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:s,content:E,timestamp:k,author:j},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let rc=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,ge);if(w.kind===`invalid-summary`){errorResponse(g,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let E=t.documents.get(S.docName);if(E&&isDocInConflict(E)){respondDocInConflict(g,new DocInConflictError({file:`${S.docName}${getDocExtension(S.docName)}`}),`rollback`);return}let D=F?.current;if(!D){errorResponse(g,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:O,commitSha:k}=S,j=te??`.`,L=safeDocPath(O,j);if(`error`in L){errorResponse(g,400,`urn:ok:error:invalid-request`,L.error,{handler:`rollback`});return}let B=shadowGit(D),H=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,J?.()??`main`,s,e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path},S);if(E===null){errorResponse(g,404,`urn:ok:error:doc-not-found`,`Commit ${k.slice(0,7)} does not contain document ${O} at any known historical path.`,{handler:`rollback`});return}let F=await B.raw(`show`,`${k}:${E}`),L=new Date().toISOString();await safetyCheckpoint(D,j,{action:`rollback`,context:{docName:O,targetSha:k}});let q=t.documents.get(O);if(!q){errorResponse(g,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let ee=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,Y;q.transact(()=>{replaceRawBody(q,F,ee),Y=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),Y!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:Y.intendedBytes,actualBytes:Y.actualBytes,byteDelta:Y.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,Y);let te;switch(w.kind){case`agent`:{let e=k.slice(0,8),t=w.summary.kind===`value`,s=t?w.summary:normalizeSummary(`Restored to ${e}`),g=Jr(s);te=t||!g.response?g.response:Yr(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),Xr(s,!t);break}case`principal`:{let e=Jr(w.summary);te=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),Xr(w.summary,!1);break}case`anonymous`:log$4.debug({docName:O,commitSha:k.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(w.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:w.kind});let ne=await Mt(O);if(ne?.kind===`failure`){Ft(g,ne.failure,`rollback`);return}if(ne?.kind===`divergence`){It(g,`rollback`);return}jt(O,`rollback`);let ae=Date.now()-H;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ae},`rollback`),w.kind===`agent`&&se?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()}),successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:L,...te?{summary:te}:{},...Y===void 0?{}:{warning:toContentDivergenceWarning(Y)}},{handler:`rollback`})}catch(e){errorResponse(g,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),ic=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$4.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),ac=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$4.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),oc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Ce&&await Ce.catch(e=>{log$4.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=Y?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function sc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let s=ge?.()??null;if(!s){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,s,{handler:`principal`})}async function cc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.getPresenceMap()??{},s=Date.now(),g={};for(let[t,S]of Object.entries(e))s-S.ts<2e4&&(g[t]=S);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:g},{handler:`metrics-agent-presence`})}catch(e){log$4.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function lc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let s=embedProbeRing.read();successResponse(t,200,EmbedDetectSuccessSchema,{entries:s,count:s.length,detection:deriveDetection(s[0])},{handler:`embed-detect`})}async function uc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let s=resolve(g),S=s,w=!0;try{S=realpathSync(s)}catch(e){let g=e?.code;if(g===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:s}),w=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:s,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:g??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:S,pathSeparator:sep,symlinkResolved:w},{handler:`workspace`})}let dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let S=assetContentTypeForPath(s),w=extname(s).slice(1).toLowerCase();if(!S||!ASSET_EXTENSIONS.has(w)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let E=realpathSync(g),D=resolve(E,s),O;try{O=realpathSync(D)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let k;try{k=statSync(O)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let j=toContentRelativePath(E,O);if(j!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(_e?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F=SANDBOXED_HTML_EXTENSIONS.has(w),L={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)||F?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`?L[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:F&&(L[`Content-Security-Policy`]=SANDBOXED_HTML_CSP),t.writeHead(200,L);try{await pipeline(createReadStream(O),t)}catch(e){log$4.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:s,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),fc=1048576,pc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let S=realpathSync(g),w=resolve(S,s),E;try{E=realpathSync(w)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(E,S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let D;try{D=statSync(E)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!D.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(S,E)!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(D.size>fc){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${fc}-byte text-viewer cap.`,{handler:`asset-text`});return}let O=(await readFile$1(E)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(O)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),mc=1440*60*1e3,hc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!F?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(F.current.gitDir,`rescue`);if(existsSync(g))try{let t=readdirSync(g).filter(e=>isSupportedDocFile(e));for(let S of t){let t=resolve(g,S),w=statSync(t);if(e-w.mtimeMs>864e5){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}s.push({docName:stripDocExtension(S),timestamp:w.mtime.toISOString(),size:w.size,source:`flat`})}}catch(e){log$4.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=J?.()??`main`,t=await listRescueCheckpoints(F.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$4.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,s,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),gc=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,ge);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let S=s.path;if(!isSupportedDocFile(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(S.includes(`..`)||S.startsWith(`/`)||S.includes(`\0`)||S.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let E=resolve(g),D=resolve(E,S);if(!D.startsWith(`${E}/`)&&D!==E){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let O=stripDocExtension(S);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`create-page`});return}let k=typeof s.template==`string`?s.template.trim():``,j=``,F;if(k.length>0){if(!/^[A-Za-z0-9_-]+$/.test(k)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let s=S.includes(`/`)?S.slice(0,S.lastIndexOf(`/`)):``,g=resolveTemplatesAvailable(E,s),w=g.find(e=>e.name===k);if(!w){let e=g.length===0?`(none)`:g.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${k}" does not resolve for folder "${s||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let D=resolve(E,w.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${w.path}.`,{handler:`create-page`,cause:e});return}let{body:L}=stripFrontmatter(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=w.scope}mkdirSync(dirname(D),{recursive:!0});try{writeFileSync(D,j,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let L=stripDocExtension(S);switch(we?.delete(L),_e&&_e.incrementMdDir(dirname(L)),registerWrite(D,contentHash(j)),e.kind){case`agent`:case`principal`:recordContributor(L,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}let B=typeof w==`function`?w():null;B instanceof Map&&updateFileIndex({kind:`create`,path:D,docName:L,content:j},B),ne&&(ne.updateDocumentFromMarkdown(L,j),ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),oe?.(`backlinks`),oe?.(`graph`)),oe?.(`files`),F!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:k,templateScope:F,docName:L})),successResponse(t,200,CreatePageSuccessSchema,{docName:L},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),_c=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,ge).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=s.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(_e?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let S=resolveContentEntryPath(g,`folder`,e);if(existsSync(S)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(S,{recursive:!0}),Ve(e),oe?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),vc=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,ge);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:E}=S,D=E===`file`?stripDocExtension(S.path):S.path;if(!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(D===`.ok`||D.startsWith(`.ok/`)||E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||E===`folder`&&isReservedSyntheticFolderPath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}E===`file`&&probeAndRegisterSourceFileExtension(g,D);let O=resolveContentEntryPath(g,E,D);if(!existsSync(O)){if(E===`file`){let e=resolveContentEntryPath(g,`folder`,D);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${E}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${E} does not exist.`,{handler:`duplicate-path`});return}let k=statSync(O);if(E===`file`&&!k.isFile()||E===`folder`&&!k.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${E}.`,{handler:`duplicate-path`});return}let j=E===`file`?[D]:Hr(resolveContentEntryPath(g,`folder`,D)),F=de?.(),L=new Set(F?F.getConflicts().map(e=>e.file):[]);for(let e of j){let g=stripDocExtension(e),S=t.documents.get(g),w=`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),D=L.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let B=typeof w==`function`?w():null,H,q=[];if(E===`file`){let e=extname(O);if(H=nextAvailableDuplicateDocName(g,D).docName,isSystemDoc(H)||isConfigDoc(H)||_e?.isExcluded(`${H}${e}`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=resolveDuplicateDocPath(g,H,e),S=readFileSync(O,`utf-8`),w=dirname(t),E=existsSync(w);try{tracedMkdirSync(w,{recursive:!0}),tracedWriteFileSync(t,S,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!E)try{tracedRmdirSync(w)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:w,err:e})}throw e}let k=!1;try{registerDocExtension(H,e),we?.delete(H),_e&&(_e.incrementMdDir(dirname(H)),k=!0),registerWrite(t,contentHash(S)),B instanceof Map&&updateFileIndex({kind:`create`,path:t,docName:H,content:S},B),ne?.updateDocumentFromMarkdown(H,S),q=[H]}catch(e){try{tracedRmSync(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw forgetDocExtension(H),_e&&k&&_e.decrementMdDir(dirname(H)),B instanceof Map&&updateFileIndex({kind:`delete`,path:t,docName:H},B),e}}else{if(H=nextAvailableDuplicateFolderPath(g,D).folderPath,_e?.isDirExcluded(H)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(g,`folder`,H);try{tracedCpSync(O,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(g,H))Ve(e);let e=collectMarkdownCopies(g,H);q=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(t.docName,e),we?.delete(t.docName),_e&&_e.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),B instanceof Map&&updateFileIndex({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content},B),ne?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of q)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}ne&&q.length>0&&(ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),oe?.(`backlinks`),oe?.(`graph`)),oe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:E,path:H,duplicatedDocNames:q},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=classifyDuplicatePathFilesystemProblem(e);if(t){errorResponse(s,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),yc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s||s.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let g=$e(s);if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(g)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:s,headings:extractHeadings(readFileSync(g,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),bc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,ge);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:w,fromPath:E,toPath:D}=S;if(!isValidRelativeContentPath(E)||!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(w===`file`&&(isSystemDoc(E)||isSystemDoc(D)||isConfigDoc(E)||isConfigDoc(D))){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||D===`.ok`||D.startsWith(`.ok/`)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(E===D){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}if(w===`asset`){let t;try{t=await Wr(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=Ht(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=Zr(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$4.debug({kind:`asset`,fromPath:E,toPath:D,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(renameAttributionCounter().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),B)try{await B()}catch(e){console.warn(`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...g?{summary:g}:{}},{handler:`rename-path`});return}let O=w===`file`?[stripDocExtension(E)]:Hr(resolveContentEntryPath(g,`folder`,E)),k=de?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]);for(let e of O){let g=stripDocExtension(e),S=t.documents.get(g),D=w===`file`?E:`${g}${getDocExtension(e)}`,O=S!==void 0&&isDocInConflict(S),k=j.has(D);if(O||k){respondDocInConflict(s,new DocInConflictError({file:D}),`rename-path`);return}}if(w===`file`&&probeAndRegisterSourceFileExtension(g,E),_e&&(w===`file`?_e.isExcluded(isSupportedDocFile(D)?D:`${D}${getDocExtension(E)}`):_e.isDirExcluded(D))){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${w===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let F=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,L;try{L=await Gr(E,D,w,F?{actor:F}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,Vt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(L.renamed.length===0&&L.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}L.renamedAssets.length>0&&Ke();let H;if(L.renamed.length>0&&(H=Zr(e,`Renamed ${E} → ${D}`,L.renamed.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$4.debug({kind:w,fromPath:E,toPath:D,affectedDocs:L.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${w}`,attribution_kind:e.kind}),B)try{await B()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:L.renamed,renamedAssets:L.renamedAssets,rewrittenDocs:L.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=Ht(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),xc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Kr(S);let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let D=e===`asset`?Vr(E):{path:E,ambiguous:!1};if(D.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let O=D.path;if(e===`asset`&&(isSupportedDocFile(O)||isReservedProjectStatePath(O))){errorResponse(s,400,isReservedProjectStatePath(O)?`urn:ok:error:reserved-doc-name`:`urn:ok:error:invalid-request`,isReservedProjectStatePath(O)?`.ok and .git are reserved directories.`:`Asset operations do not support markdown documents.`,{handler:`delete-path`});return}let k=e===`asset`?resolveContentEntryPath(g,`folder`,O):resolveContentEntryPath(g,e,O);if(!existsSync(k)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${e} does not exist.`,{handler:`delete-path`});return}let j=statSync(k);if(e===`file`&&!j.isFile()||e===`asset`&&!j.isFile()||e===`folder`&&!j.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${e}.`,{handler:`delete-path`});return}let F=e===`asset`?[]:e===`file`?[E]:Hr(resolveContentEntryPath(g,`folder`,E)),L=de?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let g of F){let S=stripDocExtension(g),w=t.documents.get(S),E=e===`file`?g:`${S}${getDocExtension(S)}`,D=w!==void 0&&isDocInConflict(w),O=B.has(E);if(D||O){respondDocInConflict(s,new DocInConflictError({file:E}),`delete-path`);return}}if(await Ut(F),we)for(let e of F)isSystemDoc(e)||isConfigDoc(e)||(we.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));e===`file`||e===`asset`?tracedUnlinkSync(k):(tracedRmSync(k,{recursive:!0,force:!1}),Ue(E)),Ke();let H=w();if(H instanceof Map)for(let e of F)updateFileIndex({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e},H);oe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:F},{handler:`delete-path`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Sc=withValidation(TrashCleanupRequestSchema,async(e,t,s)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":s.kind,"ok.cleanup.path":normalizeFsPath(s.path),"ok.cleanup.path.role":classifyFsPath(s.path)}},async()=>{try{if(extractActorIdentity(s,ge).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:S}=s;if(!isValidRelativeContentPath(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let E=e===`folder`&&isReservedSyntheticFolderPath(S),D=e===`asset`&&isReservedProjectStatePath(S),O=e===`asset`&&isSupportedDocFile(S);if(e===`file`&&(isSystemDoc(S)||isConfigDoc(S))||E||D||O){errorResponse(t,400,O?`urn:ok:error:invalid-request`:`urn:ok:error:reserved-doc-name`,O?`Asset operations do not support markdown documents.`:`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(e===`asset`){Ke(),oe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let k=w(),j=e===`file`?k.has(S)?[S]:[]:listAffectedDocNames(k,e,S);if(Ke(),j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Ut(j),we)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(we.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));let F=w();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e},F);e===`folder`&&Ue(S),oe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:j},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=t,w,E=getDocExtension(t);try{let s=readFileSync(resolve(g,`${t}${E}`),`utf-8`);e=extractPageTitle(s,t),w=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}s.push({docName:t,title:e,docExt:E,size:S.size,modified:S.modified,icon:w})}s.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:s},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),wc=withValidation(EmptyRequestSchema,async(e,s)=>{try{let g=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!g){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(g)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(g)||isConfigDoc(g)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${g}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(s,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:w(),docName:g}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function Tc(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let s;try{s=await readUploadBody(e,me??g)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:S,tempPath:w,sha:E,byteLength:D,parentDocName:O}=s,k=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},j=validateBody(UploadRequestSchema,{parentDocName:O},t,{handler:`upload-asset`});if(!j.ok){k();return}let{parentDocName:F}=j.value,{agentId:L,agentName:B}=Kr(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(D===0){k(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(F.includes(`\0`)||F.includes(`..`)||F.startsWith(`/`)){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let H=resolve(g),q=resolveUploadDestDir(F,`./`,H);if(!isWithinContentDir(q,H)){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(q,H)}catch(e){if(k(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$4.error({err:e,destDir:q},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(q,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){k();let s=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(s),s,uploadTitleFor(s),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(q),s;try{s=realpathSync(H)}catch{s=H}if(!isWithinContentDir(e,s)){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ee=await fileTypeFromFile(w),J=ee?.mime,Y=ee?.ext;if(!J){let e=readTempFileHead(w,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(J=`image/svg+xml`,Y=`svg`)}{let s=await findDuplicateAsset(q,E,D);if(s){k();let S=relative(g,resolve(q,s));log$4.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:L,agentName:B,dedup:!0,mime:J??null,size:D,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let te;if(!S||S===`upload`||GENERIC_PASTE_NAMES.test(S)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=S?extname(S).slice(1):``,s=Y??t??``;te=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else te=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,q,te),S=relative(g,resolve(q,s));log$4.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:L,agentName:B,dedup:!1,mime:J??null,size:D,destPath:S,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!1},{handler:`upload-asset`})}catch(s){let g=s instanceof UploadWriteError?s.reason:`urn:ok:error:storage-error`;log$4.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:L,agentName:B,filename:te,size:D,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Ec=`/api/local-op/clone`,Dc=`/api/local-op/ok-init`,Oc=600*1e3,kc=45e3,Ac=`local-op-clone`,jc=withValidation(LocalOpCloneRequestSchema,Mc,{handler:Ac,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ac})});async function Mc(e,t,s){let{url:g,dir:S,branch:w}=s;if(!isAllowedGitUrl(g)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:Ac,cause:Error(`url=${g}`)});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:Ac,cause:Error(`dir=${S}`)});return}if(!Pe.tryAcquire(Ec)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Ac,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Ac),D=null,O=runCloneSubprocess({cliArgs:fe,url:g,dir:S,branch:w,timeoutMs:Oc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$4.warn({stderr:redactShareSubprocessStderr(e.message),url:g,dir:S},`[local-op/clone] clone failed`);let t=classifyCloneError(e.message??``);E(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(redactShareSubprocessStderr(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await O.done,D&&!t.writableEnded&&!t.destroyed){let e=await Nc(D);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:D})}\n`):E(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?E(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$4.error({err:e,handler:Ac},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Pe.release(Ec)}})(),t.on(`close`,()=>{O.cancel()})}async function Nc(e,t){let s=resolve(expandTilde(e)),g=getLocalDir(s),S=readUiLock(g);if(S&&S.port>0)return{port:S.port};let[w,...E]=fe,D=e=>{let s=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...E,e,...s]},O=async e=>{let t=spawn(w,D(e),{cwd:s,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$4.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/clone] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$4.error({cwd:s,cliCmd:e,err:t.message},`[local-op/clone] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let Pc=`local-op-ok-init`,Fc=withValidation(LocalOpOkInitRequestSchema,async(e,t,s)=>{let{projectPath:g}=s;if(!isAbsolute(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:Pc,cause:Error(`projectPath=${g}`)});return}let S;try{S=realpathSync(g)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:Pc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Pc,cause:Error(`projectPath=${g}`)});return}let w=resolveGitDirDetailed(S).kind;if(w!==`directory`&&w!==`linked`){console.warn(`[ok-init] action=init project=${basename(S)} result=not-a-git-worktree kind=${w}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${w}).`},{handler:Pc});return}if(isProjectRoot(S)){console.warn(`[ok-init] action=init project=${basename(S)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Pc});return}if(!Pe.tryAcquire(Dc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Pc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(S)}),console.warn(`[ok-init] action=init project=${basename(S)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Pc})}catch(e){let s=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(S)} result=failed reason=${s}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:s},{handler:Pc})}finally{Pe.release(Dc)}},{handler:Pc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Pc})}),Ic=`/api/local-op/auth/login`,Lc=`/api/local-op/auth/status`,Rc=`/api/local-op/auth/repos`,zc=`/api/local-op/auth/signout`,Bc=null,Vc=`local-op-auth-login`,Hc=withValidation(LocalOpAuthHostRequestSchema,Uc,{handler:Vc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Vc})});async function Uc(e,t,s){let g=s.host??`github.com`;if(!Pe.tryAcquire(Ic)){let e=Bc;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:Vc,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),Bc=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,Vc),w=runDeviceFlowSubprocess({cliArgs:fe,host:g,timeoutMs:Oc,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(resumeSyncOnAuthEvent(e,de),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});Bc=w;let E=()=>{w.cancel(),Bc===w&&(Bc=null,Pe.release(Ic))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}Bc===w&&(Bc=null,Pe.release(Ic))})}let Wc=`local-op-auth-status`,Gc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Pe.tryAcquire(Lc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Wc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=fe,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,g.kill(`SIGTERM`)},3e4),D=[];g.stdout.on(`data`,e=>D.push(e)),g.on(`close`,()=>{if(clearTimeout(E),w){s(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(D).toString(`utf-8`))}),g.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
|
|
1710
|
+
`).map(e=>e.trim()).filter(Boolean),E=null;for(let e=w.length-1;e>=0;e--)try{E=JSON.parse(w[e]);break}catch{}E===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:Wc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:Wc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Wc,cause:e})}finally{Pe.release(Lc)}},{handler:Wc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Wc})}),Kc=`local-op-auth-repos`,qc=withValidation(LocalOpAuthHostRequestSchema,Jc,{handler:Kc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Kc})});async function Jc(e,t,s){let g=s.host??`github.com`;if(!Pe.tryAcquire(Rc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Kc,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,Kc),[w,...E]=fe,D=[...E,`auth`,`repos`,`--json`,`--host`,g],O=!1,k=``,j=spawn(w,D,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),F=setTimeout(()=>{j.kill(`SIGTERM`)},Oc);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
|
|
1711
|
+
`);k=s.pop()??``;for(let e of s){if(!e.trim())continue;let s=null;try{s=JSON.parse(e)}catch{}if(s&&s.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof s.message==`string`?s.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),j.stderr.on(`data`,e=>{log$4.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),j.on(`close`,e=>{clearTimeout(F),O||(O=!0,e!==0&&!t.writableEnded&&S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Pe.release(Rc))}),j.on(`error`,e=>{clearTimeout(F),O||(O=!0,t.writableEnded||(S(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Pe.release(Rc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Pe.release(Rc))})}let Yc=`local-op-auth-signout`,Xc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Pe.tryAcquire(zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Yc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=fe,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,{stdio:`ignore`,env:{...process.env}}),w=setTimeout(()=>{g.kill(`SIGTERM`)},3e4);g.on(`close`,()=>{clearTimeout(w),t()}),g.on(`error`,e=>{clearTimeout(w),s(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Yc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Yc,cause:e})}finally{Pe.release(zc)}},{handler:Yc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Yc})}),Zc=`/api/local-op/auth/set-identity`,Qc=`local-op-auth-set-identity`,$c=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!me){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Qc});return}if(!Pe.tryAcquire(Zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Qc,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(me,g,S),de?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Qc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Qc,cause:e})}finally{Pe.release(Zc)}},{handler:Qc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Qc})});async function nl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=de?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let il=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=de?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let S=s.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:S},{handler:`sync-trigger`}),g.trigger(S)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?de?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function al(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=de?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let cl=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=de?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:S,strategy:w,content:E}=s;try{await g.resolveConflict(S,w,E),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?de?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function ll(e,s){if(!checkLocalOpSecurity(e,s,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(s,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!me){errorResponse(s,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`file`);if(!S){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=stripDocExtension(S),E=t.documents.get(w)?.getMap(`lifecycle`).get(`status`)===`conflict`,D=de?.(),O=D?D.getConflicts().some(e=>e.file===S):!1;if(!E&&!O){errorResponse(s,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:S}});return}let k=g.searchParams.get(`source`),j=esm_default({baseDir:me,timeout:{block:15e3}});async function F(e){try{return{present:!0,content:await j.raw([`show`,`:${e}:${S}`])}}catch(t){let s=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(s))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:S,detail:s,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,g,w]=await Promise.all([F(1),F(2),F(3)]),E=e.present?e.content:``,D=w.present?w.content:``,O=g.present&&w.present?`both-modified`:!g.present&&w.present?`delete-modify`:g.present&&!w.present?`modify-delete`:`both-modified`,j=g.present?g.content:``,L=null;if(k===`ytext`){let e=stripDocExtension(S),s=t.documents.get(e);if(s){let t=s.getMap(`lifecycle`).get(`status`);if(L=typeof t==`string`&&t.length>0?t:null,O!==`delete-modify`){let t=Te?Te(e):null;t!==null&&!ytextHasConflictMarkers(t)?j=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(s,200,SyncConflictContentSuccessSchema,{file:S,base:E,ours:j,theirs:D,kind:O,lifecycleStatus:L},{handler:`sync-conflict-content`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function ul(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let s=new URL(e.url??`/`,`http://localhost`),S=s.searchParams.get(`rootDir`)??void 0,w=s.searchParams.get(`packId`),E=coercePackId(w);if(w!==null&&w!==``&&E===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${w}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:g,rootDir:S,packId:E})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let dl=withValidation(SeedApplyRequestSchema,async(e,t,s)=>{let S=s.plan;if(!S||typeof S!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let w=S,E=s.packId,D=coercePackId(E);if(typeof E==`string`&&E.length>0&&D===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${E}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(w,{projectDir:g,packId:D})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function fl(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let pl=withValidation(InstallSkillRequestSchema,async(e,t,s)=>{if(s.out!==void 0&&!isSafeLocalPath(s.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...s.noOpen===void 0?{}:{noOpen:s.noOpen},...s.out===void 0?{}:{out:s.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function ml(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Xe.probeAll)}catch(e){t.headersSent||(log$4.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}let hl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ae){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:ae.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function gl(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!ae){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let g;try{g=decodeURIComponent(s)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=ae.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:nt(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:g,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function _l(e,t,s=`path`,S=`folder-config`){let w=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${s}: must be project-root-relative.`,{handler:S}),null;let E=resolve(g),D=w===``?E:resolve(E,w);return D!==E&&!D.startsWith(`${E}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:S}),null):{folderRel:w,resolvedContentDir:E}}let vl=/^[A-Za-z0-9_-]+$/;function yl(e,t,s=`template`){return!e||!vl.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:s}),!1):!0}function xl(e,t,s){let g=t===``?[]:t.split(`/`);for(let t=g.length;t>=0;t--){let S=t===0?``:g.slice(0,t).join(`/`),w=S===``?e:resolve(e,S);if(w!==e&&!w.startsWith(`${e}${sep}`))continue;let E=resolve(w,`.ok`,`templates`,`${s}.md`);if(existsSync(E))return{abs:E,folder:S,scope:t===g.length?`local`:`inherited`}}return null}function Cl(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[s,g]of Object.entries(e))g!==void 0&&(t[s]=g);return t}async function Tl(e,t){if(e.method===`GET`)return El(e,t);if(e.method===`PUT`)return Dl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let El=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=_l(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!s)return;let g=await enrichDirectory(s.folderRel,{projectDir:s.resolvedContentDir}),S=resolve(resolve(s.resolvedContentDir,s.folderRel,`.ok`),`frontmatter.yml`),w=null;if(existsSync(S))try{let e=(0,import_dist$1.parse)(await readFile$1(S,`utf-8`));w=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${S}: ${t}`),w=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:g,frontmatter_local:w},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Dl=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(Me){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,ge);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let g=_l(s.path,t,`path`,`folder-config-put`);if(!g)return;let S=[];if(s.frontmatter!==void 0){let w=applyFolderFrontmatterPatch({anchorDir:g.resolvedContentDir,folderRel:g.folderRel,patch:s.frontmatter});if(!w.ok){let e=w.error.code===`WRITE_ERROR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push({path:w.path,action:w.action}),w.action!==`noop`&&(ji(e,Qr(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Hi(`folder-config-put`))}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:S},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function Ol(e,s,g,S){if(!s)return!1;let w=e===``?`.ok/templates/${s}`:`${e.replace(/\/$/,``)}/.ok/templates/${s}`,E=t.documents.get(w);return E&&isDocInConflict(E)?(respondDocInConflict(S,new DocInConflictError({file:`${w}.md`}),g),!0):!1}let kl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=resolveProjectTemplates(resolve(g));successResponse(t,200,TemplatesListSuccessSchema,{templates:e.templates.map(e=>{let{scope:t,...s}=e;return s}),truncated:e.truncated},{handler:`templates-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function jl(e,t){if(e.method===`GET`)return Fl(e,t);if(e.method===`PUT`)return Il(e,t);if(e.method===`POST`)return Rl(e,t);if(e.method===`DELETE`)return Ll(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Ml=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Pl=e=>{let t=e.match(Ml),s={},g=e;if(t){try{let e=(0,import_dist$1.parse)(t[1]??``);e&&typeof e==`object`&&!Array.isArray(e)&&(s=e)}catch{}g=e.slice(t[0].length)}return{frontmatter:s,body:g}},Fl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!yl(g,t,`template-get`))return;let S=_l(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=xl(E,w,g);if(!D){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${g}" not found for folder "${w||`.`}". Walked leaf → root.`});return}let{abs:O,folder:k,scope:j}=D,{frontmatter:F,body:L}=Pl(await readFile$1(O,`utf-8`));successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:F,body:L}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),Il=withValidation(TemplatePutRequestSchema,async(e,t,s)=>{try{if(Me){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(s,ge);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let g=s.name;if(!yl(g,t,`template-put`))return;let S=_l(s.folder,t,`folder`,`template-put`);if(!S||Ol(S.folderRel,g,`template-put`,t))return;let w=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g,body:typeof s.body==`string`?s.body:``,frontmatter:Cl(s.frontmatter)});if(!w.ok){let e=w.error.code===`WRITE_ERROR`||w.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write template.`:`Invalid template request.`,{handler:`template-put`,detail:w.error.code,cause:Error(w.error.message)});return}ji(e,Qr(`template`,S.folderRel,g),`${w.created?`template-create`:`template-edit`}: ${w.path}`),await Hi(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:w.path,created:w.created,warnings:w.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Ll=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!yl(g,t,`template-delete`))return;let S=_l(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S)return;let w=s.searchParams,E=extractActorIdentity({agentId:w.get(`agentId`)??void 0,agentName:w.get(`agentName`)??void 0,colorSeed:w.get(`colorSeed`)??void 0,clientName:w.get(`clientName`)??void 0,clientVersion:w.get(`clientVersion`)??void 0,label:w.get(`label`)??void 0,summary:w.get(`summary`)??void 0},ge);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Ol(S.folderRel,g,`template-delete`,t))return;let D=applyTemplateDelete({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}D.existed&&(ji(E,Qr(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Hi(`template-delete`)),successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),Rl=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,ge);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!yl(s.fromName,t,`template-move`)||!yl(s.toName,t,`template-move`))return;let g=_l(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=_l(s.toFolder,t,`folder`,`template-move`);if(!S||Ol(g.folderRel,s.fromName,`template-move`,t))return;let w=await applyTemplateMove({projectDir:g.resolvedContentDir,fromFolder:g.folderRel,fromName:s.fromName,toFolder:S.folderRel,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(me,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=xl(g.resolvedContentDir,g.folderRel,s.fromName);if(e?.scope===`inherited`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${s.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${g.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:w.error.message});return}if(w.error.code===`TEMPLATE_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,w.error.message,{handler:`template-move`,detail:w.error.code});return}let e=w.error.code===`WRITE_ERROR`||w.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:w.error.code,cause:Error(w.error.message)});return}let E=null;if(s.body!==void 0||s.frontmatter!==void 0){let e;if(typeof s.body==`string`)e=s.body;else try{e=Pl(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`)).body}catch{e=null}if(e===null)E={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:s.toName,body:e,frontmatter:Cl(s.frontmatter)});t.ok||(E=t.error)}}if(ji(e,Qr(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Hi(`template-move`),oe?.(`files`),E){let e=E.code===`WRITE_ERROR`||E.code===`READ_FAILED`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${w.toPath}", but updating its content failed.`,{handler:`template-move`,detail:E.code,cause:Error(E.message)});return}successResponse(t,200,TemplateMoveSuccessSchema,{from:w.fromPath,to:w.toPath,committed:w.committed},{handler:`template-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`});function zl(e){let t=new Map;for(let s of e){let e=s.path.split(`/`).filter(Boolean);e.pop();for(let g=1;g<=e.length;g++){let S=e.slice(0,g).join(`/`);t.set(S,Math.max(t.get(S)??0,s.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function Bl(e,t){let s=t.trim().toLowerCase();if(!s||!e)return;let g=e.toLowerCase().indexOf(s);if(g<0)return;let S=Math.max(0,g-80),w=Math.min(e.length,g+s.length+120),E=S>0?`…`:``,D=w<e.length?`…`:``;return`${E}${e.slice(S,w).replace(/\s+/g,` `).trim()}${D}`}function Vl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Hl(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let s=t.filter(e=>e===`page`||e===`folder`||e===`content`);return s.length>0?s:void 0}function Ul(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}async function Wl(e,t,s,g){let S=g.documents.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!De?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:S,capable:!1};De.embedCorpus(g.documents);let w,E=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await De.queryScores(e,g.documents);E=performance.now()-t,s&&s.size>0&&(w={scores:s})}let D=De.getStatus();return{input:w,status:{capable:D.capable,applied:!1,coverage:{embedded:D.embeddedCount,total:S}},queryEmbedMs:E,pageTotal:S,capable:D.capable}}function Gl(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Bl(e.document.content,t):void 0}}async function Kl(e){let t=performance.now(),s=await Yl(),g=await Wl(e.query,e.intent,e.semanticParam,s),S=searchWorkspaceCorpus(s,e.query,{intent:e.intent,scopes:e.scopes,limit:e.limit,semantic:g.input}).map(t=>Gl(t,e.query)),w;if(g.status){let e=S.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),t=e>0;w={...g.status,applied:t},recordSemanticQuery({outcome:g.capable?t?`applied`:g.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,capable:g.capable,embedded:g.status.coverage.embedded,total:g.pageTotal,queryEmbedMs:g.queryEmbedMs,vectorContributors:e})}return{query:e.query,intent:e.intent,results:S,elapsedMs:Math.max(0,performance.now()-t),...w?{semantic:w}:{}}}async function ql(){let e=[];for(let[t,s]of w()){if(isSystemDoc(t)||isConfigDoc(t)||isHiddenDocName(t))continue;let g=``,S=t;try{g=await readFile$1(s.canonicalPath,`utf-8`),S=extractPageTitle(g,t)}catch(e){console.warn(`[search] Failed to index ${t}:`,e)}e.push(createWorkspaceSearchDocument({kind:`page`,path:t,title:S,content:g,modifiedTs:Date.parse(s.modified)}))}return[...e,...zl(e)]}function Jl(){return[...w()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}${t.modified}${t.size}${t.canonicalPath}${t.inode}${t.aliases.join(`,`)}`).join(``)}async function Yl(){let e=`${g}${me??``}`,t=Jl(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return s.corpus;if(s?.fingerprint===t&&s.pending)return s.pending;let S=ql().then(e=>createWorkspaceSearchCorpus(e));workspaceSearchCaches.set(e,{fingerprint:t,pending:S});try{let s=await S;return workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:s}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function Xl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{Yl().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}Xl();async function Zl(e,t){if(e.method===`GET`)return Ql(e,t);if(e.method===`POST`)return $l(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let Ql=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Vl(s.searchParams.get(`intent`)),E=Hl(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),D=Ul(s.searchParams.get(`semantic`)),O=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await Kl({query:S,intent:w,scopes:E,limit:O,semanticParam:D}),{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),$l=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Vl(s.intent),w=Hl(s.scopes??s.scope),E=typeof s.limit==`number`?s.limit:void 0,D=Ul(s.semantic);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await Kl({query:g,intent:S,scopes:w,limit:E,semanticParam:D}),{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),eu=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function tu(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$4.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function nu(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$4.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let ru=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!me){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidSharePath(s.kind===`doc`?s.docPath:s.folderPath,s.kind)){emitShareConstructUrlLog(`invalid-path`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=readGitHeadBranch(me);if(e===null){if(readOriginGitHubRepo(me).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let S=readOriginGitHubRepo(me);if(S.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(S.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(me,e)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=toGitRelativePath(me,g);if(w===null)throw Error(`content dir is not contained within the project dir`);let E=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;w!==``&&E&&getLogger(`share`).warn({action:`construct-url`,kind:s.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let D;if(s.kind===`doc`)D=buildGitHubBlobUrl(S.owner,S.repo,e,s.docPath);else{let t=s.folderPath===``?w:s.folderPath;D=buildGitHubTreeUrl(S.owner,S.repo,e,t)}let O=`${SHARE_BASE_URL}${encodeShareUrl(D)}`;emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:O,sharedUrl:D,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),iu=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!me){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`branch`),S=s.searchParams.get(`path`),w=s.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!isValidBranchName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoPath(S,w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(me,g,S,w),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),au=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,ge).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!me){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(me,s.branch)),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function ou(e){let[t,...s]=fe,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,S.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),D=[],O=[];S.stdout.on(`data`,e=>D.push(e)),S.stderr.on(`data`,e=>O.push(e)),S.on(`close`,t=>{if(clearTimeout(E),w){s(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let g=Buffer.concat(D).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(O).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:g,code:t})}),S.on(`error`,e=>{clearTimeout(E),s(e)})})}let su=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Pe.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ou([`share`,`owners`,`--json`]),s=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,s.ok?`ok`:s.error,s.ok?{count:s.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,s,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{Pe.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),cu=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`owner`)??``,S=s.searchParams.get(`name`)??``;if(!isValidShareOwnerName(g)||!isValidShareRepoName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!Pe.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ou([`share`,`name-check`,`--owner`,g,`--name`,S,`--json`]),s=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,s.ok?`ok`:s.error,s.ok?{available:s.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,s,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{Pe.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),lu=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!me){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(s.owner)||!isValidShareRepoName(s.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!Pe.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,s.owner,`--name`,s.name,`--visibility`,s.visibility,`--project-dir`,me,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await ou(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&de?.()?.refreshRemote().catch(()=>{}),successResponse(t,200,SharePublishResponseSchema,S,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{Pe.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),uu=withValidation(ClientLogsRequestSchema,async(e,t,s)=>{try{let e=getLogger(`renderer`);for(let t of s.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}successResponse(t,200,ClientLogsSuccessSchema,{accepted:s.entries.length},{handler:`client-logs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`client-logs`})}),du=me?getLocalDir(me):null;async function fu(e,t){if(e.method===`DELETE`){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-config`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-config`});return}du&&clearArmedPaneTarget(du),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:du?readServerLock(du)?.port??0:0,paneTarget:du?readArmedPaneTarget(du):null,singleFile:Me};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}successResponse(t,200,ApiConfigSuccessSchema,g,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD, DELETE`}})}let pu=`local-op-embeddings-set-key`,mu=`local-op-embeddings-clear-key`,hu=`/api/local-op/embeddings`,gu=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Pe.tryAcquire(hu)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:pu,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(je).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:pu,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:pu,cause:e})}finally{Pe.release(hu)}},{handler:pu,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:pu})}),_u=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Pe.tryAcquire(hu)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:mu,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(je),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:mu,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:mu,cause:e})}finally{Pe.release(hu)}},{handler:mu,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:mu})}),vu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(De){let t=De.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(je).get()?`file`:process.env.OK_EMBEDDINGS_API_KEY?`env`:null,D=E!==null,O=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(O+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:D,keySource:E,ready:s,capable:g,embedded:S,total:O},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),yu={"/api/config":fu,"/api/asset":dc,"/api/asset-text":pc,"/api/document":Xi,"/api/documents":Zi,"/api/backlinks":ka,"/api/backlink-counts":_s,"/api/forward-links":xs,"/api/link-graph":Cs,"/api/dead-links":Os,"/api/orphans":Ts,"/api/hubs":Ds,"/api/tags":hl,"/api/pages":Cc,"/api/folder-config":Tl,"/api/template":jl,"/api/templates":kl,"/api/search":Zl,"/api/semantic-status":vu,"/api/suggest-links":wc,"/api/page-headings":yc,"/api/create-page":gc,"/api/create-folder":_c,"/api/duplicate-path":vc,"/api/rename-path":bc,"/api/delete-path":xc,"/api/trash/cleanup":Sc,"/api/upload":Tc,"/api/agent-write":Ui,"/api/agent-write-md":Gi,"/api/frontmatter-patch":Ki,"/api/agent-patch":ks,"/api/agent-undo":As,"/api/agent-activity":Ns,"/api/agent-burst-diff":Ps,"/api/save-version":ec,"/api/history":tc,"/api/rollback":rc,"/api/metrics/reconciliation":ic,"/api/metrics/parse-health":ac,"/api/metrics/agent-presence":cc,"/api/__embed-detect":lc,"/api/server-info":oc,"/api/share/construct-url":ru,"/api/git/branch-info":iu,"/api/git/checkout":au,"/api/share/publish/owners":su,"/api/share/publish/name-check":cu,"/api/share/publish":lu,"/api/principal":sc,"/api/rescue":hc,"/api/workspace":uc,"/api/sync/status":nl,"/api/sync/trigger":il,"/api/sync/conflicts":al,"/api/sync/conflict-content":ll,"/api/sync/resolve-conflict":cl,"/api/local-op/clone":jc,"/api/local-op/ok-init":Fc,"/api/local-op/auth/login":Hc,"/api/local-op/auth/status":Gc,"/api/local-op/auth/repos":qc,"/api/local-op/auth/signout":Xc,"/api/local-op/auth/set-identity":$c,"/api/local-op/embeddings/set-key":gu,"/api/local-op/embeddings/clear-key":_u,"/api/installed-agents":ml,"/api/spawn-cursor":nu,"/api/handoff":tu,"/api/install-skill":pl,"/api/skill/install-state":eu,"/api/seed/plan":ul,"/api/seed/apply":dl,"/api/seed/packs":fl,"/api/client-logs":uu};j&&(yu[`/api/test-reset`]=Is,yu[`/api/test-rescan-backlinks`]=Rs,yu[`/api/test-rescan-files`]=$s);let bu=new Set([`/api/upload`,`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/agent-write`,`/api/agent-write-md`,`/api/frontmatter-patch`,`/api/agent-patch`,`/api/agent-undo`,`/api/save-version`,`/api/rollback`,`/api/sync/trigger`,`/api/sync/resolve-conflict`,`/api/git/checkout`,`/api/test-reset`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/install-skill`,`/api/folder-config`,`/api/template`,`/api/seed/apply`,`/api/client-logs`]),xu=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let s=e.url?.split(`?`)[0];if(!s)return;let g=t=>{let s=e.headers[t];if(s!==void 0)return Array.isArray(s)?s.join(`, `):s};if(recordEmbedProbe({ts:Date.now(),url:s,method:e.method??``,ua:g(`user-agent`),origin:g(`origin`),referer:g(`referer`),host:g(`host`),remote:e.socket?.remoteAddress,secChUa:g(`sec-ch-ua`),secChUaMobile:g(`sec-ch-ua-mobile`),secChUaPlatform:g(`sec-ch-ua-platform`),secFetchSite:g(`sec-fetch-site`),secFetchDest:g(`sec-fetch-dest`),secFetchMode:g(`sec-fetch-mode`),secFetchUser:g(`sec-fetch-user`)}),s.startsWith(`/api/`)){let s=e.headers.origin;if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(bu.has(s)||xu.some(e=>s.startsWith(e))){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(Me&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:yu[s]||(E=`/api/*`);let D=getTracer(),O=Date.now();await context.with(S,()=>D.startActiveSpan(`HTTP ${w} ${E}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_URL_PATH]:s,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async g=>{try{let S=yu[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await nc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await gl(e,t,g))}E||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${w} ${s}`});let D=t.statusCode;g.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,D),D>=500&&g.setStatus({code:SpanStatusCode.ERROR,message:`status ${D}`})}catch(e){throw g.recordException(e),g.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E,cause:e}),e}finally{g.end();let e=(Date.now()-O)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function isWithinDir(e,t){return e===t?!0:e.startsWith(`${t}${sep}`)}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}async function seedBasenameIndex(e){let t=e.contentDir,s=new Set;async function g(S){let w;try{w=await readdir(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=relative(t,w);if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=await lstat(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=await realpath(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=await stat$1(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?await g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),await g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}await g(t)}const log$3=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$3.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$3.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$3.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,s,g=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:S}=await import(`./git-handle-CTJE6H8P-aY9Efmma.mjs`),w=S(this.projectDir,{credentialArgs:g});switch(t){case`mine`:await w.git.raw([`checkout`,`--ours`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`theirs`:await w.git.raw([`checkout`,`--theirs`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`content`:{if(s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),g=resolve(t,e);if(g!==t&&!g.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(g,s,`utf-8`),await w.git.raw([`add`,`--`,e]);break}case`delete`:await w.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await w.git.raw([`commit`,`--no-edit`]),log$3.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=(await w.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
|
|
1713
1712
|
`).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:s});g=e.length>0}catch(e){log$3.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}g||this.addConflict({file:e,detectedAt:s}),log$3.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let S=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${g?`unmerged files re-added`:`original file re-added`} — ${S}`,{cause:t})}}};const MIN_GIT_VERSION=`2.31.0`,PROBE_TIMEOUT_MS$1=5e3;var GitNotAvailableError=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;constructor(e,t,s){super(buildMissingMessage(t),s),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t}},GitTooOldError=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,s,g,S,w){super(buildTooOldMessage(t,s,g,S),w),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=s,this.resolvedPath=g,this.guidance=S}};function detectGit(){let e=probeGit(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};for(let e of fallbackPaths(process.platform)){if(!existsSync(e))continue;let t=probeGit(e);if(t.kind===`ok`)return{ok:!0,version:t.version,resolvedPath:e,source:`fallback`}}throw new GitNotAvailableError(process.platform,buildGuidance(process.platform))}function assertGitAvailable(){let e=detectGit();if(compareSemver(e.version,`2.31.0`)<0)throw new GitTooOldError(process.platform,e.version,MIN_GIT_VERSION,e.resolvedPath,buildGuidance(process.platform));return e}function probeGit(e){let t=spawnSync(e,[`--version`],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1,env:{...process.env,LANG:`C`,LC_ALL:`C`}});if(t.error)return`signal`in t&&t.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:`enoent`};if(t.status!==0)return{kind:`fail`,reason:`nonzero`};let s=parseGitVersion(typeof t.stdout==`string`?t.stdout:``);return s===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:s,resolvedPath:e===`git`?resolveOnPath(`git`)??e:e}}function parseGitVersion(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const SAFE_COMMAND_NAME_RE=/^[a-zA-Z0-9_.-]+$/,resolveOnPathCache=new Map;function resolveOnPath(e){if(!SAFE_COMMAND_NAME_RE.test(e))return null;let t=resolveOnPathCache.get(e);if(t!==void 0)return t;let s;if(process.platform===`win32`){let t=spawnSync(`where`,[e],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1});s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}else{let t=spawnSync(`/bin/sh`,[`-c`,`command -v ${e}`],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1});s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}return s!==null&&resolveOnPathCache.set(e,s),s}function fallbackPaths(e){switch(e){case`darwin`:return[`/opt/homebrew/bin/git`,`/usr/local/bin/git`,`/Library/Developer/CommandLineTools/usr/bin/git`,`/usr/bin/git`];case`win32`:return[`C:\\Program Files\\Git\\cmd\\git.exe`,`C:\\Program Files (x86)\\Git\\cmd\\git.exe`,join(homedir(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,join(homedir(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function buildGuidance(e){switch(e){case`darwin`:{let e=[];return hasBrew()&&e.push({label:`Install with Homebrew (recommended; no admin needed)`,command:`brew install git`,requiresAdmin:!1}),e.push({label:`Install Xcode Command Line Tools`,command:`xcode-select --install`,requiresAdmin:!0}),{product:`Git`,url:`https://git-scm.com/download/mac`,options:e}}case`win32`:{let e=[];return hasWinget()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),hasScoop()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),hasChoco()&&e.push({label:`Install with Chocolatey`,command:`choco install git -y`,requiresAdmin:!0}),e.push({label:`Download the official installer`,command:`Open https://gitforwindows.org/ in your browser`,requiresAdmin:!1}),{product:`Git for Windows`,url:`https://gitforwindows.org/`,options:e}}default:return{product:`Git`,url:`https://git-scm.com/download/linux`,options:linuxInstallOptions()}}}function linuxInstallOptions(){switch(detectLinuxFamily()){case`debian`:return[{label:`Install with apt`,command:`sudo apt install git`,requiresAdmin:!0}];case`fedora`:return[{label:`Install with dnf`,command:`sudo dnf install git`,requiresAdmin:!0}];case`arch`:return[{label:`Install with pacman`,command:`sudo pacman -S git`,requiresAdmin:!0}];case`opensuse`:return[{label:`Install with zypper`,command:`sudo zypper install git`,requiresAdmin:!0}];case`alpine`:return[{label:`Install with apk`,command:`sudo apk add git`,requiresAdmin:!0}];default:return[{label:`Use your distribution's package manager`,command:`apt / dnf / pacman / zypper / apk install git (one of these will fit your system)`,requiresAdmin:!0}]}}function detectLinuxFamily(e){let t=e;if(t===void 0)try{t=readFileSync(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let s=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return s.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:s.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:s.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:s.some(e=>/^opensuse/i.test(e))||s.includes(`suse`)?`opensuse`:s.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function hasCommand(e){return resolveOnPath(e)!==null}function hasBrew(){return hasCommand(`brew`)}function hasWinget(){return hasCommand(`winget`)}function hasScoop(){return hasCommand(`scoop`)}function hasChoco(){return hasCommand(`choco`)}function buildMissingMessage(e){let t=[];if(t.push(`Open Knowledge needs ${e.product} to track changes to your knowledge base, but it isn't installed (or isn't on PATH).`),t.push(``),e.options.length>0){t.push(`Install ${e.product}:`);for(let s of e.options){let e=s.requiresAdmin?` (admin required)`:``;t.push(` • ${s.label}${e}`),t.push(` ${s.command}`)}t.push(``)}return t.push(`Or download from: ${e.url}`),t.push(``),t.push(`After installing, re-run Open Knowledge.`),t.push("Run `ok diagnose health --check git` to verify your installation."),t.join(`
|
|
1714
1713
|
`)}function buildTooOldMessage(e,t,s,g){let S=[];if(S.push(`Open Knowledge requires ${g.product} ${t} or newer (detected ${e} at ${s}).`),S.push(``),g.options.length>0){S.push(`Update ${g.product}:`);for(let e of g.options){let t=e.requiresAdmin?` (admin required)`:``;S.push(` • ${e.label}${t}`),S.push(` ${e.command}`)}S.push(``)}return S.push(`Or download from: ${g.url}`),S.push(``),S.push(`After updating, re-run Open Knowledge.`),S.push("Run `ok diagnose health --check git` to verify your installation."),S.join(`
|
|
1715
1714
|
`)}function compareSemver(e,t){let s=e.split(`.`).map(e=>Number.parseInt(e,10)||0),g=t.split(`.`).map(e=>Number.parseInt(e,10)||0);for(let e=0;e<3;e++){let t=s[e]??0,S=g[e]??0;if(t!==S)return t-S}return 0}const GIT_PREFLIGHT_FAIL_SPAN_NAME=`ok.preflight.git.fail`;function emitPreflightFailureSpan(e){let t=e instanceof GitTooOldError?`too_old`:`not_available`,s=e instanceof GitTooOldError?e.detected:``;withSpanSync(GIT_PREFLIGHT_FAIL_SPAN_NAME,{attributes:{"ok.platform":e.platform,"ok.preflight.git.reason":t,"ok.preflight.git.detected_version":s}},()=>{})}const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,s=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,g=0,S=null,w=null,E=!1,D=!1;function O(){S!==null&&(t.clearTimeout(S),S=null),w!==null&&(t.clearTimeout(w),w=null)}function k(){O(),!(D||E)&&g===0&&(s>0&&s<e.thresholdMs&&(w=t.setTimeout(()=>{w=null,g===0&&!E&&e.log?.warn({msUntilShutdown:s,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-s)),S=t.setTimeout(()=>{if(S=null,!(D||E)&&g===0){E=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let j=(e,t)=>{e.url?.startsWith(`/collab`)&&(g++,O(),t.once(`close`,()=>{g--,g<0&&(g=0),g===0&&k()}))};return e.httpServer.on(`upgrade`,j),k(),{detach:()=>{D||(D=!0,e.httpServer.off(`upgrade`,j),O())}}}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function readRawSinkBlock(e){if(!existsSync(e))return{};let t;try{t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!isObject(t))return{};let s=t.telemetry;if(!isObject(s))return{};let g=s.localSink;return isObject(g)?g:{}}function readBoolean(e){return typeof e==`boolean`?e:void 0}function readPositiveNumber(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function readStringArray(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function readMaxBytes(e){if(isObject(e))return readPositiveNumber(e.maxBytes)}function resolveLocalSinkConfig(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=readRawSinkBlock(resolveConfigPath(`project`,e.projectDir)),s=readRawSinkBlock(resolveConfigPath(`project-local`,e.projectDir));if((readBoolean(s.enabled)??readBoolean(t.enabled)??!0)===!1)return null;let g=readMaxBytes(s.spans)??readMaxBytes(t.spans)??52428800,S=readMaxBytes(s.logs)??readMaxBytes(t.logs)??26214400,w=readStringArray(s.attributeDenylist)??readStringArray(t.attributeDenylist)??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:g,attributeDenylist:w},logs:{projectDir:e.projectDir,maxBytes:S}}}const MCP_SERVER_NAME=`open-knowledge`,MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let s=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return s?s.slice(0,128):t}function buildInstructions(e){return'Open Knowledge is a markdown-CRDT knowledge base exposed via MCP.\n\n## STOP — native tools on in-scope `.md` / `.mdx`\n\nWhen this workspace has Open Knowledge MCP configured, do **not** use your host\'s native file tools on markdown paths inside the content directory. The ban covers every common rationalization:\n\n- **Native `Read` / `Grep` / `Glob` on in-scope `.md` / `.mdx`** — the original case.\n- **`Bash ls` / `Bash find` / `Bash cat` on dirs containing in-scope markdown** — use `exec("ls -A …")` / `exec("find … -name \'*.md\'")` / `exec("cat …")` instead. Native returns bare names; `exec` returns frontmatter, backlink counts, and recent activity per child. `-A` shows hidden entries (`.ok/`, `.okignore`) which OK projects carry; omit `.` and `..` rows that `-a` would add.\n- **Glob patterns that target markdown** (`**/*.md`, any dir known to be markdown-heavy like `specs/**`, `reports/**`, `docs/**`) — use `exec` with `find`, or `exec("ls -A <dir>")`.\n- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native `Read` / `Grep` / `Glob` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via `exec` / `search`. Subagents remain appropriate for **source-code** exploration.\n- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.\n\nWhy: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK\'s tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut`) and returns raw stdout plus enriched metadata per file. One command or a pipe (`|`) per call — it is NOT a shell, so `&&` / `;` / redirects are rejected; list several dirs with `ls -A a b c` or make separate calls.\n\n**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named `exec` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its `exec` / `search` via your client\'s documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.\n\n**Escape hatch.** Native `Read` / `Grep` / `Glob` on `.md` / `.mdx` is allowed **only** when no Open Knowledge MCP server is registered for this project, **or** immediately after you tried an MCP call and it failed — then begin a user-visible sentence with `Open Knowledge MCP unavailable:`. Never use the hatch because you skipped your client\'s MCP path, didn\'t see `exec` as a top-level tool, or rationalized the skill wasn\'t necessary.\n\n**Source code and non-markdown files** (`.ts`, `.py`, `package.json`, …): native `Read` / `Grep` / `Glob` always.\n\n## Reads — examples\n\n- Read a file: `exec("cat <path>.md")` — contents + full rich enrichment.\n- List a directory: `exec("ls -A <dir>")` — per-child frontmatter, recursive markdown counts, most-recently-updated doc per subdir, the folder\'s own `title`/`description`/`tags` + `templates_available`. Prefer `-A` over plain `ls` to surface dot-prefixed entries (`.ok/`, `.okignore`) without the noisy `.`/`..` rows that `-a` adds.\n- Literal search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files.\n- Ranked search: `search({ query })` — cmd-K parity (title boost + body BM25 + recency); use when picking the best doc, not when listing every occurrence.\n\n## Preview — open the browser at session start\n\nThe user watches your edits land in a live browser preview. Open it once at session start, then keep working. Re-navigate only when the user asks to open a different doc, or to land them on a finished deliverable (see below) — not to re-check your own edits.\n\n**End a turn on the deliverable, not your scratch space.** Keep the preview steady *during* a multi-doc task — don\'t yank it around to re-check your own edits. But when a turn created or substantially changed user-facing docs, navigate the preview to the primary deliverable before you hand back: the hub / overview / index page when you created several docs, or the changed doc when you changed one. Don\'t step the user through every supporting source card — the user is watching, so leave them on the result.\n\n**`previewUrl` is a route, not a URL to open.** Every read response (per-doc, on `exec` / `search` / `links` rows) and every write response carries a `previewUrl` — a route fragment like `/#/specs/foo/SPEC`, with **no scheme, host, or port**. It identifies *which doc* to preview, not a URL to hand a browser by itself. Never construct or guess preview URLs.\n\n**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session. If a tool can navigate to a URL, it counts as an in-app browser — match on the capability, not on what your host is called.\n\n- **You have `preview_*` tools** (e.g. `preview_start` + `preview_eval`) → **First open of the session:** to land directly on a doc, arm it first with `preview_url({ armPaneTarget: true, document })` (or `folder`), then `preview_start("open-knowledge-ui")` — `ok ui` redirects the base-open straight to the armed route, so the pane opens on the doc, not root. Plain `preview_start` (no arm) opens at root. **Moving between docs once the pane is open: do it in one `preview_eval` step — set `window.location.hash` to the target\'s route fragment from the response `previewUrl`, the part from `#` on (e.g. `window.location.hash = \'#/specs/foo/SPEC\'`).** That drives the SPA router directly. Arm + `preview_start` only redirects a *fresh* open; it can\'t move an already-open pane (`preview_start` reuses the live process without reloading), so use `preview_eval` there. Don\'t read or edit `.claude/launch.json` — host-managed; the OK lock-collision proxy handles the UI-already-running case. If `preview_start` fails, report it; don\'t "fix" `launch.json`.\n- **No `preview_*` tool, but you have an in-app / built-in browser tool** — Codex\'s built-in browser, or any host tool that navigates to a URL (`browser`, `view_url`, `open_url`, `web.browse`, etc.) → call `preview_url` once for the **exact** target (`document` for a doc, `folder` for a folder) and navigate your **in-app browser** straight to the returned `url`. Open that deep URL directly — never the root then navigate. Omit both args only for the root.\n- **Truly no browser-capable tool — if you have ANY tool that navigates to a URL, use the in-app branch above** (a pure stdio host with no URL-navigation tool at all, e.g. the Claude Code CLI) → for an "open `<doc>`/`<folder>`" request, run **`ok open <doc>`** (`--folder` for a folder) — opens the doc in OK Desktop via deep link (folders in the browser), with browser fallback; an action, not a URL to print. No `ok` on PATH or no shell → `preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly. The system browser is the fallback, never the default.\n- **Honor `autoOpen`** (on `preview_url`, or on `warning` for write tools). If `false`, do not open or refresh any preview UI; surface the URL only if asked.\n\n**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc\'s `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.\n\n**Four signals to check if the preview is already attached** (read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null route) and NO `warning` → a browser is attached somewhere; do nothing.\n3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot (`preview_start`, or `preview_url` → in-app browser).\n4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don\'t loop on retries.\n\nWarnings fire at most once per session in the fresh-start case.\n\n**`previewUrl: null` only means "no UI reachable" on the two attach-warning tools: `write` / `edit`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete` / `move` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings. `preview_url` reports `running: false` + `url: null` when no UI is running.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry.\n\nOK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port, the OK lock-collision proxy bridges it to the live server transparently. That is exactly why `previewUrl` is route-only — the port behind the proxy is not the agent\'s to use. **Do not nudge the user to quit OK Electron to free a port** — the proxy handles it, and quitting tears down a UI in active use.\n\n**The preview is read-only for the agent — it is the user\'s view, not a surface you read back.** You cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK\'s preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed. (Navigating the pane with `preview_eval` by setting `window.location.hash` is fine — that drives the view, it is not a read-back verification loop.)\n\n## Scope recap\n\nOpen Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `config({ key: \'content.dir\' })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. A folder\'s own metadata + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` — NOT in `.ok/config.yml`.\n\nDefault mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what\'s excluded.\n\n**First session in this project?** If substantial folders have no frontmatter of their own and no `templates_available`, the project isn\'t onboarded — invoke `workflow({ kind: \'discover\' })` before writing.\n\n\nFull guidance lives in the bundled `open-knowledge` skill at `~/.ok/skills/open-knowledge/SKILL.md`.\n'}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let s=t.validateToolInput;if(typeof s!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,g){if(!e.inputSchema||!isZodSchema(e.inputSchema))return s.call(this,e,t,g);let S=await e.inputSchema.safeParseAsync(t);if(S.success)return S.data;let w=prettifyError(S.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${g}:\n${w}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,s={}){let g=t?{error:t instanceof Error?t.message:String(t),...s}:s;this.emit(`error`,e,g)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,s){let g={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...s},S=`${JSON.stringify(g)}\n`;process.stderr.write(S);let w=process.env.OK_LOG_FILE;if(w)try{appendFileSync(w,S)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
|
|
@@ -2814,19 +2813,19 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
2814
2813
|
`),H={documents:O},q=D.find(e=>e.ok);return q&&q.raw.systemSubscriberCount===0&&(H.warning=buildPreviewAttachWarning(resolvePreviewUrl(q.docName,{lockDir:w}),E)),textPlusStructured(B,H,!j)}async function handleSingleDoc(e,t,s,g,S,w,E){let D=await writeOneDoc(e,t,s,g,S);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.raw,k=resolvePreviewUrl(D.docName,{lockDir:w}),j=typeof O.subscriberCount==`number`?O.subscriberCount:void 0,F=(typeof O.systemSubscriberCount==`number`?O.systemSubscriberCount:void 0)===0,L=j===0,B=Array.isArray(O.hints)?O.hints:void 0,H=O.summary&&typeof O.summary==`object`?O.summary:void 0,q=typeof H?.hint==`string`?H.hint:void 0,ee=parseContentDivergence(O.warning),J=[emptyAppendNoOpNote(D.position,e.content)??(D.fromTemplate===void 0?`Written successfully (${D.position}).`:`Written successfully (instantiated from template "${D.fromTemplate}").`)],Y=frontmatterIgnoredNote(D.position,e.content);if(Y&&J.push(Y),D.extensionNote&&J.push(D.extensionNote),F&&!k&&J.push(START_UI_TEXT_HINT),q&&J.push(q),B)for(let e of B)e.message&&J.push(e.message);ee&&J.push(formatContentDivergenceLine(ee));let te=J.join(`
|
|
2815
2814
|
`);if(!k&&!F&&!L&&!B&&!H&&!ee)return textResult(te);let ne={};return B&&(ne.hints=B),H&&(ne.summary=H),ee&&(ne.contentDivergence=ee),textPlusStructured(te,nestDocResult(k,F?buildPreviewAttachWarning(k,E):void 0,ne))}function register(e,t){let s={path:string().describe(`Document path, no extension. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup".`),content:string().optional().describe("The full Markdown body. Mutually exclusive with `template`."),template:string().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:FrontmatterArg.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:PositionArg.optional()};e.registerTool(`write`,{description:DESCRIPTION,inputSchema:{document:object$1(s).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:object$1({path:string().describe(`Folder path. Example: "meetings".`),frontmatter:FrontmatterArg.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),content:string().describe(TEMPLATE_CONTENT_DESCRIBE),frontmatter:object$1({title:string().min(1).describe(`Required — the label shown when an agent picks this template.`),description:string().optional().describe(`Optional — shown beside the title in the template menu.`),tags:array(string()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:string().optional().describe(`Base64 of the binary. Use for small files.`),source:string().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:array(object$1({...s,summary:summaryArgSchema})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({hints:looseObjectArray.optional().describe(`Server-provided write hints, when any.`),...documentResultBaseShape}).optional().describe(`Single-document write result (present when there is a doc-specific signal).`),folder:object$1({ok:boolean(),path:string(),frontmatterError:string().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:object$1({ok:boolean(),path:string(),created:boolean().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),asset:object$1({ok:boolean(),src:string().optional().describe(`The reference src to embed in a doc.`),path:string().optional(),deduped:boolean().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:looseObjectArray.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, contentDivergence?, error? }`."),previewUrl:previewUrlOutputField.optional(),previewUrlSource:previewUrlSourceField,warning:previewAttachWarningField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s,E=resolveLockDir(g),D=resolveContentDir(S,g),O=S.appearance.preview.autoOpen;if(e.documents!==void 0){let s=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`,`documents`]);return s?textResult(`Error: ${s}`,!0):w?handleBatch(e.documents,g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)}let k=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`]);return k?textResult(`Error: ${k}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?handleAsset(e.asset,g,w,t):handleTemplate(e.template,e.summary,w,t):handleFolder(e.folder,e.summary,w,t):w?handleSingleDoc({...e.document,summary:e.summary},g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)})}function registerAllTools(e,t){let s=t.logger,g=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),S=e=>async g=>{try{let S=await t.resolveCwd(g);return(getCurrentMcpLogger()??s)?.debug(`tool cwd resolved`,{tool:e,cwd:S,...g?{explicit:g}:{}}),S}catch(t){throw(getCurrentMcpLogger()??s)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...g?{explicit:g}:{}}),t}};register$11(g,{resolveCwd:S(`exec`),serverUrl:t.serverUrl,config:t.config}),register$1(g,{config:t.config,resolveCwd:S(`workflow`)}),register$3(g,{resolveCwd:S(`search`),config:t.config,serverUrl:t.serverUrl}),register$8(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`links`)}),register(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`write`),identityRef:t.identityRef}),register$12(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`edit`),identityRef:t.identityRef}),register$13(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`delete`),identityRef:t.identityRef}),register$7(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`move`),identityRef:t.identityRef}),register$9(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`history`)}),register$16(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`checkpoint`),identityRef:t.identityRef}),register$4(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`restore_version`),identityRef:t.identityRef}),register$6(g,{resolveCwd:S(`palette`),config:t.config}),register$15(g,{config:t.config,resolveCwd:S(`config`)}),register$10(g,{config:t.config,resolveCwd:S(`preview_url`)}),register$14(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`conflicts`)}),register$5(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`resolve_conflict`)}),register$2(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`share_link`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,s){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(s))}function createSessionServer(e,t,s){let g=e.config,S=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION},{instructions:buildInstructions(g.content)});installPrettyZodErrors(S);let w=s??randomUUID(),E={current:{connectionId:w,displayName:w,colorSeed:w}};S.server.oninitialized=()=>{let e=S.server.getClientVersion(),t=sanitizeClientName(e?.name,w);E.current={connectionId:w,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let D=e.projectDir??e.contentDir;return registerAllTools(S,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return D;let t=resolveWithinRoot(D,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:g,identityRef:E}),{server:S,transport:t}}function createMcpHttpHandler(e){let t=new Map,s=e.sessionTtlMs??1800*1e3,g=e.maxSessions??100;async function S(s,g){let S=t.get(s);if(!S)return;t.delete(s),S.ttlTimer!==void 0&&clearTimeout(S.ttlTimer);let w=await Promise.allSettled([S.server.close(),S.transport.close()]);for(let t of w)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:s,reason:g},`MCP HTTP session close failed`);e.log?.info?.({sessionId:s,reason:g},`MCP HTTP session closed`)}function w(t,g){g.ttlTimer!==void 0&&clearTimeout(g.ttlTimer),g.ttlTimer=setTimeout(()=>{S(t,`ttl-expired`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},s),g.ttlTimer.unref?.()}return{async handle(s,E){let D=firstHeader(s.headers[`mcp-session-id`]);if(D){let e=t.get(D);if(!e){writePlain(E,404,`MCP session not found`);return}w(D,e),await e.transport.handleRequest(s,E);return}if(s.method!==`POST`){writePlain(E,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=g){e.log?.warn?.({activeSessions:t.size,maxSessions:g},`MCP HTTP session cap reached`),writePlain(E,503,`Too many active MCP sessions`);return}let O=firstHeader(s.headers[MCP_CONNECTION_ID_HEADER]),k=validateAgentId(O)??void 0;O!==void 0&&k===void 0&&e.log?.warn?.({headerLength:O.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let j=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableJsonResponse:!0,onsessioninitialized:async s=>{try{let g=createSessionServer(e,j,k);await g.server.connect(j),t.set(s,g),w(s,g),e.log?.info?.({sessionId:s},`MCP HTTP session initialized`)}catch(g){throw t.delete(s),e.log?.error?.({err:g,sessionId:s},`MCP HTTP session initialization failed`),g}}});j.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},j.onclose=()=>{let t=j.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}S(t,`transport-closed`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await j.handleRequest(s,E)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>S(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:s,mcpHttpHandler:g,log:S,sessionManager:w,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,contentAssetMiddleware:O,reactShellMiddleware:k,ephemeral:j}=e,F=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,L=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});L.on(`error`,e=>{S.error({err:e},`WebSocketServer error`)});let B=new Map,H=new Set,q=!1;return t.on(`request`,(e,t)=>{let w=e.url?.split(`?`)[0];if(g!==void 0&&w===`/mcp`){let s=e.headers.origin,w=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`));for(let[e,s]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,s);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}g.handle(e,t).catch(e=>{S.error({err:e,sessionId:w},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(w?.startsWith(`/api/`)){s.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${w}`})}).catch(e=>{S.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let E=(s,g,w)=>{if(s===void 0){w();return}try{s(e,t,()=>{t.writableEnded||t.headersSent||w()})}catch(e){S.error({err:e},`Unhandled ${g} middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},D=s=>{if(j===!0&&O!==void 0&&(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host))){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`content-asset`});return}E(O,`content-asset`,s)},F=e=>E(k,`react-shell`,e),L=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${w??`/`}`})};if(k!==void 0&&w?.startsWith(`/assets/`)){F(()=>D(L));return}if(O!==void 0||k!==void 0){D(()=>F(L));return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${w??`/`}`})}),t.on(`upgrade`,(e,t,g)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive socket error`)}),L.handleUpgrade(e,t,g,t=>{let s=parseKeepaliveConnectionId(e.url);if(s){let e=B.get(s);e!==void 0&&(clearTimeout(e),B.delete(s),S.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&D){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),g=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);D.setPresence(toBroadcasterKey(s),{displayName:t.displayName,icon:e,color:g,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){S.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let g=setInterval(()=>{try{t.ping()}catch{}},3e4);g.unref?.();let O=s?setInterval(()=>{D?.bumpPresenceTs(toBroadcasterKey(s))},3e3):null;O?.unref?.(),t.on(`close`,()=>{if(clearInterval(g),O!==null&&clearInterval(O),!s)return;let e=setTimeout(()=>{if(B.delete(s),q)return;let e=(async()=>{S.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await w?.closeAllForAgent(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{E?.clearFocus(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{D?.clearPresence(toBroadcasterKey(s))}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}})();H.add(e),e.finally(()=>H.delete(e))},F);e.unref?.(),B.set(s,e),S.info({connectionId:s,graceMs:F},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`Upgrade socket error`)}),L.handleUpgrade(e,t,g,t=>{let g=s.handleConnection(t,e),w=!1;t.on(`message`,e=>{if(w)return;let s=e.byteLength;if(s>MAX_COLLAB_MESSAGE_BYTES){w=!0,incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,bytes:s,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}g.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{g.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||S.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:L,shutdown:async()=>{if(!q){q=!0;for(let e of B.values())clearTimeout(e);B.clear(),H.size>0&&await Promise.allSettled(H)}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),s=sanitizeIdentityField(t.searchParams.get(`displayName`)),g=sanitizeIdentityField(t.searchParams.get(`clientName`)),S=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return s===null||g===null||S===null?null:{displayName:s,clientName:g,colorSeed:S}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`Open Knowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,s){super(MISSING_OK_CONFIG_MESSAGE,s),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-BDjANGpQ.mjs`),S=dirname(e);try{tracedMkdirSync(S,{recursive:!0})}catch(e){e.code!==`EEXIST`&&s.warn({err:e,watchDir:S},`failed to create watch directory; watcher may be inert`)}let w=g(S,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==S&&t!==e});await new Promise(e=>{w.once(`ready`,e)});let E=null;try{E=readFileSync(e,`utf-8`)}catch{}let D=(g,S=!0)=>{if(g!==e)return;let w;try{w=readFileSync(g,`utf-8`)}catch(e){if(e.code===`ENOENT`){S&&s.debug({path:g},`config file disappeared between event and read; dropping`);return}s.warn({err:e,path:g},`config file read failed; dropping event`);return}if(w!==E){E=w;try{t(w)}catch(e){s.warn({err:e,path:g},`config file change handler threw`)}}},O=e=>D(e);w.on(`add`,O),w.on(`change`,O),w.on(`unlink`,t=>{t===e&&s.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),w.on(`error`,t=>{s.warn({err:t,watchDir:S,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let k=0,j=setInterval(()=>{k++,D(e,!1),k>=20&&clearInterval(j)},500);j.unref?.();let F=!1;return async()=>{F||(F=!0,clearInterval(j),await w.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-BDjANGpQ.mjs`),S=new Set(e),w=Array.from(new Set(Array.from(S,e=>dirname(e))));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&s.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let E=g(w,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!S.has(e)&&!w.includes(e)});await new Promise(e=>{E.once(`ready`,e)});let D=new Map;for(let e of S)try{D.set(e,readFileSync(e,`utf-8`))}catch{D.set(e,null)}let O=(e,g=!0)=>{if(!S.has(e))return;let w;try{w=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g&&s.debug({path:e},`config file disappeared between event and read; dropping`);return}s.warn({err:t,path:e},`config file read failed; dropping event`);return}if(w!==D.get(e)){D.set(e,w);try{t(e,w)}catch(t){s.warn({err:t,path:e},`config file change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{S.has(e)&&s.debug({path:e},`config file unlinked; downstream state retained`)}),E.on(`error`,e=>{s.warn({err:e,watchDirs:w,paths:Array.from(S)},`[config-file-watcher] chokidar error in multi-path watcher`)});let j=0,F=setInterval(()=>{j++;for(let e of S)O(e,!1);j>=20&&clearInterval(F)},500);F.unref?.();let L=!1;return async()=>{L||(L=!0,clearInterval(F),await E.close())}}function entryMatchesDocName(e,t,s,g){let S=relative(g,join(s,e.file));return S.startsWith(`..`)?!1:stripDocExtension(S)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:s,contentDir:g}=e;return{async afterLoadDocument({documentName:e,document:S}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let w=t();if(!w)return;let E=w.getConflicts();if(E.length===0||!E.some(t=>entryMatchesDocName(t,e,s,g)))return;let D=S.getMap(`lifecycle`);if(D.get(`status`)===`conflict`)return;D.set(`status`,`conflict`),D.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,`Library`,`Applications`,`.Trash`]),ALWAYS_SKIP_DIRS=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`]);function pathHasAlwaysSkipSegment(e){for(let t of e.split(`/`))if(ALWAYS_SKIP_DIRS.has(t))return!0;return!1}const BUILTIN_SKIP_FILES=new Set([`.DS_Store`,`.localized`]);function isAlwaysSkipFile(e){return BUILTIN_SKIP_FILES.has(e.slice(e.lastIndexOf(`/`)+1))}function isSingleDocAncestorDir(e,t){return t===e||t.startsWith(`${e}/`)}const IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let s=readGitCommonDirSync(e);if(s===null)return[];let g=[];appendExcludeFileIfExists(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=resolveGlobalExcludesfileSync(e);return S&&appendExcludeFileIfExists(S,t,g,`global excludesfile`),g}async function loadGitExcludeSourcesAsync(e,t){let s=await readGitCommonDirAsync(e);if(s===null)return[];let g=[];await appendExcludeFileIfExistsAsync(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=await resolveGlobalExcludesfileAsync(e);return S&&await appendExcludeFileIfExistsAsync(S,t,g,`global excludesfile`),g}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=t.trim();if(s)return s}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,s,g){if(existsSync(e))try{let g=readFileSync(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,s,g){if(existsSync(e))try{let g=await readFile$1(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=relative(t,s),E=w.startsWith(`..`),D,O,k,j=0,F=0,L=0;function B(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],S=0,B=0;for(let s of IGNORE_FILE_NAMES){let w=join(t,s);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);S+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${w}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);S+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,w));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:S};B+=loadNestedIgnoreFiles(s,t,e,H),S=H.value;let q=loadGitExcludeSources(t,H);S=H.value,q.length>0&&(g.push(...q),e.add(q));let ee=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return D=e,O=g,k=ee,j=g.length,F=B,L=S,{patternCount:j,nestedFileCount:F,bytes:L}}B();let H=new Map;function q(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}let ee=()=>{S===void 0&&populateDirCount(s,``,q,H)};ee();function J(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function Y(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:q(e)}return{isExcluded(e,t){if(J(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(Y(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((H.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return J(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:Y(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;H.set(t,(H.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=H.get(t)??0;s<=1?H.delete(t):H.set(t,s-1)},rebuildDirCount(){let e=new Map(H);H.clear();try{ee()}catch(t){for(let[t,s]of e)H.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=k,w=j,E=F,q=L,J=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async Y=>{try{let t=B();H.clear(),ee();let s=Date.now()-J;if(Y.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s}}catch(g){D=t,O=s,k=S,j=w,F=E,L=q,H.clear();try{ee()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let B=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(B)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:B}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
|
|
2816
2815
|
`).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function prefixPattern(e,t){return e.startsWith(`!`)?`!${t}/${e.slice(1)}`:`${t}/${e}`}function loadNestedIgnoreFiles(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){return console.warn(`[content-filter] Failed to read directory ${e}:`,t),0}let w=0;for(let E of S){if(!E.isDirectory()||BUILTIN_SKIP_DIRS.has(E.name))continue;let S=join(e,E.name),D=relative(t,S);if(!D.startsWith(`..`)&&!(s.ignores(D)||s.ignores(`${D}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(S,e);if(existsSync(t))try{let e=readFileSync(t,`utf-8`);g.value+=e.length;let S=parseIgnorePatterns(e).map(e=>prefixPattern(e,D));s.add(S),w++}catch(s){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,s)}}w+=loadNestedIgnoreFiles(S,t,s,g)}}return w}async function initContentDirStateAsync(e,t,s,g,S,w,E){let D;try{D=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let O of D){let D=t?`${t}/${O.name}`:O.name;if(O.isDirectory()){if(BUILTIN_SKIP_DIRS.has(O.name))continue;let t=join(e,O.name);if(!w){let e=relative(s,t);if(e.startsWith(`..`)||g.ignores(e)||g.ignores(`${e}/`))continue;for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.add(t.map(t=>prefixPattern(t,e)))}catch(e){console.warn(`[content-filter] Failed to read nested ${s} at ${S}:`,e)}}}await initContentDirStateAsync(t,D,s,g,S,w,E)}else if(O.isFile()&&isSupportedDocFile(O.name)){if(!w){let e=S?`${S}/${D}`:D;if(g.ignores(e))continue}E.set(t,(E.get(t)??0)+1)}}}async function createContentFilterAsync(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=relative(t,s),E=w.startsWith(`..`),D=(0,import_ignore.default)(),O=[],k=new Map,j=()=>{S===void 0&&populateDirCount(s,``,F,k)};function F(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}function L(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function B(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:F(e)}async function H(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[];for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.push(...t),e.add(t)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${S}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=parseIgnorePatterns(await readFile$1(g,`utf-8`));e.add(t.map(e=>prefixPattern(e,w)))}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let j=await loadGitExcludeSourcesAsync(t,{value:0});j.length>0&&(g.push(...j),e.add(j));let F=new Map;S===void 0&&await initContentDirStateAsync(s,``,t,e,w,E,F),D=e,O=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),k.clear();for(let[e,t]of F)k.set(e,t)}return await H(),{isExcluded(e,t){if(L(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(B(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((k.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return L(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:B(e)},getWatcherIgnoreGlobs(){return O},incrementMdDir(e){let t=e===`.`?``:e;k.set(t,(k.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=k.get(t)??0;s<=1?k.delete(t):k.set(t,s-1)},rebuildDirCount(){let e=new Map(k);k.clear();try{j()}catch(t){for(let[t,s]of e)k.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=new Map(k),w=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async E=>{try{await H();let t=Date.now()-w;if(E.setAttributes({"ok.ignore.pattern_count":O.length,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),e.info({durationMs:t},`content-filter async rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:O.length,nestedFileCount:0,bytes:0,durationMs:t}}catch(g){D=t,O=s,k.clear();for(let[e,t]of S)k.set(e,t);let w=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(w)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:w}}}})}}}function runDocLineageGuard(e,t,s){try{if(typeof t!=`string`||t.length===0||isSystemDoc(e)||isConfigDoc(e))return;let g=s.getLoadedDoc(e);if(g===void 0)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch: claim against unloaded ${e} is stale by construction`);let S=g.getMap(`lifecycle`).get(LINEAGE_EPOCH_KEY);if(typeof S!=`string`||S.length===0||S!==t)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch for ${e}: claimed epoch does not match the live lineage`)}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthDocLineageGuardError(),console.warn(JSON.stringify({event:`doc-lineage-guard-error`,documentName:e,errorName:t instanceof Error?t.name:typeof t,message:t instanceof Error?t.message:String(t)}))}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let s=resolve(e,t.slice(5));try{return readFileSync(s,`utf-8`).trim()}catch{try{let s=readFileSync(resolve(e,`packed-refs`),`utf-8`),g=t.slice(5),S=s.split(`
|
|
2817
|
-
`).find(e=>e.endsWith(` ${g}`));if(S)return S.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}function watchedGitFile(e){let t=e.split(`/`).pop()??``;return WATCHED_FILES.has(t)?t:null}async function tryStartParcelHeadWatcher(e,t){let s;try{s=await import(`@parcel/watcher`)}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher unavailable; falling back to chokidar`),null}try{let g=await s.subscribe(e,(e,s)=>{if(e){getLogger(`head-watcher`).warn({err:e},`[head-watcher] parcel subscription error`);return}for(let e of s)t(e.path)});return()=>g.unsubscribe()}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher subscribe failed; falling back to chokidar`),null}}async function startChokidarHeadWatcher(e,t){let{watch:s}=await import(`./chokidar-BDjANGpQ.mjs`),g=s(e,{ignoreInitial:!0,depth:0,followSymlinks:!1});return g.on(`all`,(e,s)=>t(s)),g.on(`error`,e=>{getLogger(`head-watcher`).warn({err:e},`[head-watcher] chokidar watcher error`)}),()=>g.close()}async function startHeadWatcher(e,t,s,g={}){let S=resolveGitDir(e);if(!S)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let w=S,E=!1,D=null,O=null,k=null,j=null;async function F(e){if(B&&await B,!E)return;D&&=(clearTimeout(D),null),O&&=(clearTimeout(O),null);let t=readHeadSha(w),g=k!==t,S=readBranchFromHead(w),F;F=S?.startsWith(`detached-`)?`detached-head`:j===S?`within-branch`:`cross-branch`;let L=j;try{await s({headMoved:g,oldHead:k,newHead:t,timeout:e,batchKind:F,oldBranch:L,newBranch:S})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{E=!1,k=t,j=S}}function L(){D&&clearTimeout(D),D=setTimeout(()=>{D=null,F(!1)},QUIET_WINDOW_MS)}let B=null;async function H(e){if(!E){E=!0,k=readHeadSha(w);let s=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();B=s,await s,B=null,O=setTimeout(()=>{O=null,F(!0)},BATCH_TIMEOUT_MS)}L()}let q=e=>{let t=watchedGitFile(e);t!==null&&H(t)},ee=null,J=`chokidar`;if(g.forceBackend!==`chokidar`&&(ee=await tryStartParcelHeadWatcher(w,q),ee&&(J=`parcel`)),!ee){if(g.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable for HEAD watching (forced backend)`);ee=await startChokidarHeadWatcher(w,q),J=`chokidar`}let Y=ee;return k=readHeadSha(w),j=readBranchFromHead(w),getLogger(`head-watcher`).info({gitDir:w,backend:J},`watching for HEAD changes`),{unsubscribe:async()=>{E&&await F(!1),D&&clearTimeout(D),O&&clearTimeout(O),await Y()},getLastKnownBranch:()=>j}}const LIVE_DERIVED_INDEX_DEBOUNCE_MS=100;function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){return e.getText(`source`).toString()}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,tagIndex:s,signalChannel:g,debounceMs:S=100}=e,w=new Map;function E(e){let t=w.get(e);t&&(clearTimeout(t),w.delete(e))}function D(e,D){E(e),w.set(e,setTimeout(()=>{w.delete(e);try{let S=serializeLiveDocument(D);t.updateDocumentFromMarkdown(e,S),g?.(`backlinks`),g?.(`graph`),s&&(s.updateDocumentFromMarkdown(e,S),g?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},S))}return{async onChange({documentName:e,document:t,transactionOrigin:s}){isSystemDoc(e)||isConfigDoc(e)||isLocalOriginLike(s)&&s.context?.origin===`file-watcher`||D(e,t)},async beforeUnloadDocument({documentName:e}){E(e)},async onDestroy(){for(let e of w.values())clearTimeout(e);w.clear()}}}const PRINCIPAL_FILE=`principal.json`,GIT_TIMEOUT_MS=3e3;async function readGitConfig(e){try{let t=esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function loadPrincipal(e){let t=getLocalDir(e),s=resolve(t,PRINCIPAL_FILE),{name:g,email:S}=await readGitConfig(e);if(existsSync(s)){let e;try{e=JSON.parse(readFileSync(s,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${randomUUID()}`,w=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),E=t.slice(10,18),D={id:t,display_name:g?sanitizeGitIdentity(g):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:S?sanitizeGitIdentity(S):typeof e.display_email==`string`?e.display_email:`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:w};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}mkdirSync(t,{recursive:!0});let w=`principal-${randomUUID()}`,E=w.slice(10,18),D={id:w,display_name:g?sanitizeGitIdentity(g):`Local User`,display_email:S?sanitizeGitIdentity(S):`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}const DEFAULT_CAPACITY=1e4;var RecentlyRemovedDocs=class{map=new Map;capacity;onEviction;onSizeChange;now;constructor(e=DEFAULT_CAPACITY,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&this.onSizeChange?.(this.map.size)}get size(){return this.map.size}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size)}};function fileExistsForDocName(e,t){let s=e.resolveFilePath(t);return s!==null&&e.fileExists(s)}async function runRemovalRedirectGuard(e,t){try{if(isSystemDoc(e)||isConfigDoc(e))return;let s=t.recentlyRemovedDocs.get(e);if(s===void 0)return;if(s.kind===`deleted`){if(fileExistsForDocName(t,e)){t.recentlyRemovedDocs.delete(e);return}throw incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let g=new Set([e]),S=s.newDocName;for(;;){if(g.has(S)){incrementRemovalRedirectChainCycle(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:S}));return}g.add(S);let s=t.recentlyRemovedDocs.get(S);if(s===void 0)throw incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S);if(s.kind===`deleted`)throw fileExistsForDocName(t,S)?(t.recentlyRemovedDocs.delete(S),incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S)):(incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`));S=s.newDocName}}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthRemovalGuardError(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}function createServerObserverExtension(e){let t=new Map,s=new Map;return{async afterLoadDocument({documentName:g,document:S}){if(isSystemDoc(g)||isConfigDoc(g)||t.has(g))return;let w=S,E=w.getXmlFragment(`default`),D=w.getText(`source`),O=()=>{try{let s=setupServerObservers({doc:w,xmlFragment:E,ytext:D,mdManager:e.mdManager,schema:e.schema,docName:g,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize});return t.set(g,s),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${g}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!O()){let e=setTimeout(()=>{s.delete(g),!t.has(g)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${g}'`),O())},5e3);s.set(g,e)}},async afterUnloadDocument({documentName:e}){let g=s.get(e);g&&(clearTimeout(g),s.delete(e));let S=t.get(e);S&&(S(),t.delete(e))},async onDestroy(){for(let e of s.values())clearTimeout(e);s.clear();for(let[e,s]of t.entries())try{s()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const STATE_MANIFEST_FILENAME=`state.json`;function detectProjectShape(e){return e.lockDir,existsSync(e.shadowRepoDir)?`adopt`:`fresh`}function manifestPath(e){return resolve(e,STATE_MANIFEST_FILENAME)}function isCompatibleSchema(e,t){return e===t||e===0&&t===1}var StateManifestError=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function isStateManifestRecord(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let s=t.createdBy;return!(typeof s.runtimeVersion!=`string`||s.protocolVersion!==void 0&&typeof s.protocolVersion!=`number`)}function readStateManifest(e){let t=manifestPath(e);if(!existsSync(t))return{status:`absent`};let s;try{s=readFileSync(t,`utf-8`)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let g;try{g=JSON.parse(s)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!isStateManifestRecord(g))throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:g}}function writeStateManifest(e,t){let s=manifestPath(e);mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function assertCompatibleStateManifest(e){let t=getLogger(`state-manifest`),s=e.currentStateSchemaVersion??1,g=e.currentRuntimeVersion??RUNTIME_VERSION,S=e.currentProtocolVersion??1,w=(e.now??(()=>new Date))().toISOString(),E=manifestPath(e.lockDir),D=readStateManifest(e.lockDir);if(D.status===`present`){let O=D.manifest;if(!isCompatibleSchema(O.stateSchemaVersion,s))throw new StateManifestError({kind:`incompatible`,path:E,message:`State manifest at ${E} declares stateSchemaVersion=${O.stateSchemaVersion} but this binary supports ${s}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${O.createdBy.runtimeVersion}, protocol ${O.createdBy.protocolVersion}.)`});try{let t={...O,lastWriteBy:{runtimeVersion:g,protocolVersion:S,at:w}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),O}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let D={stateSchemaVersion:s,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S}};return writeStateManifest(e.lockDir,D),t.info({path:E,stateSchemaVersion:s},`[state-manifest] fresh project — wrote manifest`),D}let O={stateSchemaVersion:0,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S,adoptedAt:w}};return writeStateManifest(e.lockDir,O),t.warn({path:E,runtimeVersion:g},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),O}function deriveUserFacingCode(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function extractStderr(e){return e.git?.toString()??e.message??``}function matchesAny(e,t){return t.some(t=>t.test(e))}const AUTH_PATTERNS=[/\b(401|403)\b/,/authentication failed/i,/authorization failed/i,/invalid credentials/i,/credential helper/i,/bad credentials/i,/token.*expired/i,/expired.*token/i,/permission denied.*\(publickey\)/i,/host key verification failed/i,/fatal:.*repository.*not found/i],SCOPE_MISMATCH_PATTERNS=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],NON_FAST_FORWARD_PATTERNS=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],PROTECTED_BRANCH_PATTERNS=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],MERGE_CONFLICT_PATTERNS=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],LFS_PATTERNS=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],LARGE_FILE_PATTERNS=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],PRE_RECEIVE_PATTERNS=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],SECRET_DETECTED_PATTERNS=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],INDEX_LOCK_PATTERNS=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],DIRTY_TREE_PATTERNS=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],DISK_FULL_PATTERNS=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],NETWORK_PATTERNS=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],HTTP_5XX_PATTERNS=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],HTTP_429_PATTERNS=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function classifyGitError(e){let t=classifyGitErrorBase(e);return{...t,userFacingCode:deriveUserFacingCode(t.class,t.subclass)}}function classifyGitErrorBase(e){let t=e instanceof Error?e:Error(String(e)),s=extractStderr(t),g=`${t.message}\n${s}`.toLowerCase();return matchesAny(g,INDEX_LOCK_PATTERNS)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:s}:matchesAny(g,DIRTY_TREE_PATTERNS)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:s}:matchesAny(g,DISK_FULL_PATTERNS)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:s}:matchesAny(g,SCOPE_MISMATCH_PATTERNS)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:s}:matchesAny(g,AUTH_PATTERNS)?/\b401\b/.test(g)||/token.*expired/i.test(g)?{class:`auth`,subclass:`401`,retryable:!1,message:`Authentication failed — token may be expired`,rawStderr:s}:/\b403\b/.test(g)?matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:{class:`auth`,subclass:`403`,retryable:!1,message:`Access denied (403)`,rawStderr:s}:{class:`auth`,subclass:`unknown-auth`,retryable:!1,message:`Authentication failed`,rawStderr:s}:matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:matchesAny(g,NON_FAST_FORWARD_PATTERNS)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:s}:matchesAny(g,MERGE_CONFLICT_PATTERNS)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:s}:matchesAny(g,LFS_PATTERNS)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:s}:matchesAny(g,LARGE_FILE_PATTERNS)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:s}:matchesAny(g,SECRET_DETECTED_PATTERNS)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:s}:matchesAny(g,PRE_RECEIVE_PATTERNS)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:s}:matchesAny(g,HTTP_429_PATTERNS)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:s}:matchesAny(g,HTTP_5XX_PATTERNS)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:s}:matchesAny(g,NETWORK_PATTERNS)?/timed? out/i.test(g)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:s}:/refused/i.test(g)||/econnrefused/i.test(g)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:s}:/resolve.*host/i.test(g)||/enotfound/i.test(g)||/getaddrinfo/i.test(g)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:s}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:s}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:s}}const log$2=getLogger(`github-permissions`),PROBE_TIMEOUT_MS=5e3;function githubApiBase(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function buildHeaders(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function readPushFlag(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let s=t.push;return typeof s==`boolean`?s:null}async function classify(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return log$2.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let s=readPushFlag(t);return s===null?(log$2.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):s?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return log$2.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function resolveProbeTokenWithSource(e,t,s){let g=t(e);if(g.available&&g.token)return{token:g.token,source:`gh`};if(s)try{let t=await s.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){log$2.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function runProbe(e){let{owner:t,repo:s,host:g=`github.com`,detectGh:S=()=>({available:!1}),tokenStore:w,_fetchFn:E=fetch,_timeoutMs:D=PROBE_TIMEOUT_MS}=e,{token:O,source:k}=await resolveProbeTokenWithSource(g,S,w),j=`${githubApiBase(g)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(s)}`;log$2.info({host:g,tokenSource:k,tokenLen:O===void 0?0:O.length},`[permissions] probe starting`);let F=new AbortController,L=setTimeout(()=>F.abort(),D);try{let e=await E(j,{signal:F.signal,headers:buildHeaders(O)}),t=await classify(e,O!==void 0);return log$2.info({host:g,tokenSource:k,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return F.signal.aborted?(log$2.warn({host:g,timeoutMs:D},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(log$2.warn({err:e,host:g},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(L)}}async function checkPushPermission(e){let t=performance.now(),s=await runProbe(e);return recordProbeTelemetry(s,performance.now()-t),s}function outcomeAttributes(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let _outcomeCounter=null;function outcomeCounter(){return _outcomeCounter||=getMeter().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,none}.`}),_outcomeCounter}let _durationHist=null;function durationHist(){return _durationHist||=getMeter().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),_durationHist}function recordProbeTelemetry(e,t){let s=outcomeAttributes(e);outcomeCounter().add(1,s),durationHist().record(t,{outcome:s.outcome})}function computeRemainingMs(e,t,s=Date.now()){if(!e)return 0;let g=new Date(e).getTime();if(Number.isNaN(g))return 0;let S=g+t*1e3;return Math.max(0,S-s)}const log$1=getLogger(`sync-engine`),SHA_HEX_40=/^[0-9a-f]{40}$/i;function pushPermissionStatusFrom(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function pushPermissionStatusEqual(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function jitteredMs(e){let t=e*1e3,s=t*.15*(2*Math.random()-1);return Math.round(t+s)}function isUnbornHead(e){try{let t=join(e,`.git`,`HEAD`);if(!existsSync(t))return!1;let s=readFileSync(t,`utf-8`).trim(),g=/^ref:\s+(refs\/.+)$/.exec(s);if(!g)return!1;let S=g[1];if(existsSync(join(e,`.git`,S)))return!1;let w=join(e,`.git`,`packed-refs`);if(existsSync(w)){let e=readFileSync(w,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${S}$`,`m`).test(e))return!1}return!0}catch{return!1}}function backoffMs(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var SyncEngine=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;setBatchInProgress;onAutoDisable;detectGh;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.detectGh=e.detectGh,this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??checkPushPermission,this.statePath=resolve(getLocalDir(this.projectDir),`sync-state.json`),this.conflictStore=new ConflictStore(this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){log$1.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),log$1.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){log$1.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null,g=s!==null&&existsSync(s);if(this.conflictCount>0&&!g)log$1.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&g)try{let e=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
|
|
2818
|
-
`).map(e=>e.trim()).filter(Boolean):[]),s=this.conflictCount;for(let e of this.conflictStore.list())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<s&&log$1.info({cleared:s-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){log$1.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(g&&this.conflictCount===0){log$1.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),log$1.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let S=computeRemainingMs(this.lastFetchUtc,this.pullIntervalSeconds),w=computeRemainingMs(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(S>0?S:void 0),this.schedulePush(w>0?w:void 0),log$1.info({branch:this.currentBranch,pullDelayMs:S,pushDelayMs:w},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setEnabled(e){if(this.syncEnabled!==e){if(this.syncEnabled=e,!e){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null);let e=3e4,t=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-t>3e4){log$1.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await setTimeout$1(50)}this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?log$1.warn({op:e,state:this.state,syncEnabled:this.syncEnabled,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):log$1.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(e===`pull`||await this.runPushCycle(),await this.runPullCycle())}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.syncEnabled===!0,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?readSyncRemoteInfo(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await resolveGitIdentity(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=readOriginGitHubRepo(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,pushPermissionStatusEqual(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,log$1.info({caller:e,host:`github.com`,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let s;try{s=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:`github.com`,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){log$1.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),s={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let g=pushPermissionStatusFrom(s),S=this.pushPermission;this.pushPermission=g;let w=!1;return g.checkStatus===`denied`&&this.syncEnabled===!0?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),w=!0,log$1.info({reason:g.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):g.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.syncEnabled===!0&&this.transitionTo(`idle`),w=!0,log$1.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!w&&!pushPermissionStatusEqual(S,g)&&this.cc1Broadcaster?.signal(`sync-status`),g}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,log$1.info({syncEnabled:this.syncEnabled},`[sync] remote detected post-boot — re-evaluating state`),this.syncEnabled===!0?(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()):this.transitionTo(`disabled`))}async probeRemote(){if(!existsSync(join(this.projectDir,`.git`)))return!1;try{return(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw(`remote`,`-v`)).trim().length>0}catch(e){return log$1.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){if(this.conflictCount===0)return;let e=this.conflictCount,t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null;if(!(s!==null&&existsSync(s)))log$1.info({cleared:e},`[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts`),this.conflictStore.clear(),this.conflictCount=0;else try{let t=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),s=new Set(t?t.split(`
|
|
2819
|
-
`).map(e=>e.trim()).filter(Boolean):[]);for(let e of this.conflictStore.list())s.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<e&&log$1.info({cleared:e-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){log$1.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}this.conflictCount!==e&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,s){this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,s)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{log$1.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??jitteredMs(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{log$1.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=this.consecutiveFailures,t=backoffMs(e);return t>0?t:jitteredMs(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`)){if(this.state===`conflict`){this.schedulePull();return}if(isUnbornHead(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),t;try{let s=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!s||s===`HEAD`){this.transitionTo(`disabled`),this.pausedReason=`detached-head`,log$1.warn({},`[sync] detached HEAD — pausing sync`);return}t=s,this.currentBranch=t}catch(e){this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))),`pull`);return}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));this.handleError(t,`pull`);return}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let s=await this.prepareForMerge(e,t);if(!s.proceed)return;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{s.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`);return}finally{this.setBatchInProgress?.(!1)}}else this.transitionTo(`idle`);this.scheduleSaveState()}async runPushCycle(){if(!this.pushInFlight&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(isUnbornHead(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),s=join(tmpdir(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),g=null;this.transitionTo(`pushing`);try{await withParentLock(async()=>{let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:s});if(isUnbornHead(this.projectDir)){log$1.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let S;try{S=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),s=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(s)||/ambiguous argument 'HEAD'/i.test(s)||/does not have any commits yet/i.test(s)){log$1.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,S]);let w=await this.listHeadContentPaths(e,S);if(t.length>0){let s=100;for(let s=0;s<t.length;s+=100){let g=t.slice(s,s+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...g])}}let E=new Set(t.map(e=>e.projectRelPath)),D=[...w].filter(e=>!E.has(e));await this.removePathsFromIndex(e,D);let O=(await e.git.raw([`write-tree`])).trim(),k=``;try{k=(await e.git.raw([`rev-parse`,`${S}^{tree}`])).trim()}catch{}if(k&&k===O){let s=null;try{s=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(s===S){log$1.info({contentFileCount:t.length,headSha:S},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=S,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}log$1.info({headSha:S,upstreamSha:s},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let w=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),w=!0}catch{}w?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),g=S;return}let j=[],F=[];try{let s=(await e.git.raw([`diff-tree`,`--name-only`,`-r`,S,O])).trim();if(s){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of s.split(`
|
|
2816
|
+
`).find(e=>e.endsWith(` ${g}`));if(S)return S.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}function watchedGitFile(e){let t=e.split(`/`).pop()??``;return WATCHED_FILES.has(t)?t:null}async function tryStartParcelHeadWatcher(e,t){let s;try{s=await import(`@parcel/watcher`)}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher unavailable; falling back to chokidar`),null}try{let g=await s.subscribe(e,(e,s)=>{if(e){getLogger(`head-watcher`).warn({err:e},`[head-watcher] parcel subscription error`);return}for(let e of s)t(e.path)});return()=>g.unsubscribe()}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher subscribe failed; falling back to chokidar`),null}}async function startChokidarHeadWatcher(e,t){let{watch:s}=await import(`./chokidar-BDjANGpQ.mjs`),g=s(e,{ignoreInitial:!0,depth:0,followSymlinks:!1});return g.on(`all`,(e,s)=>t(s)),g.on(`error`,e=>{getLogger(`head-watcher`).warn({err:e},`[head-watcher] chokidar watcher error`)}),()=>g.close()}async function startHeadWatcher(e,t,s,g={}){let S=resolveGitDir(e);if(!S)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let w=S,E=!1,D=null,O=null,k=null,j=null;async function F(e){if(B&&await B,!E)return;D&&=(clearTimeout(D),null),O&&=(clearTimeout(O),null);let t=readHeadSha(w),g=k!==t,S=readBranchFromHead(w),F;F=S?.startsWith(`detached-`)?`detached-head`:j===S?`within-branch`:`cross-branch`;let L=j;try{await s({headMoved:g,oldHead:k,newHead:t,timeout:e,batchKind:F,oldBranch:L,newBranch:S})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{E=!1,k=t,j=S}}function L(){D&&clearTimeout(D),D=setTimeout(()=>{D=null,F(!1)},QUIET_WINDOW_MS)}let B=null;async function H(e){if(!E){E=!0,k=readHeadSha(w);let s=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();B=s,await s,B=null,O=setTimeout(()=>{O=null,F(!0)},BATCH_TIMEOUT_MS)}L()}let q=e=>{let t=watchedGitFile(e);t!==null&&H(t)},ee=null,J=`chokidar`;if(g.forceBackend!==`chokidar`&&(ee=await tryStartParcelHeadWatcher(w,q),ee&&(J=`parcel`)),!ee){if(g.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable for HEAD watching (forced backend)`);ee=await startChokidarHeadWatcher(w,q),J=`chokidar`}let Y=ee;return k=readHeadSha(w),j=readBranchFromHead(w),getLogger(`head-watcher`).info({gitDir:w,backend:J},`watching for HEAD changes`),{unsubscribe:async()=>{E&&await F(!1),D&&clearTimeout(D),O&&clearTimeout(O),await Y()},getLastKnownBranch:()=>j}}const LIVE_DERIVED_INDEX_DEBOUNCE_MS=100;function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){return e.getText(`source`).toString()}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,tagIndex:s,signalChannel:g,debounceMs:S=100}=e,w=new Map;function E(e){let t=w.get(e);t&&(clearTimeout(t),w.delete(e))}function D(e,D){E(e),w.set(e,setTimeout(()=>{w.delete(e);try{let S=serializeLiveDocument(D);t.updateDocumentFromMarkdown(e,S),g?.(`backlinks`),g?.(`graph`),s&&(s.updateDocumentFromMarkdown(e,S),g?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},S))}return{async onChange({documentName:e,document:t,transactionOrigin:s}){isSystemDoc(e)||isConfigDoc(e)||isLocalOriginLike(s)&&s.context?.origin===`file-watcher`||D(e,t)},async beforeUnloadDocument({documentName:e}){E(e)},async onDestroy(){for(let e of w.values())clearTimeout(e);w.clear()}}}const PRINCIPAL_FILE=`principal.json`,GIT_TIMEOUT_MS=3e3;async function readGitConfig(e){try{let t=esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function loadPrincipal(e){let t=getLocalDir(e),s=resolve(t,PRINCIPAL_FILE),{name:g,email:S}=await readGitConfig(e);if(existsSync(s)){let e;try{e=JSON.parse(readFileSync(s,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${randomUUID()}`,w=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),E=t.slice(10,18),D={id:t,display_name:g?sanitizeGitIdentity(g):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:S?sanitizeGitIdentity(S):typeof e.display_email==`string`?e.display_email:`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:w};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}mkdirSync(t,{recursive:!0});let w=`principal-${randomUUID()}`,E=w.slice(10,18),D={id:w,display_name:g?sanitizeGitIdentity(g):`Local User`,display_email:S?sanitizeGitIdentity(S):`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}const DEFAULT_CAPACITY=1e4;var RecentlyRemovedDocs=class{map=new Map;capacity;onEviction;onSizeChange;now;constructor(e=DEFAULT_CAPACITY,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&this.onSizeChange?.(this.map.size)}get size(){return this.map.size}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size)}};function fileExistsForDocName(e,t){let s=e.resolveFilePath(t);return s!==null&&e.fileExists(s)}async function runRemovalRedirectGuard(e,t){try{if(isSystemDoc(e)||isConfigDoc(e))return;let s=t.recentlyRemovedDocs.get(e);if(s===void 0)return;if(s.kind===`deleted`){if(fileExistsForDocName(t,e)){t.recentlyRemovedDocs.delete(e);return}throw incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let g=new Set([e]),S=s.newDocName;for(;;){if(g.has(S)){incrementRemovalRedirectChainCycle(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:S}));return}g.add(S);let s=t.recentlyRemovedDocs.get(S);if(s===void 0)throw incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S);if(s.kind===`deleted`)throw fileExistsForDocName(t,S)?(t.recentlyRemovedDocs.delete(S),incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S)):(incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`));S=s.newDocName}}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthRemovalGuardError(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}function createServerObserverExtension(e){let t=new Map,s=new Map;return{async afterLoadDocument({documentName:g,document:S}){if(isSystemDoc(g)||isConfigDoc(g)||t.has(g))return;let w=S,E=w.getXmlFragment(`default`),D=w.getText(`source`),O=()=>{try{let s=setupServerObservers({doc:w,xmlFragment:E,ytext:D,mdManager:e.mdManager,schema:e.schema,docName:g,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize});return t.set(g,s),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${g}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!O()){let e=setTimeout(()=>{s.delete(g),!t.has(g)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${g}'`),O())},5e3);s.set(g,e)}},async afterUnloadDocument({documentName:e}){let g=s.get(e);g&&(clearTimeout(g),s.delete(e));let S=t.get(e);S&&(S(),t.delete(e))},async onDestroy(){for(let e of s.values())clearTimeout(e);s.clear();for(let[e,s]of t.entries())try{s()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const STATE_MANIFEST_FILENAME=`state.json`;function detectProjectShape(e){return e.lockDir,existsSync(e.shadowRepoDir)?`adopt`:`fresh`}function manifestPath(e){return resolve(e,STATE_MANIFEST_FILENAME)}function isCompatibleSchema(e,t){return e===t||e===0&&t===1}var StateManifestError=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function isStateManifestRecord(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let s=t.createdBy;return!(typeof s.runtimeVersion!=`string`||s.protocolVersion!==void 0&&typeof s.protocolVersion!=`number`)}function readStateManifest(e){let t=manifestPath(e);if(!existsSync(t))return{status:`absent`};let s;try{s=readFileSync(t,`utf-8`)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let g;try{g=JSON.parse(s)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!isStateManifestRecord(g))throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:g}}function writeStateManifest(e,t){let s=manifestPath(e);mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function assertCompatibleStateManifest(e){let t=getLogger(`state-manifest`),s=e.currentStateSchemaVersion??1,g=e.currentRuntimeVersion??RUNTIME_VERSION,S=e.currentProtocolVersion??1,w=(e.now??(()=>new Date))().toISOString(),E=manifestPath(e.lockDir),D=readStateManifest(e.lockDir);if(D.status===`present`){let O=D.manifest;if(!isCompatibleSchema(O.stateSchemaVersion,s))throw new StateManifestError({kind:`incompatible`,path:E,message:`State manifest at ${E} declares stateSchemaVersion=${O.stateSchemaVersion} but this binary supports ${s}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${O.createdBy.runtimeVersion}, protocol ${O.createdBy.protocolVersion}.)`});try{let t={...O,lastWriteBy:{runtimeVersion:g,protocolVersion:S,at:w}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),O}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let D={stateSchemaVersion:s,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S}};return writeStateManifest(e.lockDir,D),t.info({path:E,stateSchemaVersion:s},`[state-manifest] fresh project — wrote manifest`),D}let O={stateSchemaVersion:0,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S,adoptedAt:w}};return writeStateManifest(e.lockDir,O),t.warn({path:E,runtimeVersion:g},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),O}function deriveUserFacingCode(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`auth`&&t===`no-credential`?`auth-no-credential`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function extractStderr(e){return e.git?.toString()??e.message??``}function matchesAny(e,t){return t.some(t=>t.test(e))}const AUTH_PATTERNS=[/\b(401|403)\b/,/authentication failed/i,/authorization failed/i,/invalid credentials/i,/credential helper/i,/bad credentials/i,/token.*expired/i,/expired.*token/i,/permission denied.*\(publickey\)/i,/host key verification failed/i,/fatal:.*repository.*not found/i],NO_CREDENTIAL_PATTERNS=[/could not read (username|password)/i,/terminal prompts disabled/i],SCOPE_MISMATCH_PATTERNS=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],NON_FAST_FORWARD_PATTERNS=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],PROTECTED_BRANCH_PATTERNS=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],MERGE_CONFLICT_PATTERNS=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],LFS_PATTERNS=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],LARGE_FILE_PATTERNS=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],PRE_RECEIVE_PATTERNS=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],SECRET_DETECTED_PATTERNS=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],INDEX_LOCK_PATTERNS=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],DIRTY_TREE_PATTERNS=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],DISK_FULL_PATTERNS=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],NETWORK_PATTERNS=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],HTTP_5XX_PATTERNS=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],HTTP_429_PATTERNS=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function classifyGitError(e){let t=classifyGitErrorBase(e);return{...t,userFacingCode:deriveUserFacingCode(t.class,t.subclass)}}function classifyGitErrorBase(e){let t=e instanceof Error?e:Error(String(e)),s=extractStderr(t),g=`${t.message}\n${s}`.toLowerCase();return matchesAny(g,INDEX_LOCK_PATTERNS)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:s}:matchesAny(g,DIRTY_TREE_PATTERNS)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:s}:matchesAny(g,DISK_FULL_PATTERNS)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:s}:matchesAny(g,NO_CREDENTIAL_PATTERNS)?{class:`auth`,subclass:`no-credential`,retryable:!1,message:`No GitHub credential available — reconnect to resume syncing`,rawStderr:s}:matchesAny(g,SCOPE_MISMATCH_PATTERNS)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:s}:matchesAny(g,AUTH_PATTERNS)?/\b401\b/.test(g)||/token.*expired/i.test(g)?{class:`auth`,subclass:`401`,retryable:!1,message:`Authentication failed — token may be expired`,rawStderr:s}:/\b403\b/.test(g)?matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:{class:`auth`,subclass:`403`,retryable:!1,message:`Access denied (403)`,rawStderr:s}:{class:`auth`,subclass:`unknown-auth`,retryable:!1,message:`Authentication failed`,rawStderr:s}:matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:matchesAny(g,NON_FAST_FORWARD_PATTERNS)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:s}:matchesAny(g,MERGE_CONFLICT_PATTERNS)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:s}:matchesAny(g,LFS_PATTERNS)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:s}:matchesAny(g,LARGE_FILE_PATTERNS)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:s}:matchesAny(g,SECRET_DETECTED_PATTERNS)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:s}:matchesAny(g,PRE_RECEIVE_PATTERNS)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:s}:matchesAny(g,HTTP_429_PATTERNS)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:s}:matchesAny(g,HTTP_5XX_PATTERNS)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:s}:matchesAny(g,NETWORK_PATTERNS)?/timed? out/i.test(g)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:s}:/refused/i.test(g)||/econnrefused/i.test(g)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:s}:/resolve.*host/i.test(g)||/enotfound/i.test(g)||/getaddrinfo/i.test(g)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:s}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:s}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:s}}const log$2=getLogger(`github-permissions`),PROBE_TIMEOUT_MS=5e3;function githubApiBase(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function buildHeaders(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function readPushFlag(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let s=t.push;return typeof s==`boolean`?s:null}async function classify(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return log$2.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let s=readPushFlag(t);return s===null?(log$2.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):s?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return log$2.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function resolveProbeTokenWithSource(e,t,s){let g=t(e);if(g.available&&g.token)return{token:g.token,source:`gh`};if(s)try{let t=await s.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){log$2.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function runProbe(e){let{owner:t,repo:s,host:g=`github.com`,detectGh:S=()=>({available:!1}),tokenStore:w,_fetchFn:E=fetch,_timeoutMs:D=PROBE_TIMEOUT_MS}=e,{token:O,source:k}=await resolveProbeTokenWithSource(g,S,w),j=`${githubApiBase(g)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(s)}`;log$2.info({host:g,tokenSource:k,tokenLen:O===void 0?0:O.length},`[permissions] probe starting`);let F=new AbortController,L=setTimeout(()=>F.abort(),D);try{let e=await E(j,{signal:F.signal,headers:buildHeaders(O)}),t=await classify(e,O!==void 0);return log$2.info({host:g,tokenSource:k,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return F.signal.aborted?(log$2.warn({host:g,timeoutMs:D},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(log$2.warn({err:e,host:g},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(L)}}async function checkPushPermission(e){let t=performance.now(),s=await runProbe(e);return recordProbeTelemetry(s,performance.now()-t),s}function outcomeAttributes(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let _outcomeCounter=null;function outcomeCounter(){return _outcomeCounter||=getMeter().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,none}.`}),_outcomeCounter}let _durationHist=null;function durationHist(){return _durationHist||=getMeter().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),_durationHist}function recordProbeTelemetry(e,t){let s=outcomeAttributes(e);outcomeCounter().add(1,s),durationHist().record(t,{outcome:s.outcome})}function computeRemainingMs(e,t,s=Date.now()){if(!e)return 0;let g=new Date(e).getTime();if(Number.isNaN(g))return 0;let S=g+t*1e3;return Math.max(0,S-s)}const log$1=getLogger(`sync-engine`),SHA_HEX_40=/^[0-9a-f]{40}$/i;function pushPermissionStatusFrom(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function pushPermissionStatusEqual(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function jitteredMs(e){let t=e*1e3,s=t*.15*(2*Math.random()-1);return Math.round(t+s)}function isUnbornHead(e){try{let t=join(e,`.git`,`HEAD`);if(!existsSync(t))return!1;let s=readFileSync(t,`utf-8`).trim(),g=/^ref:\s+(refs\/.+)$/.exec(s);if(!g)return!1;let S=g[1];if(existsSync(join(e,`.git`,S)))return!1;let w=join(e,`.git`,`packed-refs`);if(existsSync(w)){let e=readFileSync(w,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${S}$`,`m`).test(e))return!1}return!0}catch{return!1}}function backoffMs(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var SyncEngine=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;setBatchInProgress;onAutoDisable;detectGh;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.detectGh=e.detectGh,this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??checkPushPermission,this.statePath=resolve(getLocalDir(this.projectDir),`sync-state.json`),this.conflictStore=new ConflictStore(this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){log$1.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),log$1.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){log$1.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null,g=s!==null&&existsSync(s);if(this.conflictCount>0&&!g)log$1.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&g)try{let e=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
|
|
2817
|
+
`).map(e=>e.trim()).filter(Boolean):[]),s=this.conflictCount;for(let e of this.conflictStore.list())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<s&&log$1.info({cleared:s-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){log$1.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(g&&this.conflictCount===0){log$1.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),log$1.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let S=computeRemainingMs(this.lastFetchUtc,this.pullIntervalSeconds),w=computeRemainingMs(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(S>0?S:void 0),this.schedulePush(w>0?w:void 0),log$1.info({branch:this.currentBranch,pullDelayMs:S,pushDelayMs:w},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setEnabled(e){if(this.syncEnabled!==e){if(this.syncEnabled=e,!e){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null);let e=3e4,t=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-t>3e4){log$1.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await setTimeout$1(50)}this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async notifyCredentialsChanged(){if(this.syncEnabled&&!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`)){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?log$1.warn({op:e,state:this.state,syncEnabled:this.syncEnabled,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):log$1.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(e===`pull`||await this.runPushCycle(),await this.runPullCycle())}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.syncEnabled===!0,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?readSyncRemoteInfo(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await resolveGitIdentity(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=readOriginGitHubRepo(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,pushPermissionStatusEqual(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,log$1.info({caller:e,host:`github.com`,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let s;try{s=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:`github.com`,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){log$1.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),s={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let g=pushPermissionStatusFrom(s),S=this.pushPermission;this.pushPermission=g;let w=!1;return g.checkStatus===`denied`&&this.syncEnabled===!0?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),w=!0,log$1.info({reason:g.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):g.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.syncEnabled===!0&&this.transitionTo(`idle`),w=!0,log$1.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!w&&!pushPermissionStatusEqual(S,g)&&this.cc1Broadcaster?.signal(`sync-status`),g}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,log$1.info({syncEnabled:this.syncEnabled},`[sync] remote detected post-boot — re-evaluating state`),this.syncEnabled===!0?(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()):this.transitionTo(`disabled`))}async probeRemote(){if(!existsSync(join(this.projectDir,`.git`)))return!1;try{return(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw(`remote`,`-v`)).trim().length>0}catch(e){return log$1.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){if(this.conflictCount===0)return;let e=this.conflictCount,t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null;if(!(s!==null&&existsSync(s)))log$1.info({cleared:e},`[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts`),this.conflictStore.clear(),this.conflictCount=0;else try{let t=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),s=new Set(t?t.split(`
|
|
2818
|
+
`).map(e=>e.trim()).filter(Boolean):[]);for(let e of this.conflictStore.list())s.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<e&&log$1.info({cleared:e-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){log$1.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}this.conflictCount!==e&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,s){this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,s)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{log$1.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??jitteredMs(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{log$1.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=this.consecutiveFailures,t=backoffMs(e);return t>0?t:jitteredMs(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`||this.state===`auth-error`)){if(this.state===`conflict`){this.schedulePull();return}if(isUnbornHead(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),t;try{let s=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!s||s===`HEAD`){this.transitionTo(`disabled`),this.pausedReason=`detached-head`,log$1.warn({},`[sync] detached HEAD — pausing sync`);return}t=s,this.currentBranch=t}catch(e){this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))),`pull`);return}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));this.handleError(t,`pull`);return}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let s=await this.prepareForMerge(e,t);if(!s.proceed)return;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{s.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`);return}finally{this.setBatchInProgress?.(!1)}}else this.transitionTo(`idle`);this.scheduleSaveState()}async runPushCycle(){if(!this.pushInFlight&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(isUnbornHead(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),s=join(tmpdir(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),g=null;this.transitionTo(`pushing`);try{await withParentLock(async()=>{let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:s});if(isUnbornHead(this.projectDir)){log$1.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let S;try{S=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),s=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(s)||/ambiguous argument 'HEAD'/i.test(s)||/does not have any commits yet/i.test(s)){log$1.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,S]);let w=await this.listHeadContentPaths(e,S);if(t.length>0){let s=100;for(let s=0;s<t.length;s+=100){let g=t.slice(s,s+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...g])}}let E=new Set(t.map(e=>e.projectRelPath)),D=[...w].filter(e=>!E.has(e));await this.removePathsFromIndex(e,D);let O=(await e.git.raw([`write-tree`])).trim(),k=``;try{k=(await e.git.raw([`rev-parse`,`${S}^{tree}`])).trim()}catch{}if(k&&k===O){let s=null;try{s=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(s===S){log$1.info({contentFileCount:t.length,headSha:S},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=S,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}log$1.info({headSha:S,upstreamSha:s},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let w=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),w=!0}catch{}w?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),g=S;return}let j=[],F=[];try{let s=(await e.git.raw([`diff-tree`,`--name-only`,`-r`,S,O])).trim();if(s){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of s.split(`
|
|
2820
2819
|
`)){let s=t.trim();if(!s)continue;j.push(s);let g=e.get(s)??relative(this.contentDir,join(this.projectDir,s));g&&!g.startsWith(`..`)&&F.push(g)}}}catch{j=t.map(e=>e.projectRelPath).concat(D),F=t.map(e=>e.contentRelPath)}let L=this.buildCommitMessage(F),B=await resolveGitIdentity(this.projectDir),H=B===null;this.identityUnresolved!==H&&(this.identityUnresolved=H,this.cc1Broadcaster?.signal(`sync-status`));let q=B?.name??`Open Knowledge`,ee=B?.email??`sync@open-knowledge.local`;e.git.env({GIT_AUTHOR_NAME:q,GIT_AUTHOR_EMAIL:ee,GIT_COMMITTER_NAME:q,GIT_COMMITTER_EMAIL:ee});let J=(await e.git.raw([`commit-tree`,O,`-p`,S,`-m`,L])).trim();if(!J||!SHA_HEX_40.test(J)){log$1.warn({raw:J},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,J,S]),await this.resetRealIndexForPaths(j);let Y=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),Y=!0}catch{}Y?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),g=J}),g&&(this.lastPushedSha=g,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let s=classifyGitError(t instanceof Error?t:Error(String(t)));if(s.class===`semantic`&&s.subclass===`non-fast-forward`){if(e>0){log$1.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}log$1.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(s,`push`)}finally{try{unlinkSync(s)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),s=this.gatherContentFilesSync(),g=await this.listHeadContentPaths(e,t);if(s.length===0&&g.size===0)return null;let S=join(tmpdir(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),w=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:S});try{await w.git.raw([`read-tree`,t]);let S=100;for(let e=0;e<s.length;e+=100){let t=s.slice(e,e+100).map(e=>e.projectRelPath);await w.git.raw([`add`,`--`,...t])}let E=new Set(s.map(e=>e.projectRelPath)),D=[...g].filter(e=>!E.has(e));await this.removePathsFromIndex(w,D);let O=(await w.git.raw([`write-tree`])).trim();if(O===(await w.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let k=[];try{let e=(await w.git.raw([`diff-tree`,`--name-only`,`-r`,t,O])).trim();k=e?e.split(`
|
|
2821
2820
|
`).map(e=>e.trim()).filter(Boolean):[]}catch{k=s.map(e=>e.projectRelPath).concat(D)}let j=await resolveGitIdentity(this.projectDir),F=j?.name??`Open Knowledge`,L=j?.email??`sync@open-knowledge.local`;w.git.env({GIT_AUTHOR_NAME:F,GIT_AUTHOR_EMAIL:L,GIT_COMMITTER_NAME:F,GIT_COMMITTER_EMAIL:L});let B=(await w.git.raw([`commit-tree`,O,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!B||!SHA_HEX_40.test(B)?(log$1.warn({raw:B},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,B,t]),await this.resetRealIndexForPaths(k,e),B)}finally{try{unlinkSync(S)}catch{}}}async prepareForMerge(e,t){let s=``;try{s=(await e.git.raw([`diff-index`,`--name-only`,`HEAD`])).trim()}catch(e){return log$1.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}if(!s)return{proceed:!0,needsStashPop:!1};let g=s.split(`
|
|
2822
2821
|
`).map(e=>e.trim()).filter(Boolean);if(g.length===0)return{proceed:!0,needsStashPop:!1};let S=``;try{S=(await e.git.raw([`diff`,`--name-only`,`HEAD..origin/${t}`])).trim()}catch(e){return log$1.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let w=new Set(S.split(`
|
|
2823
2822
|
`).map(e=>e.trim()).filter(Boolean)),E=g.filter(e=>w.has(e));if(E.length>0){let e=E.slice(0,3).join(`, `),t=E.length>3?`, +${E.length-3} more`:``;return this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log$1.warn({files:E},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1}}let D=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,D])}catch(e){return log$1.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){log$1.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}gatherContentFilesSync(){let e=[],t=s=>{let g;try{g=readdirSync(s,{withFileTypes:!0})}catch{return}for(let S of g){let g=join(s,S.name);if(S.isDirectory()){let e=relative(this.contentDir,g);if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(g)}else if(S.isFile()){let t=relative(this.contentDir,g);if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let s=relative(this.projectDir,g);e.push({contentRelPath:t,projectRelPath:s})}}}};return existsSync(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let s=new Set;try{let g=(await e.git.raw([`ls-tree`,`-r`,`--name-only`,t])).trim();for(let e of g?g.split(`
|
|
2824
2823
|
`):[]){let t=e.trim();if(!t)continue;let g=join(this.projectDir,t),S=relative(this.contentDir,g);!S.startsWith(`..`)&&!this.contentFilter.isExcluded(S)&&s.add(t)}}catch{}return s}async removePathsFromIndex(e,t){if(t.length===0)return;let s=[...new Set(t)],g=100;for(let t=0;t<s.length;t+=100){let g=s.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...g])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let s=t??createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),g=[...new Set(e)],S=100;for(let e=0;e<g.length;e+=100){let t=g.slice(e,e+100);try{await s.git.raw([`reset`,`HEAD`,`--`,...t])}catch{}}}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),t=[];try{let s=(await e.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();t=s?s.split(`
|
|
2825
|
-
`).map(e=>e.trim()).filter(Boolean):[]}catch(t){log$1.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let s=[],g=[];for(let e of t){let t=join(this.projectDir,e),S=relative(this.contentDir,t);!S.startsWith(`..`)&&isSupportedDocFile(S)&&!this.contentFilter.isExcluded(S)?s.push(e):g.push(e)}let S=[];for(let t of g)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log$1.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log$1.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),S.push({file:t,err:e})}if(S.length>0){let t=S.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let s=t.slice(0,3).join(`, `),g=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${s}${g}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log$1.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(s.length>0){for(let e of s)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(s),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log$1.warn({files:s},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log$1.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log$1.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){log$1.warn({err:t,files:e},`[sync] content conflict callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),log$1.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log$1.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};writeFileSync(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$1.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`?void 0:t.pausedReason;let s=t.inflightConflicts??[];if(s.length>0){for(let e of s)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log$1.warn({err:e},`[sync] failed to load sync state`)}}};const MOUNT_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function createSyncHandshakeSpanExtension(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(isSystemDoc(e)||isConfigDoc(e))return;let s=t?.get(`mountId`)??void 0,g={"doc.name":e};s!==void 0&&MOUNT_ID_PATTERN.test(s)&&(g[`mount.id`]=s);try{withSpanSync(`sync.handshake`,{attributes:g},()=>{})}catch(e){console.warn(`[sync-handshake-span] emission failed:`,e instanceof Error?e:String(e))}}}}const TAG_VALUE_RE=createTagInTextRegex();function createEmptyState(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function stripInlineCodeSpans(e){return e.replace(/`[^`]*`/g,``)}function extractInlineTagsFromBody(e){let t=e.replaceAll(`\r
|
|
2824
|
+
`).map(e=>e.trim()).filter(Boolean):[]}catch(t){log$1.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let s=[],g=[];for(let e of t){let t=join(this.projectDir,e),S=relative(this.contentDir,t);!S.startsWith(`..`)&&isSupportedDocFile(S)&&!this.contentFilter.isExcluded(S)?s.push(e):g.push(e)}let S=[];for(let t of g)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log$1.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log$1.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),S.push({file:t,err:e})}if(S.length>0){let t=S.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let s=t.slice(0,3).join(`, `),g=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${s}${g}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log$1.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(s.length>0){for(let e of s)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(s),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log$1.warn({files:s},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log$1.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log$1.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){log$1.warn({err:t,files:e},`[sync] content conflict callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),log$1.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log$1.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};writeFileSync(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$1.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`?void 0:t.pausedReason;let s=t.inflightConflicts??[];if(s.length>0){for(let e of s)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log$1.warn({err:e},`[sync] failed to load sync state`)}}};const MOUNT_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function createSyncHandshakeSpanExtension(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(isSystemDoc(e)||isConfigDoc(e))return;let s=t?.get(`mountId`)??void 0,g={"doc.name":e};s!==void 0&&MOUNT_ID_PATTERN.test(s)&&(g[`mount.id`]=s);try{withSpanSync(`sync.handshake`,{attributes:g},()=>{})}catch(e){console.warn(`[sync-handshake-span] emission failed:`,e instanceof Error?e:String(e))}}}}const TAG_VALUE_RE=createTagInTextRegex();function createEmptyState(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function stripInlineCodeSpans(e){return e.replace(/`[^`]*`/g,``)}function extractInlineTagsFromBody(e){let t=e.replaceAll(`\r
|
|
2826
2825
|
`,`
|
|
2827
2826
|
`).split(`
|
|
2828
|
-
`),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let s of t){let t=this.state.byTag.get(s);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(s))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,s){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,s)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let s=[];for(let g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].sort((e,t)=>e.localeCompare(t))})}return s.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),s=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&s.add(e.slice(0,t));let g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:s}of e)try{let e=readFileSync(s,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.size===0&&this.state.byTag.delete(t))}for(let t of s){let s=this.state.byTag.get(t);s||(s=new Set,this.state.byTag.set(t,s)),s.add(e)}s.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,s),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let s;try{s=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=relative(this.contentDir,s);this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),filePath:s})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function buildSyncCredentialArgs(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(shellEscape).join(` `)} auth git-credential`]}function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1,singleDocRelPath:ee,ephemeral:J=!1}=e,Y=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}function ne(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function ae(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}initTelemetry();let oe=randomUUID(),se=getLocalDir(s);if(acquireServerLock(se,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:se,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(se),e}let ce=createBasenameIndex(),ue=(e,t)=>ce.resolveEmbed(e,t),de=(e,s)=>{let g=ce.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g),w=resolve(t);if(S!==w&&!S.startsWith(`${w}/`))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},fe,me,ge,_e,ve,ye,Ce,we=null,Te=null,De=null,je=null,Me=ne(),Pe=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ne();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:Me.enabled,providerFingerprint:ae(Me)}),Ie=null,Re=new Set,ze=!1,Be,Ve,Ue,We=new Promise((e,t)=>{Ve=e,Ue=t});function Ge(e){we?.signal(e)}let Ke=2e3,Xe=null;function $e(){Xe!==null&&clearTimeout(Xe),Xe=setTimeout(()=>{Xe=null,me.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let nt=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),rt=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||nt.setRenamed(e,t)},it=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(nt.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}nt.setDeleted(e)}},at=e=>{isSystemDoc(e)||isConfigDoc(e)||nt.delete(e)};try{fe=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{me.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{ge.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let{prunedFiles:e,prunedFolders:t}=reconcileFileIndexAfterFilterRebuild(Ut),s=e+t;s>0?getLogger(`server-factory`).info({pruned:s,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)}}}),me=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:fe}),ge=new TagIndex({contentDir:t,contentFilter:fe});try{ge.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}_e={current:F},ve=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:_e,ephemeral:J,contentRoot:L,backlinkIndex:me,configHomedirOverride:k,getCurrentBranch:()=>Wt?.getLastKnownBranch()??null,resolveEmbed:ue,resolveSize:de,getPrincipal:()=>Ie,onAgentCommit:()=>we?.signal(`session-activity`),onDiskFlush:(e,t,s,g)=>{we?.emitDiskAck(e,t),!(isSystemDoc(e)||isConfigDoc(e))&&assetReferencesChanged(g,s)&&(je?.(),Ge(`files`))},onConfigRejected:(e,t)=>we?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),ye=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[ve.extension]});let B=ye.shouldUnloadDocument.bind(ye);ye.shouldUnloadDocument=e=>{if(Re.has(e)||ze&&B(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},Be=async e=>{Re.add(e);try{await ye.unloadDocument(e)}finally{Re.delete(e)}},we=new CC1Broadcaster(ye),Te=new AgentFocusBroadcaster(ye),De=new AgentPresenceBroadcaster(ye),Ce=new AgentSessionManager(ye);let q=createLiveDerivedIndexExtension({backlinkIndex:me,tagIndex:ge,signalChannel:Ge});ye.configuration.extensions.push(q),ye.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==oe)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${oe}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(Ie&&s.principalId===Ie.id?E.principalId=Ie.id:Ie?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Ie.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),ye.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,s=t.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s))throw Error(`config-doc admission requires loopback peer (peer=${s}, doc=${e.documentName})`);let g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}});let Y=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(Y,`${e}${getDocExtension(e)}`);return!t.startsWith(`${Y}/`)&&t!==Y?null:t}ye.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:nt,resolveFilePath:te,fileExists:existsSync})}}),ye.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>ye.documents.get(e)})}}),ye.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let ne=createApiExtension({hocuspocus:ye,sessionManager:Ce,contentDir:t,contentFilter:fe,serverInstanceId:oe,getFileIndex:()=>Ut?Ut.getFileIndex():new Map,getFolderIndex:()=>Ut?Ut.getFolderIndex():new Map,getAliasMap:()=>Ut?Ut.getAliasMap():new Map,rescanFiles:()=>Ut?.rescanFromDisk(),enableTestRoutes:j,shadowRef:_e,flushGitCommit:()=>ve.flushPendingGitCommit(),flushContributors:()=>ve.flushContributors(),takeStoreFailure:e=>ve.takeStoreFailure(e),takeStoreDivergence:e=>ve.takeStoreDivergence(e),markAgentWriteStore:e=>ve.markAgentWriteStore(e),getCurrentBranch:()=>Wt?.getLastKnownBranch()??null,getDiskAckSVs:()=>we?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:me,tagIndex:ge,signalChannel:Ge,agentFocusBroadcaster:Te,agentPresenceBroadcaster:De,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Kt,localOpCliArgs:H,projectDir:s,resolveEmbed:ue,getPrincipal:()=>Ie,forceUnloadDocument:Be,ready:We,recentlyRemovedDocs:nt,serializeDoc:Dt,semanticSearch:Pe,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{je=e}});ye.configuration.extensions.push(ne),ye.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:_e,contentRoot:L,getCurrentBranch:()=>Wt?.getLastKnownBranch()??null,resolveEmbed:ue,resolveSize:de})),ye.configuration.extensions.push(createSyncHandshakeSpanExtension()),ye.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>Kt,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(se),e}let st=null,vt=new Map,Tt=[];function Et(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return g.startsWith(`${s}/`)?g:null}function Dt(e){let t=ye.documents.get(e);if(!t)return null;let{frontmatter:s,body:g}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(s,g)}let jt=(e,t)=>applyExternalChange(ye,e,t,ue,de);function Mt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Ft=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of ye.documents){if(isSystemDoc(s)||isConfigDoc(s))continue;let g=ye.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,ue,s)},FILE_WATCHER_ORIGIN)}catch(t){Y.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},It=null,Lt=e=>{e&&(It===null&&(It=new Set,setImmediate(()=>{let e=It;if(It=null,e)try{for(let t of e)Ft(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),It.add(e))};function Rt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function zt(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),me.updateDocumentFromMarkdown(e.docName,e.content),$e(),ge.updateDocumentFromMarkdown(e.docName,e.content),Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`),at(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=ye.documents.get(t);if(!g){me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`);return}let S=getReconciledBase(t)??``,w=Dt(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(Y.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:Mt(g),me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`);break;case`clean`:try{jt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Mt(g),me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Mt(g)}break;case`merged`:try{jt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Mt(g),me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Mt(g)}break;case`conflicts`:try{jt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}{let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,E.reason);break}}break}case`delete`:{let{docName:t}=e,s=ye.documents.get(t);if(!s){me.deleteDocument(t),$e(),ge.deleteDocument(t),Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`),it(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=Dt(t)??``,w=S!==g;if(w&&_e.current){let e=_e.current,s=Wt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{Y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),me.deleteDocument(t),$e(),ge.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),ye.closeConnections(t),await Be(s),Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`),it(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:s,content:g}=e,S=ye.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),me.renameDocument(t,s,g),$e(),ge.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}Y.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`),rt(t,s),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:s,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,s=ye.documents.get(t);if(!s)return;let g=Dt(t);g===null?Y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,g);let S=s.getMap(`lifecycle`);S.set(`status`,`conflict`),S.set(`reason`,`conflict-markers`),Y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ce.add(e.relativePath),Ge(`files`),Lt(basename(e.relativePath));break;case`asset-delete`:ce.remove(e.relativePath),Ge(`files`),Lt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:Ge(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Rt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let Bt=[];async function Vt(e){if(isBatchInProgress()){Bt.push(e);return}await zt(e)}async function Ht(){let e=Bt.splice(0,Bt.length);for(let t of e)await zt(t)}let Ut=null,Wt=null,Kt=null,$t=null;async function en(e){if(ye.documents.size===0)return;let t=!1,s=new Promise(e=>{ye.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(ye.documents.keys());ye.closeConnections(),ye.flushPendingStores();for(let e of ye.documents.values())e.getConnectionsCount()===0&&ye.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let S,w=new Promise((s,w)=>{S=setTimeout(()=>{t=!0;let s=Array.from(ye.documents.keys()),S=[],E=[];if(_e.current){for(let e of s)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=Dt(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Et(_e.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:_e.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),Y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),Y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else Y.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function jr(){return $t||($t=(async()=>{let e=Date.now(),t=[];ze=!0,Xe!==null&&(clearTimeout(Xe),Xe=null);let g,S=await Promise.race([We.then(()=>`completed`,e=>(Y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&Y.warn({},`[server] init did not complete within 5s during shutdown`);let w=ye.documents.size;try{try{try{Wt&&=(await Wt.unsubscribe(),null),Ut&&=(await Ut.unsubscribe(),null);for(let{docName:e,cleanup:t}of Tt)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Tt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{we?.destroy(),De?.destroy(),st&&=(await st.disconnect(),null);for(let[e,t]of vt)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}vt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await Ce.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await en(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ve.flushPendingGitCommit(),await ve.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Kt&&=(await Kt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(_e.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(_e.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(_e.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?Y.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):Y.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(se)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),$t)}let Mr=[];async function Fr(){try{Ie=await loadPrincipal(s),Y.info({principalId:Ie.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!_e.current)try{_e.current=await initShadowRepo(s),Y.info({gitDir:_e.current.gitDir},`[server] history repo initialized at ${_e.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Mr.push(`shadow-repo`)}if(_e.current){let e=null;try{e=loadRenameLogIndex(_e.current.gitDir),sweepLazyPopOrphans(_e.current.gitDir,e),setRenameLogIndex(_e.current.gitDir,e),Y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){Y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(_e.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){Y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(_e.current)try{await shadowGit(_e.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){Y.warn({},`[server] history repo appears corrupted — reinitializing`);try{_e.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),_e.current=void 0,Mr.includes(`shadow-repo`)||Mr.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(_e.current)try{let e=resolve(_e.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==t){let e=`main`;try{let t=(await esm_default({baseDir:s,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}Y.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(_e.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){Y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else Y.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){Y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){Y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,s);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,s=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;Y.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){Y.error({err:e},`[server] managed rename recovery failed`),Mr.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&Y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){Y.error({err:e},`[server] upload-tempfile sweep failed`),Mr.push(`upload-tempfile-sweep`)}try{st=await ye.openDirectConnection(SYSTEM_DOC_NAME),we?.emitServerInfo(oe,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Mr.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await ye.openDirectConnection(e);vt.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Mr.push(`config-doc:${e}`)}let S=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,s)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,s)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,s,k)]]);for(let e of g){let t=S.get(e);if(t)try{Y.info({docName:e,path:t},`[config-file-watcher] starting`);let s=await startConfigFileWatcher(t,t=>{let s=ye.documents.get(e);Y.info({docName:e,hasDocument:s!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,e,t,ve.configPersistenceCtx);if(Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),e===`__config__/project`||e===`__local__/project`){let e=te();Kt?.setEnabled(e).catch(t=>{Y.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}let S=ne();Pe.applyConfig({enabled:S.enabled,providerFingerprint:ae(S)})});Tt.push({docName:e,cleanup:s}),Y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(s){Y.warn({err:s,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Mr.push(`config-file-watcher:${e}`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:s,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(s,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(S=t)}}catch{}let w=S?[e,g,S]:[e,g],E=Y;E.info({okignorePath:e,gitignorePath:g,gitInfoExcludePath:S,ephemeral:J},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let D=J?null:await startMultiPathConfigFileWatcher(w,(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(ye.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,ve.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(s,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let S=await fe.rebuildIgnorePatterns();if(S.ok)E.info({changedPath:relative(s,t),patternCount:S.patternCount,nestedFileCount:S.nestedFileCount,durationMs:S.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),we?.signal(`files`);else{let e=relative(s,t)||`.`;E.warn({changedPath:e,error:S.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),we?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(Tt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`))}catch(e){Y.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Mr.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),me.switchBranch(E);try{{let e=getActiveBranch();try{if(await me.loadFromDisk(e)){let t=await me.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await me.rebuildFromDisk(e);me.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){Y.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Ut=await startWatcher(t,Vt,fe),ge.init();let e=0;try{ee===void 0?seedBasenameIndex({contentDir:t,contentFilter:fe,basenameIndex:ce,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during seed (${t}${s?` ${s}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:ce,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during single-file seed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Mr.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Mr.push(`basename-index`)}}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Mr.push(`file-watcher`)}try{Wt=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),ye.flushPendingStores(),await ve.flushPendingGitCommit(),setBatchInProgress(!0),_e.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of ye.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let s=null;if(t.transact(()=>{s=Dt(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(_e.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),Y.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){Y.error({err:e},`[shadow] park failed`)}}},async e=>{let s=Bt.length,g=e.newBranch??`main`;if(Y.info({kind:e.batchKind,headMoved:e.headMoved,docs:s,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${s}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Ht(),await ve.flushDeferredStores(`within-branch`),Kt!==null)try{await Kt.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Bt.splice(0,Bt.length),switchReconciledBaseScope(g),Xe!==null&&(clearTimeout(Xe),Xe=null),me.switchBranch(g),fe.rebuildDirCount();try{let e=0;ce.clear(),seedBasenameIndex({contentDir:t,contentFilter:fe,basenameIndex:ce,onSkip:(t,s,S)=>{e++,Y.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e,branch:g},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Mr.includes(`basename-index-partial`)||Mr.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of ye.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=Dt(e)??``;if(S!==t&&_e.current){let t=_e.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:g,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{Y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Y.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);jt(e,w),setReconciledBase(e,w),Y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){Y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}Y.info({branch:g,docCount:ye.documents.size},`[branch-switch] loaded branch ${g} (${ye.documents.size} docs)`);try{if(await me.loadFromDisk(g)){let e=await me.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await me.rebuildFromDisk(g);me.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){Y.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(ge.init(),_e.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of ye.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let s=await readParkedState(_e.current,g,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let S=getReconciledBase(t);if(!S)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:S});switch(w.kind){case`merged`:case`clean`:jt(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:jt(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=ye.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){Y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&Y.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&_e.current)try{let t=shadowGit(_e.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
|
|
2829
|
-
`))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ve.flushDeferredStores(`discard-stale`),we?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&_e.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(_e.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Mr.push(`head-watcher`)}function D(e){for(let g of e)try{let e=relative(t,join(s,g));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=ye.documents.get(S);if(!w)continue;let E=Dt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let O=buildSyncCredentialArgs(H);try{Kt=new SyncEngine({projectDir:s,contentDir:t,contentFilter:fe,contentRoot:L,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:we,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||ve.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:D,onAutoDisable:async e=>{Y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||Y.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Kt.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Kt=null}Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}return Fr().then(Ve,Ue),{hocuspocus:ye,sessionManager:Ce,cc1Broadcaster:we,agentFocusBroadcaster:Te,agentPresenceBroadcaster:De,contentFilter:fe,basenameIndex:ce,serverInstanceId:oe,destroy:jr,ready:We,degraded:Mr,lockDir:se,get syncEngine(){return Kt}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){let t=resolveLocalSinkConfig({projectDir:e.projectDir??e.contentDir});if(t){let e=t.telemetry.attributeDenylist,s=[];for(let t of e){s.push(t);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)s.push(`${`*.`.repeat(e)}${t}`)}loggerFactory.configure({pinoConfig:{fileSink:t.logs,redactPaths:s}})}initTelemetry({localSink:t?.telemetry}),installServerMemoryGauge();let{kind:s,gitdir:g}=computeWorktreeAttributes(e.projectDir??e.contentDir),S={"ok.worktree.kind":s};return g!==null&&(S[`ok.worktree.gitdir`]=normalizeFsPath(g)),withSpan(`ok.boot`,{attributes:S},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-CyhBidkz-C2yQNfyA.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe}=H,se=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ce=e.port??0,ue=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${se}:${ce}`,log:S}),de=D();de.headersTimeout=3e4,de.requestTimeout=6e4;let fe=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,me=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),me=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let ge=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,_e=mountMcpAndApi({httpServer:de,hocuspocus:q,mcpHttpHandler:ue,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:fe,reactShellMiddleware:ge,ephemeral:e.ephemeral}),ve=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ye=null;g!==null&&(ye=attachIdleShutdown({httpServer:de,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ve()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);de.once(`error`,g),de.listen(e.port,e.host,()=>{de.removeListener(`error`,g),t()})})}catch(e){if(me)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let Ce=de.address(),we=typeof Ce==`object`&&Ce?Ce.port:e.port??0;if(ce=we,O(te,we),me&&updateUiLockPort(te,we),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let Te=!1,De=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};return ve=async()=>{if(Te)return;Te=!0;let e=[],t=async(t,s)=>{try{await De(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{ye?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>_e.shutdown()),ue!==void 0&&await t(`mcpHttpHandler.close`,()=>ue.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{_e.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{de.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{de.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>ee()),me&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:de,destroy:ve,lockDir:te,contentDir:e.contentDir,port:we,ready:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
|
|
2830
|
-
`).map(e=>e.trim()).filter(Boolean):[])}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!
|
|
2827
|
+
`),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();initChain=Promise.resolve();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let s of t){let t=this.state.byTag.get(s);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(s))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,s){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,s)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let s=[];for(let g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].sort((e,t)=>e.localeCompare(t))})}return s.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),s=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&s.add(e.slice(0,t));let g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){let e=this.initChain.then(()=>this.initOnce());return this.initChain=e.catch(e=>{console.warn(`[tag-index] init failed (chain cleared for next init):`,e)}),e}async initOnce(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=await this.listDocsWithPaths(),t=50;for(let t=0;t<e.length;t+=50){let s=e.slice(t,t+50),g=await Promise.all(s.map(async({docName:e,filePath:t})=>{try{return{docName:e,markdown:await readFile$1(t,`utf-8`)}}catch(t){return console.warn(`[tag-index] Failed to read ${e} during init:`,t),null}}));for(let e of g)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown)}catch(t){console.warn(`[tag-index] Failed to index ${e.docName} during init:`,t)}}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.size===0&&this.state.byTag.delete(t))}for(let t of s){let s=this.state.byTag.get(t);s||(s=new Set,this.state.byTag.set(t,s)),s.add(e)}s.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,s),this.state.byDocLiteral.set(e,t))}async listDocsWithPaths(){let e=[];await this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}async walkContentDir(e,t){let s;try{s=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=relative(this.contentDir,s);this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),filePath:s})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function buildSyncCredentialArgs(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(shellEscape).join(` `)} auth git-credential`]}function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1,singleDocRelPath:ee,ephemeral:J=!1}=e,Y=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}function ne(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function ae(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}initTelemetry();let oe=randomUUID(),se=getLocalDir(s);if(acquireServerLock(se,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:se,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(se),e}let ce=createBasenameIndex(),ue=(e,t)=>ce.resolveEmbed(e,t),de=(e,s)=>{let g=ce.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g),w=resolve(t);if(S!==w&&!S.startsWith(`${w}/`))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},fe,me,ge,_e,ve,ye,Ce,we=null,Te=null,De=null,je=null,Me=ne(),Pe=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ne();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:Me.enabled,providerFingerprint:ae(Me)}),Ie=null,Re=new Set,ze=!1,Be,Ve,Ue,We=new Promise((e,t)=>{Ve=e,Ue=t});function Ge(e){we?.signal(e)}let Ke=2e3,Xe=null;function $e(){Xe!==null&&clearTimeout(Xe),Xe=setTimeout(()=>{Xe=null,me.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let nt=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),rt=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||nt.setRenamed(e,t)},it=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(nt.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}nt.setDeleted(e)}},at=e=>{isSystemDoc(e)||isConfigDoc(e)||nt.delete(e)};try{fe=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{me.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),ge.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),reconcileFileIndexAfterFilterRebuild(Ut).then(({prunedFiles:e,prunedFolders:t})=>{let s=e+t;s>0?getLogger(`server-factory`).info({pruned:s,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),me=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:fe}),ge=new TagIndex({contentDir:t,contentFilter:fe}),ge.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),_e={current:F},ve=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:_e,ephemeral:J,contentRoot:L,backlinkIndex:me,configHomedirOverride:k,getCurrentBranch:()=>Wt?.getLastKnownBranch()??null,resolveEmbed:ue,resolveSize:de,getPrincipal:()=>Ie,onAgentCommit:()=>we?.signal(`session-activity`),onDiskFlush:(e,t,s,g)=>{we?.emitDiskAck(e,t),!(isSystemDoc(e)||isConfigDoc(e))&&assetReferencesChanged(g,s)&&(je?.(),Ge(`files`))},onConfigRejected:(e,t)=>we?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),ye=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[ve.extension]});let B=ye.shouldUnloadDocument.bind(ye);ye.shouldUnloadDocument=e=>{if(Re.has(e)||ze&&B(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},Be=async e=>{Re.add(e);try{await ye.unloadDocument(e)}finally{Re.delete(e)}},we=new CC1Broadcaster(ye),Te=new AgentFocusBroadcaster(ye),De=new AgentPresenceBroadcaster(ye),Ce=new AgentSessionManager(ye);let q=createLiveDerivedIndexExtension({backlinkIndex:me,tagIndex:ge,signalChannel:Ge});ye.configuration.extensions.push(q),ye.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==oe)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${oe}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(Ie&&s.principalId===Ie.id?E.principalId=Ie.id:Ie?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Ie.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),ye.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,s=t.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s))throw Error(`config-doc admission requires loopback peer (peer=${s}, doc=${e.documentName})`);let g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}});let Y=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(Y,`${e}${getDocExtension(e)}`);return!t.startsWith(`${Y}/`)&&t!==Y?null:t}ye.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:nt,resolveFilePath:te,fileExists:existsSync})}}),ye.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>ye.documents.get(e)})}}),ye.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let ne=createApiExtension({hocuspocus:ye,sessionManager:Ce,contentDir:t,contentFilter:fe,serverInstanceId:oe,getFileIndex:()=>Ut?Ut.getFileIndex():new Map,getFolderIndex:()=>Ut?Ut.getFolderIndex():new Map,getAliasMap:()=>Ut?Ut.getAliasMap():new Map,rescanFiles:()=>Ut?.rescanFromDisk(),enableTestRoutes:j,shadowRef:_e,flushGitCommit:()=>ve.flushPendingGitCommit(),flushContributors:()=>ve.flushContributors(),takeStoreFailure:e=>ve.takeStoreFailure(e),takeStoreDivergence:e=>ve.takeStoreDivergence(e),markAgentWriteStore:e=>ve.markAgentWriteStore(e),getCurrentBranch:()=>Wt?.getLastKnownBranch()??null,getDiskAckSVs:()=>we?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:me,tagIndex:ge,signalChannel:Ge,agentFocusBroadcaster:Te,agentPresenceBroadcaster:De,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Kt,localOpCliArgs:H,projectDir:s,resolveEmbed:ue,getPrincipal:()=>Ie,forceUnloadDocument:Be,ready:We,recentlyRemovedDocs:nt,serializeDoc:Dt,semanticSearch:Pe,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{je=e}});ye.configuration.extensions.push(ne),ye.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:_e,contentRoot:L,getCurrentBranch:()=>Wt?.getLastKnownBranch()??null,resolveEmbed:ue,resolveSize:de})),ye.configuration.extensions.push(createSyncHandshakeSpanExtension()),ye.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>Kt,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(se),e}let st=null,vt=new Map,Tt=[];function Et(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return g.startsWith(`${s}/`)?g:null}function Dt(e){let t=ye.documents.get(e);if(!t)return null;let{frontmatter:s,body:g}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(s,g)}let jt=(e,t)=>applyExternalChange(ye,e,t,ue,de);function Mt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Ft=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of ye.documents){if(isSystemDoc(s)||isConfigDoc(s))continue;let g=ye.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,ue,s)},FILE_WATCHER_ORIGIN)}catch(t){Y.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},It=null,Lt=e=>{e&&(It===null&&(It=new Set,setImmediate(()=>{let e=It;if(It=null,e)try{for(let t of e)Ft(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),It.add(e))};function Rt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function zt(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),me.updateDocumentFromMarkdown(e.docName,e.content),$e(),ge.updateDocumentFromMarkdown(e.docName,e.content),Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`),at(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=ye.documents.get(t);if(!g){me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`);return}let S=getReconciledBase(t)??``,w=Dt(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(Y.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:Mt(g),me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`);break;case`clean`:try{jt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Mt(g),me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Mt(g)}break;case`merged`:try{jt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Mt(g),me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Mt(g)}break;case`conflicts`:try{jt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}{let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,E.reason);break}}break}case`delete`:{let{docName:t}=e,s=ye.documents.get(t);if(!s){me.deleteDocument(t),$e(),ge.deleteDocument(t),Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`),it(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=Dt(t)??``,w=S!==g;if(w&&_e.current){let e=_e.current,s=Wt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{Y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),me.deleteDocument(t),$e(),ge.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),ye.closeConnections(t),await Be(s),Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`),it(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:s,content:g}=e,S=ye.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),me.renameDocument(t,s,g),$e(),ge.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}Y.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`),rt(t,s),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:s,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,s=ye.documents.get(t);if(!s)return;let g=Dt(t);g===null?Y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,g);let S=s.getMap(`lifecycle`);S.set(`status`,`conflict`),S.set(`reason`,`conflict-markers`),Y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ce.add(e.relativePath),Ge(`files`),Lt(basename(e.relativePath));break;case`asset-delete`:ce.remove(e.relativePath),Ge(`files`),Lt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:Ge(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Rt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let Bt=[];async function Vt(e){if(isBatchInProgress()){Bt.push(e);return}await zt(e)}async function Ht(){let e=Bt.splice(0,Bt.length);for(let t of e)await zt(t)}let Ut=null,Wt=null,Kt=null,$t=null;async function en(e){if(ye.documents.size===0)return;let t=!1,s=new Promise(e=>{ye.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(ye.documents.keys());ye.closeConnections(),ye.flushPendingStores();for(let e of ye.documents.values())e.getConnectionsCount()===0&&ye.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let S,w=new Promise((s,w)=>{S=setTimeout(()=>{t=!0;let s=Array.from(ye.documents.keys()),S=[],E=[];if(_e.current){for(let e of s)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=Dt(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Et(_e.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:_e.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),Y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),Y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else Y.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function jr(){return $t||($t=(async()=>{let e=Date.now(),t=[];ze=!0,Xe!==null&&(clearTimeout(Xe),Xe=null);let g,S=await Promise.race([We.then(()=>`completed`,e=>(Y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&Y.warn({},`[server] init did not complete within 5s during shutdown`);let w=ye.documents.size;try{try{try{Wt&&=(await Wt.unsubscribe(),null),Ut&&=(await Ut.unsubscribe(),null);for(let{docName:e,cleanup:t}of Tt)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Tt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{we?.destroy(),De?.destroy(),st&&=(await st.disconnect(),null);for(let[e,t]of vt)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}vt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await Ce.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await en(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ve.flushPendingGitCommit(),await ve.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Kt&&=(await Kt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(_e.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(_e.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(_e.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?Y.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):Y.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(se)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),$t)}let Mr=[];async function Fr(){try{Ie=await loadPrincipal(s),Y.info({principalId:Ie.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!_e.current)try{_e.current=await initShadowRepo(s),Y.info({gitDir:_e.current.gitDir},`[server] history repo initialized at ${_e.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Mr.push(`shadow-repo`)}if(_e.current){let e=null;try{e=loadRenameLogIndex(_e.current.gitDir),sweepLazyPopOrphans(_e.current.gitDir,e),setRenameLogIndex(_e.current.gitDir,e),Y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){Y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(_e.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){Y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(_e.current)try{await shadowGit(_e.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){Y.warn({},`[server] history repo appears corrupted — reinitializing`);try{_e.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),_e.current=void 0,Mr.includes(`shadow-repo`)||Mr.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(_e.current)try{let e=resolve(_e.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==t){let e=`main`;try{let t=(await esm_default({baseDir:s,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}Y.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(_e.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){Y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else Y.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){Y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){Y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,s);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,s=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;Y.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){Y.error({err:e},`[server] managed rename recovery failed`),Mr.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&Y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){Y.error({err:e},`[server] upload-tempfile sweep failed`),Mr.push(`upload-tempfile-sweep`)}try{st=await ye.openDirectConnection(SYSTEM_DOC_NAME),we?.emitServerInfo(oe,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Mr.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await ye.openDirectConnection(e);vt.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Mr.push(`config-doc:${e}`)}let S=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,s)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,s)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,s,k)]]);for(let e of g){let t=S.get(e);if(t)try{Y.info({docName:e,path:t},`[config-file-watcher] starting`);let s=await startConfigFileWatcher(t,t=>{let s=ye.documents.get(e);Y.info({docName:e,hasDocument:s!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,e,t,ve.configPersistenceCtx);if(Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),e===`__config__/project`||e===`__local__/project`){let e=te();Kt?.setEnabled(e).catch(t=>{Y.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}let S=ne();Pe.applyConfig({enabled:S.enabled,providerFingerprint:ae(S)})});Tt.push({docName:e,cleanup:s}),Y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(s){Y.warn({err:s,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Mr.push(`config-file-watcher:${e}`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:s,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(s,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(S=t)}}catch{}let w=S?[e,g,S]:[e,g],E=Y;E.info({okignorePath:e,gitignorePath:g,gitInfoExcludePath:S,ephemeral:J},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let D=J?null:await startMultiPathConfigFileWatcher(w,(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(ye.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,ve.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(s,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let S=await fe.rebuildIgnorePatterns();if(S.ok)E.info({changedPath:relative(s,t),patternCount:S.patternCount,nestedFileCount:S.nestedFileCount,durationMs:S.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),we?.signal(`files`);else{let e=relative(s,t)||`.`;E.warn({changedPath:e,error:S.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),we?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(Tt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`))}catch(e){Y.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Mr.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),me.switchBranch(E);try{{let e=getActiveBranch();try{if(await me.loadFromDisk(e)){let t=await me.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await me.rebuildFromDisk(e);me.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){Y.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Ut=await startWatcher(t,Vt,fe);try{await ge.init()}catch(e){Y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Mr.push(`tag-index`)}let e=0;try{ee===void 0?await seedBasenameIndex({contentDir:t,contentFilter:fe,basenameIndex:ce,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during seed (${t}${s?` ${s}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:ce,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during single-file seed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Mr.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Mr.push(`basename-index`)}}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Mr.push(`file-watcher`)}try{Wt=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),ye.flushPendingStores(),await ve.flushPendingGitCommit(),setBatchInProgress(!0),_e.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of ye.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let s=null;if(t.transact(()=>{s=Dt(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(_e.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),Y.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){Y.error({err:e},`[shadow] park failed`)}}},async e=>{let s=Bt.length,g=e.newBranch??`main`;if(Y.info({kind:e.batchKind,headMoved:e.headMoved,docs:s,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${s}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Ht(),await ve.flushDeferredStores(`within-branch`),Kt!==null)try{await Kt.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Bt.splice(0,Bt.length),switchReconciledBaseScope(g),Xe!==null&&(clearTimeout(Xe),Xe=null),me.switchBranch(g),fe.rebuildDirCount();try{let e=0;ce.clear(),await seedBasenameIndex({contentDir:t,contentFilter:fe,basenameIndex:ce,onSkip:(t,s,S)=>{e++,Y.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e,branch:g},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Mr.includes(`basename-index-partial`)||Mr.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of ye.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=Dt(e)??``;if(S!==t&&_e.current){let t=_e.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:g,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{Y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Y.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);jt(e,w),setReconciledBase(e,w),Y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){Y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}Y.info({branch:g,docCount:ye.documents.size},`[branch-switch] loaded branch ${g} (${ye.documents.size} docs)`);try{if(await me.loadFromDisk(g)){let e=await me.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await me.rebuildFromDisk(g);me.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){Y.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await ge.init(),_e.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of ye.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let s=await readParkedState(_e.current,g,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let S=getReconciledBase(t);if(!S)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:S});switch(w.kind){case`merged`:case`clean`:jt(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:jt(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=ye.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){Y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&Y.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&_e.current)try{let t=shadowGit(_e.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
|
|
2828
|
+
`))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ve.flushDeferredStores(`discard-stale`),we?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&_e.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(_e.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Mr.push(`head-watcher`)}function D(e){for(let g of e)try{let e=relative(t,join(s,g));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=ye.documents.get(S);if(!w)continue;let E=Dt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let O=buildSyncCredentialArgs(H);try{Kt=new SyncEngine({projectDir:s,contentDir:t,contentFilter:fe,contentRoot:L,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:we,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||ve.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:D,onAutoDisable:async e=>{Y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||Y.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Kt.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Kt=null}Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}return Fr().then(Ve,Ue),{hocuspocus:ye,sessionManager:Ce,cc1Broadcaster:we,agentFocusBroadcaster:Te,agentPresenceBroadcaster:De,contentFilter:fe,basenameIndex:ce,serverInstanceId:oe,destroy:jr,ready:We,degraded:Mr,lockDir:se,get syncEngine(){return Kt}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){let t=resolveLocalSinkConfig({projectDir:e.projectDir??e.contentDir});if(t){let e=t.telemetry.attributeDenylist,s=[];for(let t of e){s.push(t);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)s.push(`${`*.`.repeat(e)}${t}`)}loggerFactory.configure({pinoConfig:{fileSink:t.logs,redactPaths:s}})}initTelemetry({localSink:t?.telemetry}),installServerMemoryGauge();let{kind:s,gitdir:g}=computeWorktreeAttributes(e.projectDir??e.contentDir),S={"ok.worktree.kind":s};return g!==null&&(S[`ok.worktree.gitdir`]=normalizeFsPath(g)),withSpan(`ok.boot`,{attributes:S},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-CyhBidkz-CrazWnBM.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe}=H,se=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ce=e.port??0,ue=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${se}:${ce}`,log:S}),de=D();de.headersTimeout=3e4,de.requestTimeout=6e4;let fe=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,me=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),me=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let ge=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,_e=mountMcpAndApi({httpServer:de,hocuspocus:q,mcpHttpHandler:ue,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:fe,reactShellMiddleware:ge,ephemeral:e.ephemeral}),ve=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ye=null;g!==null&&(ye=attachIdleShutdown({httpServer:de,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ve()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);de.once(`error`,g),de.listen(e.port,e.host,()=>{de.removeListener(`error`,g),t()})})}catch(e){if(me)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let Ce=de.address(),we=typeof Ce==`object`&&Ce?Ce.port:e.port??0;if(ce=we,O(te,we),me&&updateUiLockPort(te,we),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let Te=!1,De=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};return ve=async()=>{if(Te)return;Te=!0;let e=[],t=async(t,s)=>{try{await De(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{ye?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>_e.shutdown()),ue!==void 0&&await t(`mcpHttpHandler.close`,()=>ue.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{_e.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{de.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{de.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>ee()),me&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:de,destroy:ve,lockDir:te,contentDir:e.contentDir,port:we,ready:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
|
|
2829
|
+
`).map(e=>e.trim()).filter(Boolean):[])}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let w=``;try{w=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,w);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}var SingleFileNotFoundError=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},SingleFileNotAFileError=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},SingleFileNotMarkdownError=class extends Error{constructor(e){super(`Open Knowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function prepareSingleFileOpen(e){if(!isSupportedDocFile(e))throw new SingleFileNotMarkdownError(e);let t;try{t=realpathSync(resolve(e))}catch(t){throw t.code===`ENOENT`?new SingleFileNotFoundError(e):t}if(!statSync(t).isFile())throw new SingleFileNotAFileError(e);let s=dirname(t),g=findEnclosingProjectRoot(s);if(g){let e=g.rootPath;return{mode:`project`,projectRoot:e,docName:stripDocExtension(relative(resolveProjectContentDir(e),t).split(sep).join(`/`)),canonicalFilePath:t}}let S=basename(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:s,singleDocRelPath:S,docName:stripDocExtension(S)}}function resolveProjectContentDir(e){return resolve(e,readConfigSafely({absPath:resolveConfigPath(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function createEphemeralProjectDir(e){let t=mkdtempSync(resolve(tmpdir(),`ok-ephemeral-`)),s=resolve(t,`.ok`);return mkdirSync(s,{recursive:!0}),writeFileSync(resolve(s,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),writeFileSync(resolve(s,`.gitignore`),`local/
|
|
2831
2830
|
`,`utf-8`),t}export{STATE_MANIFEST_FILENAME as $,loadPrincipal as $n,saveInMemoryCheckpoint as $r,createServerObserverExtension as $t,LOG_MD_TEMPLATE as A,withSpan as Ai,handleSpawnCursor as An,removeLastKnownHash as Ar,clearContributors as At,OK_OKIGNORE_TEMPLATE as B,isJSONRPCRequest as Bi,isAllowedWorkspaceHostHeader as Bn,restoreContributors as Br,createApiExtension as Bt,GitNotAvailableError as C,tracedWriteFile as Ci,getLogFilePath as Cn,readUiLock as Cr,buildInstructions as Ct,HocuspocusAuthTokenSchema as D,validateAgentId as Di,getMetrics as Dn,registerAllTools as Dr,classifyEvents as Dt,HocuspocusAuthRejection as E,updateUiLockPort as Ei,getMeter as En,recordSkillInstallEvent as Er,buildWipTree as Et,MIN_GIT_VERSION as F,writeTracker as Fi,initTelemetry as Fn,resolveCursorSpawnInvocation as Fr,commitWipFromTree as Ft,ROOT_GITIGNORE_TEMPLATE as G,withFileLockSync as Gi,isPairedWriteOrigin as Gn,runAuthStatusSubprocess as Gr,createEphemeralProjectDir as Gt,PinoLogger as H,atomicWriteFileSync as Hi,isHocuspocusAuthRejectionReason as Hn,rewriteMarkdownLinksForDocumentRename as Hr,createContentFilter as Ht,MISSING_OK_CONFIG_MESSAGE as I,McpServer as Ii,installPrettyZodErrors as In,resolveLockDir as Ir,compareSemver as It,STARTER_FOLDERS as J,MalformedGitPointerError as Ji,isSelfWrite as Jn,runWithMcpLogger as Jr,createLiveDerivedIndexExtension as Jt,SERVICE_WRITER as K,writeConfigPatch as Ki,isPathWithinDir as Kn,runCloneSubprocess as Kr,createExternalChangeHandler as Kt,McpLogger as L,JSONRPCMessageSchema as Li,installTestLoggers as Ln,resolvePack as Lr,containsConflictMarkers as Lt,MAX_AGENT_SESSIONS as M,writeRootGitignoreForNewRepo as Mi,incrementServerObserverFire as Mn,resolveBundledSkillDir as Mr,coercePackId as Mt,MCP_CONNECTION_ID_HEADER as N,writeStateManifest as Ni,initContent as Nn,resolveContentDir as Nr,commitUpstreamImport as Nt,INSTALLED_AGENTS_SCHEMES as O,validateCloneInputs as Oi,getTracer as On,registerWrite as Or,classifyFsPath as Ot,MCP_SERVER_NAME as P,writeTargetVersion as Pi,initShadowRepo as Pn,resolveCursorBinaryDefault as Pr,commitWip as Pt,STARTER_TEMPLATES as Q,listStarterPacks as Qn,sanitizeClientName as Qr,createServer$1 as Qt,MissingOkConfigError as R,LATEST_PROTOCOL_VERSION as Ri,installUserSkill as Rn,resolvePackageVersion as Rr,contentHash as Rt,GIT_UPSTREAM_WRITER as S,tracedUnlinkSync as Si,getLocalDir as Sn,readTargetVersion as Sr,buildExecResult as St,HOCUSPOCUS_AUTH_REJECTION_REASONS as T,updateLastKnownHash as Ti,getLogsDir as Tn,recordContributor as Tr,buildStarterFolderFrontmatterYaml as Tt,ProjectGitInitError as U,readConfigSafely as Ui,isKnownPackId as Un,rewriteWikiLinksForDocumentRename as Ur,createContentFilterAsync as Ut,PANE_TARGET_TTL_MS as V,isJSONRPCResultResponse as Vi,isConfigDoc as Vn,restoreLifecycleFromConflictsJson as Vr,createAssetServeMiddleware as Vt,ROLLBACK_ORIGIN as W,resolveConfigPath as Wi,isLoopbackAddress as Wn,runAuthReposSubprocess as Wr,createEmbeddingsSecretStore as Wt,STARTER_PACKS as X,resolveShadowDir as Xi,lastKnownHash as Xn,safeSubdir as Xr,createOsProbe as Xt,STARTER_FOLDER_FRONTMATTER_FILENAME as Y,resolveGitDirDetailed as Yi,isSystemDoc as Yn,safeContentPath as Yr,createMcpHttpHandler as Yt,STARTER_PACK_IDS as Z,listRescueCheckpoints as Zn,safetyCheckpoint as Zr,createPersistenceExtension as Zt,EMBEDDINGS_API_KEY_ENV as _,tracedMkdirSync as _i,formatAuthRejectionWire as _n,readProjectLocalSemanticConfig as _r,assertNeverDiskEvent as _t,AgentPresenceBroadcaster as a,shutdownTelemetry as ai,detectProjectShape as an,normalizeFsPath as ar,StateManifestError as at,FileEmbeddingsBackend as b,tracedRmSync as bi,gcCheckpointRefs as bn,readStateManifest as br,buildAndOpenSkill as bt,BacklinkIndex as c,spawnDetached as ci,encodeFolderRoute as cn,parseGitVersion as cr,__getShowAllWalkStatsForTesting as ct,CONFLICT_MARKER_RE as d,streamingProblemEvent as di,evictStaleTrackerEntries as dn,pathToDocName as dr,applyAgentMarkdownWrite as dt,saveVersion as ei,createStreamingErrorWriter as en,loggerFactory as er,SeedPrerequisiteError as et,CURSOR_BUNDLE_PATHS_BY_PLATFORM as f,swapContributors as fi,extractWikiLinksFromMarkdown as fn,planSeed as fr,applyExternalChange as ft,DEFAULT_PACK_ID as g,tracedMkdir as gi,flushFileLogger as gn,readBranchFromHead as gr,assertGitAvailable as gt,DEFAULT_EMBEDDINGS_DIMENSIONS as h,tracedLinkSync as hi,findEnclosingProjectRoot as hn,readArmedPaneTarget as hr,assertCompatibleStateManifest as ht,AgentFocusBroadcaster as i,shadowGit as ii,detectGit as in,mountMcpAndApi as ir,SingleFileNotMarkdownError as it,MANAGED_RENAME_ORIGIN as j,withSpanSync as ji,incrementCollabSocketFilteredError as jn,resetMetrics as jr,clearEmbeddingsKeyFromAllBackends as jt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as k,validateSkillZip as ki,handleCollabSocketError as kn,releaseUiLock as kr,clearArmedPaneTarget as kt,CC1Broadcaster as l,splitMarkdownBlocks as li,ensureProjectGit as ln,parseHocuspocusAuthToken as lr,__resetShowAllWalkStatsForTesting as lt,DEFAULT_CHECKPOINT_RETENTION as m,tracedAppendFileSync as mi,findEnclosingGitRoot as mn,readAllTargets as mr,armPaneTarget as mt,AGENT_ID_RE as n,serializeError as ni,describeStoredEmbeddingsKey as nn,logsPreviousPath as nr,SingleFileNotAFileError as nt,AgentSessionCapacityError as o,spansCurrentPath as oi,emitPreflightFailureSpan as on,packageVersionMajorMinor as or,TagIndex as ot,ConfigSchema as p,toBroadcasterKey as pi,fallbackPaths as pn,prepareSingleFileOpen as pr,applySeed as pt,SKILL_INSTALL_EVENTS_FILE_REL as q,GitDirAccessError as qi,isProjectRoot as qn,runDeviceFlowSubprocess as qr,createFileLogger as qt,AGENT_WRITE_ORIGIN as r,setActiveSpanAttributes as ri,detectClaudeDesktopPresence as rn,makeLazyEmbeddingsKeyStore as rr,SingleFileNotFoundError as rt,AgentSessionManager as s,spansPreviousPath as si,encodeDocName as sn,parseAuthRejectionWire as sr,UiLockCollisionError as st,AGENT_ID_MAX_LEN as t,seedBasenameIndex as ti,createTestLogger as tn,logsCurrentPath as tr,SeedRootDirError as tt,CONFIG_FILENAME as u,startWatcher as ui,errorResponse as un,parseKeepaliveConnectionId as ur,acquireUiLock as ut,FILE_SYSTEM_WRITER as v,tracedRename as vi,formatContributors as vn,readServerPackageVersion as vr,attachIdleShutdown as vt,GitTooOldError as w,tracedWriteFileSync as wi,getLogger as wn,reconcile as wr,buildSkillZip as wt,GIT_PREFLIGHT_FAIL_SPAN_NAME as x,tracedRmdirSync as xi,getCurrentMcpLogger as xn,readTargetRecordedAt as xr,buildConfigYmlContent as xt,FILE_WATCHER_ORIGIN as y,tracedRenameSync as yi,formatContributorsFrom as yn,readSkillInstallStateSnapshot as yr,bootServer as yt,OBSERVER_SYNC_ORIGIN as z,isInitializedNotification as zi,isAllowedApiOrigin as zn,resolveUiInfo as zr,contributorCount as zt};
|
|
2832
|
-
//# sourceMappingURL=dist-
|
|
2831
|
+
//# sourceMappingURL=dist-9gkYdouR.mjs.map
|